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"
33 /* Maximum line of a HTTP request line. Longer request lines are aborted with
34 * an error. The standard doesn't specify a maximum line length but this
35 * should be a good limit to make processing simpler. */
36 #define MAX_REQUEST_LINE 4096
38 /* Paths to necessary TLS files: the CA and the server key. */
39 #define PROXY_CA_FILE "proxy-ca.pem"
40 #define PROXY_KEY_FILE "proxy-key.pem"
43 static int initialize_tls_session_client(int peer_socket,
45 gnutls_session_t *session,
46 gnutls_certificate_credentials_t *x509_cred);
47 static int initialize_tls_session_server(int peer_socket,
48 gnutls_session_t *session,
49 gnutls_certificate_credentials_t *x509_cred);
51 static int read_http_request(FILE *client_fd, char *request, size_t length);
52 static void send_bad_request(FILE *client_fd);
53 static void send_forwarding_failure(FILE *client_fd);
56 static void transfer_data(int client, int server);
57 static int read_from_write_to(int from, int to);
59 static void transfer_data_tls(int client, int server,
60 gnutls_session_t client_session,
61 gnutls_session_t server_session);
62 static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to);
64 static int connect_to_host(const char *hostname, const char *port);
66 static int parse_request(const char *buffer, char *host, char *port,
70 void handle_connection(int client_socket) {
72 FILE *client_fd, *server_fd;
74 char buffer[MAX_REQUEST_LINE];
75 char host[MAX_REQUEST_LINE];
81 /* client_x509_cred is used when talking to the client (acting as a TSL
82 * server), server_x509_cred is used when talking to the server (acting as
84 gnutls_certificate_credentials_t client_x509_cred, server_x509_cred;
86 gnutls_session_t client_session, server_session;
87 /* initialize_tls_session_*() called? - used for goto out */
88 int client_session_init, server_session_init;
89 /* gnutls_handshake() called? - used for goto out */
90 int client_session_started, server_session_started;
92 LOG(LOG_DEBUG, "new connection");
97 client_session_init = 0;
98 server_session_init = 0;
99 client_session_started = 0;
100 server_session_started = 0;
102 client_fd = fdopen(client_socket, "a+");
103 if (NULL == client_fd) {
104 LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
108 /* Read request line (CONNECT ..) and headers (they are discarded). */
109 result = read_http_request(client_fd, buffer, sizeof(buffer));
112 LOG(LOG_WARNING, "read_http_request(): client read error");
114 } else if (-2 == result) {
116 LOG(LOG_WARNING, "read_http_request(): client EOF");
117 send_bad_request(client_fd);
121 if (0 != parse_request(buffer, host, port, &version_minor)) {
122 LOG(LOG_WARNING, "bad request: %s", buffer);
123 send_bad_request(client_fd);
127 LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
129 /* Connect to proxy server or directly to server. */
130 if (NULL != global_proxy_host && NULL != global_proxy_port) {
131 LOG(LOG_DEBUG, "connecting to %s:%s", global_proxy_host,
133 server_socket = connect_to_host(global_proxy_host, global_proxy_port);
135 LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
136 server_socket = connect_to_host(host, port);
139 if (-1 == server_socket) {
140 LOG(LOG_WARNING, "failed to connect to server");
141 send_forwarding_failure(client_fd);
144 server_fd = fdopen(server_socket, "a+");
145 if (NULL == server_fd) {
146 LOG_PERROR(LOG_WARNING, "fdopen(): server failed");
147 send_forwarding_failure(client_fd);
151 /* Connect to proxy if requested (command line option). */
152 if (NULL != global_proxy_host && NULL != global_proxy_port) {
153 fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
154 fprintf(server_fd, "\r\n");
156 /* Read response line from proxy server. */
157 result = read_http_request(server_fd, buffer, sizeof(buffer));
160 LOG(LOG_WARNING, "read_http_request(): proxy read error");
161 send_forwarding_failure(client_fd);
163 } else if (-2 == result) {
165 LOG(LOG_WARNING, "read_http_request(): proxy EOF");
166 send_forwarding_failure(client_fd);
170 /* Check response of proxy server. */
171 if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
172 LOG(LOG_WARNING, "bad proxy response: %s", buffer);
173 send_forwarding_failure(client_fd);
178 LOG(LOG_DEBUG, "connection to server established");
180 /* We've established a connection, tell the client. */
181 fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
182 fprintf(client_fd, "\r\n");
185 /* Initialize TLS server credentials to talk to the client. */
186 result = initialize_tls_session_client(client_socket, host,
190 LOG(LOG_WARNING, "initialize_tls_session_client() failed");
191 send_forwarding_failure(client_fd);
194 client_session_init = 1;
196 LOG(LOG_DEBUG, "starting client TLS handshake");
198 /* Try to establish TLS handshake between client and us. */
199 result = gnutls_handshake(client_session);
200 if (GNUTLS_E_SUCCESS != result) {
201 LOG(LOG_WARNING, "client TLS handshake failed: %s",
202 gnutls_strerror(result));
203 send_forwarding_failure(client_fd);
206 client_session_started = 1;
208 LOG(LOG_DEBUG, "client TLS handshake finished");
210 result = initialize_tls_session_server(server_socket, &server_session,
212 /* Initialize TLS client credentials to talk to the server. */
214 LOG(LOG_WARNING, "initialize_tls_session_server() failed");
215 send_forwarding_failure(client_fd);
218 server_session_init = 1;
220 LOG(LOG_DEBUG, "starting server TLS handshake");
222 /* Try to establish TLS handshake between us and server. */
223 result = gnutls_handshake(server_session);
224 if (GNUTLS_E_SUCCESS != result) {
225 LOG(LOG_WARNING, "server TLS handshake failed: %s",
226 gnutls_strerror(result));
227 send_forwarding_failure(client_fd);
230 server_session_started = 1;
232 LOG(LOG_DEBUG, "server TLS handshake finished, transferring data");
234 /* FIXME: verify server's fingerprint */
236 /* Proxy data between client and server until one suite is done (EOF or
238 transfer_data_tls(client_socket, server_socket,
239 client_session, server_session);
241 LOG(LOG_DEBUG, "finished transferring data");
244 /* Close TLS sessions if necessary. */
245 if (0 != server_session_started) {
246 gnutls_bye(server_session, GNUTLS_SHUT_WR);
248 if (0 != client_session_started) {
249 gnutls_bye(client_session, GNUTLS_SHUT_WR);
251 if (0 != server_session_init) {
252 gnutls_deinit(server_session);
253 gnutls_certificate_free_credentials(server_x509_cred);
255 if (0 != client_session_init) {
256 gnutls_deinit(client_session);
257 gnutls_certificate_free_cas(client_x509_cred);
258 gnutls_certificate_free_keys(client_x509_cred);
259 gnutls_certificate_free_credentials(client_x509_cred);
262 /* Close connection to server/proxy. */
263 if (NULL != server_fd) {
265 } else if (-1 != server_socket) {
266 close(server_socket);
268 LOG(LOG_DEBUG, "connection to server closed");
269 /* Close connection to client. */
270 if (NULL != client_fd) {
273 close(client_socket);
275 LOG(LOG_DEBUG, "connection to client closed");
277 LOG(LOG_DEBUG, "connection finished");
281 static int initialize_tls_session_client(int peer_socket,
282 const char *hostname,
283 gnutls_session_t *session,
284 gnutls_certificate_credentials_t *x509_cred) {
287 /* The server certificate for the given hostname is stored in
288 * "./certificate-hostname-proxy.pem". */
289 #define PATH_FORMAT "./certificate-%s-proxy.pem"
291 /* Hostname too long. */
292 if (sizeof(path) - strlen(PATH_FORMAT) <= strlen(hostname)) {
294 "initialize_tls_session_client(): hostname too long: '%s'",
298 /* Try to prevent path traversals in hostnames. */
299 if (NULL != strstr(hostname, "..")) {
301 "initialize_tls_session_client(): possible path traversal: '%s'",
305 snprintf(path, sizeof(path), PATH_FORMAT, hostname);
308 result = gnutls_certificate_allocate_credentials(x509_cred);
309 if (GNUTLS_E_SUCCESS != result) {
311 "initialize_tls_session_client(): \
312 gnutls_certificate_allocate_credentials(): %s",
313 gnutls_strerror(result));
317 /* Load proxy CA file, this CA "list" is send to the client. */
318 result = gnutls_certificate_set_x509_trust_file(*x509_cred,
320 GNUTLS_X509_FMT_PEM);
323 "initialize_tls_session_client(): can't read CA file: '%s'",
327 /* And certificate for this website and proxy's private key. */
328 result = gnutls_certificate_set_x509_key_file(*x509_cred,
329 path, PROXY_KEY_FILE,
330 GNUTLS_X509_FMT_PEM);
331 if (GNUTLS_E_SUCCESS != result) {
333 "initialize_tls_session_client(): \
334 can't read server certificate ('%s') or key file ('%s'): %s",
335 path, PROXY_KEY_FILE, gnutls_strerror(result));
336 /* Could be a missing certificate. */
340 gnutls_certificate_set_dh_params(*x509_cred, tls_dh_params);
342 result = gnutls_init(session, GNUTLS_SERVER);
343 if (GNUTLS_E_SUCCESS != result) {
345 "initialize_tls_session_client(): gnutls_init(): %s",
346 gnutls_strerror(result));
349 result = gnutls_priority_set(*session, tls_priority_cache);
350 if (GNUTLS_E_SUCCESS != result) {
352 "initialize_tls_session_client(): gnutls_priority_set(): %s",
353 gnutls_strerror(result));
356 result = gnutls_credentials_set(*session,
357 GNUTLS_CRD_CERTIFICATE, *x509_cred);
358 if (GNUTLS_E_SUCCESS != result) {
360 "initialize_tls_session_client(): gnutls_credentials_set(): %s",
361 gnutls_strerror(result));
365 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
369 static int initialize_tls_session_server(int peer_socket,
370 gnutls_session_t *session,
371 gnutls_certificate_credentials_t *x509_cred) {
374 result = gnutls_certificate_allocate_credentials(x509_cred);
375 if (GNUTLS_E_SUCCESS != result) {
377 "initialize_tls_session_server(): \
378 gnutls_certificate_allocate_credentials(): %s",
379 gnutls_strerror(result));
383 result = gnutls_init(session, GNUTLS_CLIENT);
384 if (GNUTLS_E_SUCCESS != result) {
386 "initialize_tls_session_server(): gnutls_init(): %s",
387 gnutls_strerror(result));
390 gnutls_priority_set(*session, tls_priority_cache);
391 if (GNUTLS_E_SUCCESS != result) {
393 "initialize_tls_session_server(): gnutls_priority_set(): %s",
394 gnutls_strerror(result));
397 result = gnutls_credentials_set(*session,
398 GNUTLS_CRD_CERTIFICATE, *x509_cred);
399 if (GNUTLS_E_SUCCESS != result) {
401 "initialize_tls_session_server(): gnutls_credentials_set(): %s",
402 gnutls_strerror(result));
406 gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
412 /* Read HTTP request line and headers (ignored).
414 * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
416 static int read_http_request(FILE *client_fd, char *request, size_t length) {
417 char buffer[MAX_REQUEST_LINE];
419 if (NULL == fgets(request, (int)length, client_fd)) {
420 if (ferror(client_fd)) {
421 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
428 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
430 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
434 if (ferror(client_fd)) {
435 LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
442 static void send_bad_request(FILE *client_fd) {
443 fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
444 fprintf(client_fd, "\r\n");
446 static void send_forwarding_failure(FILE *client_fd) {
447 fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
448 fprintf(client_fd, "\r\n");
453 /* Transfer data between client and server sockets until one closes the
455 static void transfer_data(int client, int server) {
456 struct pollfd fds[2];
458 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
461 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
465 int result = poll(fds, 2, -1 /* no timeout */);
467 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
471 /* Data available from client. */
472 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
473 if (0 != read_from_write_to(client, server)) {
474 /* EOF (or other error) */
478 /* Data available from server. */
479 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
480 if (0 != read_from_write_to(server, client)) {
481 /* EOF (or other error) */
486 /* Client closed connection. */
487 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
490 /* Server closed connection. */
491 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
497 /* Read available data from socket from and write it to socket to. At maximum
498 * 4096 bytes are read/written. */
499 static int read_from_write_to(int from, int to) {
501 ssize_t size_written;
504 size_read = read(from, buffer, sizeof(buffer));
506 LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
510 if (0 == size_read) {
514 size_written = write(to, buffer, (size_t)size_read);
515 if (0 > size_written) {
516 LOG_PERROR(LOG_WARNING, "read_from_write_to(): write()");
519 if (size_read != size_written) {
520 LOG(LOG_ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
521 (long int)size_written, (long int)size_read);
529 /* Transfer data between client and server TLS connection until one closes the
531 static void transfer_data_tls(int client, int server,
532 gnutls_session_t client_session,
533 gnutls_session_t server_session) {
534 struct pollfd fds[2];
536 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
539 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
543 int result = poll(fds, 2, -1 /* no timeout */);
545 LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
549 /* Data available from client. */
550 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
551 if (0 != read_from_write_to_tls(client_session, server_session)) {
552 /* EOF (or other error) */
556 /* Data available from server. */
557 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
558 if (0 != read_from_write_to_tls(server_session, client_session)) {
559 /* EOF (or other error) */
564 /* Client closed connection. */
565 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
568 /* Server closed connection. */
569 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
575 /* Read available data from session from and write to session to. */
576 static int read_from_write_to_tls(gnutls_session_t from,
577 gnutls_session_t to) {
580 ssize_t size_written;
583 /* Get maximum possible buffer size. */
584 size = gnutls_record_get_max_size(from);
585 LOG(LOG_DEBUG, "read_from_write_to_tls(): suggested buffer size: %ld",
587 if (size > gnutls_record_get_max_size(to)) {
588 size = gnutls_record_get_max_size(to);
590 if (size > sizeof(buffer)) {
591 size = sizeof(buffer);
593 LOG(LOG_DEBUG, "read_from_write_to_tls(): used buffer size: %ld",
596 size_read = gnutls_record_recv(from, buffer, size);
598 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
599 gnutls_strerror((int)size_read));
603 if (0 == size_read) {
607 size_written = gnutls_record_send(to, buffer, (size_t)size_read);
608 if (0 > size_written) {
609 LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
610 gnutls_strerror((int)size_written));
613 if (size_read != size_written) {
614 LOG(LOG_ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
615 (long int)size_written, (long int)size_read);
623 static int connect_to_host(const char *hostname, const char *port) {
624 struct addrinfo gai_hints;
625 struct addrinfo *gai_result;
629 struct addrinfo *server;
631 if (NULL == hostname || NULL == port) {
635 /* Get IP of hostname server. */
636 memset(&gai_hints, 0, sizeof(gai_hints));
637 gai_hints.ai_family = AF_UNSPEC;
638 gai_hints.ai_socktype = SOCK_STREAM;
639 gai_hints.ai_protocol = 0;
640 gai_hints.ai_flags = AI_NUMERICSERV /* given port is numeric */
641 | AI_ADDRCONFIG /* supported by this computer */
642 | AI_V4MAPPED; /* support IPv4 through IPv6 */
643 gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
644 if (0 != gai_return) {
645 LOG_PERROR(LOG_WARNING, "connect_to_host(): getaddrinfo()");
649 /* Now try to connect to each server returned by getaddrinfo(), use the
650 * first successful connect. */
651 for (server = gai_result; NULL != server; server = server->ai_next) {
652 server_socket = socket(server->ai_family,
654 server->ai_protocol);
655 if (-1 == server_socket) {
656 LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
660 if (-1 != connect(server_socket, server->ai_addr,
661 server->ai_addrlen)) {
664 LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
666 close(server_socket);
668 /* Make sure we free the result from getaddrinfo(). */
669 freeaddrinfo(gai_result);
671 if (NULL == server) {
672 LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
676 return server_socket;
680 /* Parse HTTP CONNECT request string and save its parameters.
682 * The following format is expected: "CONNECT host:port HTTP/1.x".
684 * request and host must have the same size! port must be at least 6 bytes
687 static int parse_request(const char *request, char *host, char *port,
688 int *version_minor) {
689 int port_unused; /* just used to verify the port is numeric */
692 /* scanf() doesn't check spaces. */
693 if (0 != strncmp(request, "CONNECT ", 8)) {
696 /* Check request and extract data, "host:port" is not yet separated. */
697 if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
698 host, version_minor)) {
701 /* Make sure ":port" is there. */
702 if (NULL == (position = strchr(host, ':'))) {
705 /* Make sure port is numeric. */
706 if (1 != sscanf(position + 1, "%d", &port_unused)) {
709 /* Store it in *port. */
710 strncpy(port, position + 1, 5);
712 /* And remove port from host. */