3 I've been hacking together a way to use rsync with OpenSSL, and have
4 attached my current patch against a recent CVS tree. The details of
5 this implementation are:
7 1. The SSL code is added as a "layer" that is forked into its own
10 2. An SSL connection is established by the client issuing the
15 And, if the daemon allows SSL, it replies with
19 At which point both sides begin negotiating the SSL connection.
20 Servers that can't or don't want to use SSL just treat it as a
21 normal unknown command.
23 3. The SSL code is meant to be unobtrusive, and when this patch is
24 applied the program may still be built with no SSL code.
26 4. There are a number of details not implemented.
28 All warnings apply; I don't do C programming all that often, so I
29 can't say if I've left any cleanup/compatibility errors in the code.
31 To use this patch, run these commands for a successful build:
33 patch -p1 <patches/openssl-support.diff
38 based-on: d64bda1c1e79dc385f194d74f7957ce7cd118654
39 diff --git a/Makefile.in b/Makefile.in
42 @@ -41,7 +41,7 @@ OBJS3=progress.o pipe.o
43 DAEMON_OBJ = params.o loadparm.o clientserver.o access.o connection.o authenticate.o
44 popt_OBJS=popt/findme.o popt/popt.o popt/poptconfig.o \
45 popt/popthelp.o popt/poptparse.o
46 -OBJS=$(OBJS1) $(OBJS2) $(OBJS3) $(DAEMON_OBJ) $(LIBOBJ) $(ZLIBOBJ) @BUILD_POPT@
47 +OBJS=$(OBJS1) $(OBJS2) $(OBJS3) $(DAEMON_OBJ) $(LIBOBJ) $(ZLIBOBJ) @BUILD_POPT@ @SSL_OBJS@
49 TLS_OBJ = tls.o syscall.o lib/compat.o lib/snprintf.o lib/permstring.o lib/sysxattrs.o @BUILD_POPT@
51 diff --git a/cleanup.c b/cleanup.c
54 @@ -26,6 +26,9 @@ extern int am_server;
56 extern int am_receiver;
61 extern int keep_partial;
62 extern int got_xfer_error;
63 extern int protocol_version;
64 @@ -138,6 +141,14 @@ NORETURN void _exit_cleanup(int code, const char *file, int line)
65 who_am_i(), code, file, line);
79 diff --git a/clientserver.c b/clientserver.c
82 @@ -30,6 +30,9 @@ extern int am_sender;
89 extern int rsync_port;
90 extern int protect_args;
91 extern int ignore_errors;
92 @@ -132,8 +135,18 @@ int start_socket_client(char *host, int remote_argc, char *remote_argv[],
95 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
101 + int f_in = get_tls_rfd();
102 + int f_out = get_tls_wfd();
103 + return client_run(f_in, f_out, -1, argc, argv);
107 - return ret ? ret : client_run(fd, fd, -1, argc, argv);
108 + return client_run(fd, fd, -1, argc, argv);
111 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
112 @@ -276,6 +289,32 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
113 if (DEBUG_GTE(CMD, 1))
114 print_child_argv("sending daemon args:", sargs);
118 + io_printf(f_out, "#starttls\n");
120 + if (!read_line_old(f_in, line, sizeof line)) {
121 + rprintf(FERROR, "rsync: did not receive reply to #starttls\n");
124 + if (strncmp(line, "@ERROR", 6) == 0) {
125 + rprintf(FERROR, "%s\n", line);
128 + if (strcmp(line, "@RSYNCD: starttls") == 0)
130 + rprintf(FINFO, "%s\n", line);
132 + if (start_tls(f_in, f_out)) {
133 + rprintf(FERROR, "rsync: error during SSL handshake: %s\n",
137 + f_in = get_tls_rfd();
138 + f_out = get_tls_wfd();
142 io_printf(f_out, "%.*s\n", modlen, modname);
144 /* Old servers may just drop the connection here,
145 @@ -301,6 +340,10 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
146 * server to terminate the listing of modules.
147 * We don't want to go on and transfer
148 * anything; just exit. */
156 @@ -308,6 +351,10 @@ int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char
157 rprintf(FERROR, "%s\n", line);
158 /* This is always fatal; the server will now
159 * close the socket. */
167 @@ -692,6 +739,10 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
168 set_env_num("RSYNC_PID", (long)pid);
169 if (wait_process(pid, &status, 0) < 0)
175 set_env_num("RSYNC_RAW_STATUS", status);
176 if (WIFEXITED(status))
177 status = WEXITSTATUS(status);
178 @@ -1033,6 +1084,9 @@ int start_daemon(int f_in, int f_out)
179 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
186 if (!read_line_old(f_in, line, sizeof line))
188 @@ -1044,6 +1098,20 @@ int start_daemon(int f_in, int f_out)
193 + if (use_ssl && strcmp(line, "#starttls") == 0) {
194 + io_printf(f_out, "@RSYNCD: starttls\n");
195 + if (start_tls(f_in, f_out)) {
196 + rprintf(FLOG, "SSL connection failed: %s\n",
200 + f_in = get_tls_rfd();
201 + f_out = get_tls_wfd();
207 /* it's some sort of command that I don't understand */
208 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
209 diff --git a/configure.ac b/configure.ac
212 @@ -318,6 +318,25 @@ if test x"$enable_locale" != x"no"; then
213 AC_DEFINE(CONFIG_LOCALE)
216 +AC_ARG_ENABLE(openssl,
217 + AC_HELP_STRING([--enable-openssl], [compile SSL support with OpenSSL.]))
219 +if test "x$enable_openssl" != xno
222 + LIBS="$LIBS -lcrypto"
224 + AC_CHECK_LIB(ssl, SSL_library_init, , [have_ssl=no])
225 + if test "x$have_ssl" = xyes
227 + AC_DEFINE(HAVE_OPENSSL, 1, [true if you want to use SSL.])
235 AC_MSG_CHECKING([whether to call shutdown on all sockets])
237 *cygwin* ) AC_MSG_RESULT(yes)
238 diff --git a/main.c b/main.c
241 @@ -91,6 +91,9 @@ extern char backup_dir_buf[MAXPATHLEN];
242 extern char *basis_dir[MAX_BASIS_DIRS+1];
243 extern struct file_list *first_flist;
244 extern filter_rule_list daemon_filter_list;
251 @@ -151,6 +154,52 @@ pid_t wait_process(pid_t pid, int *status_ptr, int flags)
255 +/* Sends signal "signo", waits for the process to die, and if it doesn't, sends
256 + * a SIGKILL. If "graceful" is set, the initial "signo" signal is delayed by a
257 + * second to try to let the process exit on its own first. */
258 +pid_t terminate_process(pid_t pid, int *status_ptr, int signo, int graceful)
261 + int timeout = graceful ? 1000 : 3000;
265 + waited_pid = wait_process(pid, status_ptr, timeout >= 0 ? WNOHANG : 0);
268 + if (timeout == 0) {
276 + rprintf(FINFO, "%s:%s shutdown didn't work - sending signal %d\n",
277 + __FUNCTION__, graceful ? " graceful" : "", signo);
282 + /* interruptible wait and calculate the time left for waiting */
283 + struct timeval tval, t1, t2;
285 + gettimeofday(&t1, NULL);
287 + tval.tv_sec = timeout/1000;
288 + tval.tv_usec = (timeout%1000)*1000;
289 + select(0, NULL, NULL, NULL, &tval);
290 + gettimeofday(&t2, NULL);
292 + timeout -= (t2.tv_sec-t1.tv_sec)*1000 + (t2.tv_usec-t1.tv_usec)/1000;
301 /* Wait for a process to exit, calling io_flush while waiting. */
302 static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
304 @@ -802,6 +851,11 @@ static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
310 + start_tls_buffering();
313 flist = send_file_list(f_out,argc,argv);
314 if (!flist || flist->used == 0)
316 @@ -922,6 +976,10 @@ static int do_recv(int f_in, int f_out, char *local_name)
318 io_start_buffering_out(f_out);
319 io_start_multiplex_in(f_in);
322 + start_tls_buffering();
325 #ifdef SUPPORT_HARD_LINKS
326 if (preserve_hard_links && inc_recurse) {
327 @@ -1126,6 +1184,10 @@ int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
328 io_start_multiplex_in(f_in);
330 io_start_buffering_in(f_in);
333 + start_tls_buffering();
335 send_filter_list(f_out);
338 diff --git a/options.c b/options.c
341 @@ -191,6 +191,14 @@ int logfile_format_has_o_or_i = 0;
342 int always_checksum = 0;
347 +char *ssl_cert_path = NULL;
348 +char *ssl_key_path = NULL;
349 +char *ssl_key_passwd = NULL;
350 +char *ssl_ca_path = NULL;
353 #define MAX_BATCH_NAME_LEN 256 /* Must be less than MAXPATHLEN-13 */
354 char *batch_name = NULL;
356 @@ -568,6 +576,7 @@ static void print_rsync_version(enum logcode f)
357 char const *links = "no ";
358 char const *iconv = "no ";
359 char const *ipv6 = "no ";
360 + char const *ssl = "no ";
361 STRUCT_STAT *dumstat;
363 #if SUBPROTOCOL_VERSION != 0
364 @@ -601,6 +610,9 @@ static void print_rsync_version(enum logcode f)
365 #ifdef CAN_SET_SYMLINK_TIMES
372 rprintf(f, "%s version %s protocol version %d%s\n",
373 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION, subprotocol);
374 @@ -614,8 +626,8 @@ static void print_rsync_version(enum logcode f)
375 (int)(sizeof (int64) * 8));
376 rprintf(f, " %ssocketpairs, %shardlinks, %ssymlinks, %sIPv6, batchfiles, %sinplace,\n",
377 got_socketpair, hardlinks, links, ipv6, have_inplace);
378 - rprintf(f, " %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes\n",
379 - have_inplace, acls, xattrs, iconv, symtimes);
380 + rprintf(f, " %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes, %sSSL\n",
381 + have_inplace, acls, xattrs, iconv, symtimes, ssl);
383 #ifdef MAINTAINER_MODE
384 rprintf(f, "Panic Action: \"%s\"\n", get_panic_action());
385 @@ -787,6 +799,13 @@ void usage(enum logcode F)
387 rprintf(F," -4, --ipv4 prefer IPv4\n");
388 rprintf(F," -6, --ipv6 prefer IPv6\n");
390 + rprintf(F," --ssl allow socket connections to use SSL\n");
391 + rprintf(F," --ssl-cert=FILE path to daemon's SSL certificate\n");
392 + rprintf(F," --ssl-key=FILE path to daemon's SSL private key\n");
393 + rprintf(F," --ssl-key-passwd=PASS password for PEM-encoded private key\n");
394 + rprintf(F," --ssl-ca-certs=FILE path to trusted CA certificates\n");
396 rprintf(F," --version print version number\n");
397 rprintf(F,"(-h) --help show this help (-h works with no other options)\n");
399 @@ -800,7 +819,7 @@ enum {OPT_VERSION = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
400 OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
401 OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
402 OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
403 - OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG,
404 + OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG, OPT_USE_SSL,
405 OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_BWLIMIT,
406 OPT_SERVER, OPT_REFUSED_BASE = 9000};
408 @@ -1018,6 +1037,13 @@ static struct poptOption long_options[] = {
409 {"checksum-seed", 0, POPT_ARG_INT, &checksum_seed, 0, 0, 0 },
410 {"server", 0, POPT_ARG_NONE, 0, OPT_SERVER, 0, 0 },
411 {"sender", 0, POPT_ARG_NONE, 0, OPT_SENDER, 0, 0 },
413 + {"ssl", 0, POPT_ARG_NONE, 0, OPT_USE_SSL, 0, 0},
414 + {"ssl-cert", 0, POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
415 + {"ssl-key", 0, POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
416 + {"ssl-key-passwd", 0, POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
417 + {"ssl-ca-certs", 0, POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
419 /* All the following options switch us into daemon-mode option-parsing. */
420 {"config", 0, POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
421 {"daemon", 0, POPT_ARG_NONE, 0, OPT_DAEMON, 0, 0 },
422 @@ -1045,6 +1071,13 @@ static void daemon_usage(enum logcode F)
423 rprintf(F," -v, --verbose increase verbosity\n");
424 rprintf(F," -4, --ipv4 prefer IPv4\n");
425 rprintf(F," -6, --ipv6 prefer IPv6\n");
427 + rprintf(F," --ssl allow socket connections to use SSL\n");
428 + rprintf(F," --ssl-cert=FILE path to daemon's SSL certificate\n");
429 + rprintf(F," --ssl-key=FILE path to daemon's SSL private key\n");
430 + rprintf(F," --ssl-key-passwd=PASS password for PEM-encoded private key\n");
431 + rprintf(F," --ssl-ca-certs=FILE path to trusted CA certificates\n");
433 rprintf(F," --help show this help screen\n");
436 @@ -1070,6 +1103,13 @@ static struct poptOption long_daemon_options[] = {
437 {"protocol", 0, POPT_ARG_INT, &protocol_version, 0, 0, 0 },
438 {"server", 0, POPT_ARG_NONE, &am_server, 0, 0, 0 },
439 {"temp-dir", 'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
441 + {"ssl", 0, POPT_ARG_NONE, 0, OPT_USE_SSL, 0, 0},
442 + {"ssl-cert", 0, POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
443 + {"ssl-key", 0, POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
444 + {"ssl-key-passwd", 0, POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
445 + {"ssl-ca-certs", 0, POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
447 {"verbose", 'v', POPT_ARG_NONE, 0, 'v', 0, 0 },
448 {"no-verbose", 0, POPT_ARG_VAL, &verbose, 0, 0, 0 },
449 {"no-v", 0, POPT_ARG_VAL, &verbose, 0, 0, 0 },
450 @@ -1365,6 +1405,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
462 "rsync: %s: %s (in daemon mode)\n",
463 @@ -1391,6 +1437,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
464 exit_cleanup(RERR_SYNTAX);
470 + snprintf(err_buf, sizeof(err_buf),
471 + "Openssl error: %s\n",
478 *argv_p = argv = poptGetArgs(pc);
479 *argc_p = argc = count_args(argv);
481 @@ -1769,6 +1826,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
492 /* A large opt value means that set_refuse_options()
493 * turned this option off. */
494 @@ -2171,6 +2234,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
495 if (delay_updates && !partial_dir)
496 partial_dir = tmp_partialdir;
501 + snprintf(err_buf, sizeof(err_buf),
502 + "Openssl error: %s\n",
510 #ifdef HAVE_FTRUNCATE
512 @@ -2763,9 +2837,18 @@ char *check_for_hostspec(char *s, char **host_ptr, int *port_ptr)
516 - if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
517 - *host_ptr = parse_hostspec(s + strlen(URL_PREFIX), &path, port_ptr);
520 + int url_prefix_len;
521 + if (strncasecmp(URL_PREFIX, s, sizeof URL_PREFIX - 1) == 0)
522 + url_prefix_len = sizeof URL_PREFIX - 1;
523 + else if (strncasecmp(SSL_URL_PREFIX, s, sizeof SSL_URL_PREFIX - 1) == 0) {
527 + url_prefix_len = sizeof SSL_URL_PREFIX - 1;
529 + url_prefix_len = 0;
530 + if (url_prefix_len && (*host_ptr = parse_hostspec(s + url_prefix_len, &path, port_ptr))) {
532 *port_ptr = RSYNC_PORT;
534 diff --git a/rsync.h b/rsync.h
539 #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
540 #define URL_PREFIX "rsync://"
541 +#define SSL_URL_PREFIX "rsyncs://"
543 #define SYMLINK_PREFIX "/rsyncd-munged/" /* This MUST have a trailing slash! */
544 #define SYMLINK_PREFIX_LEN ((int)sizeof SYMLINK_PREFIX - 1)
545 @@ -587,6 +588,11 @@ typedef unsigned int size_t;
546 # define SIZEOF_INT64 SIZEOF_OFF_T
550 +#include <openssl/ssl.h>
551 +#include <openssl/err.h>
557 diff --git a/ssl.c b/ssl.c
562 +/* -*- c-file-style: "linux" -*-
563 + * ssl.c: operations for negotiating SSL rsync connections.
565 + * Copyright (C) 2003 Casey Marshall <rsdio@metastatic.org>
567 + * This program is free software; you can redistribute it and/or modify
568 + * it under the terms of the GNU General Public License as published by
569 + * the Free Software Foundation; either version 2 of the License, or
570 + * (at your option) any later version.
572 + * This program is distributed in the hope that it will be useful,
573 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
574 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
575 + * GNU General Public License for more details.
577 + * You should have received a copy of the GNU General Public License
578 + * along with this program; if not, write to the Free Software
579 + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
584 +#ifdef HAVE_SYS_SELECT_H
585 +#include <sys/select.h>
587 +#include <sys/time.h>
588 +#include <sys/types.h>
593 +#define SSL_MAX_RECORD_SIZE (1024*16) /* TLS record size */
594 +#define MAX_BUFFERING_TIME_MS 100
596 +extern int am_daemon;
597 +extern int am_server;
599 +extern char *ssl_cert_path;
600 +extern char *ssl_key_path;
601 +extern char *ssl_key_passwd;
602 +extern char *ssl_ca_path;
604 +static SSL_CTX *ssl_ctx;
606 +static int tls_read[2] = { -1, -1 };
607 +static int tls_write[2] = { -1, -1 };
608 +static int ssl_running;
609 +static int ssl_min_send_size;
610 +static int ssl_pid = -1;
612 +#ifdef HAVE_SIGACTION
613 +static struct sigaction sigact;
616 +/* copied from progress.c */
617 +static unsigned long msdiff(struct timeval *t1, struct timeval *t2)
619 + return (t2->tv_sec - t1->tv_sec) * 1000L
620 + + (t2->tv_usec - t1->tv_usec) / 1000;
624 + * A non-interactive callback to be passed to SSL_CTX_set_default_password_cb,
625 + * which merely copies the value of ssl_key_passwd into buf. This is
626 + * used for when the private key password is supplied via an option.
628 +static int default_password_cb(char *buf, int n, UNUSED(int f), UNUSED(void *u))
630 + if (ssl_key_passwd == NULL || n < (int)strlen(ssl_key_passwd))
632 + strncpy(buf, ssl_key_passwd, n-1);
633 + return strlen(ssl_key_passwd);
637 + * If verbose, this method traces the status of the SSL handshake.
639 +static void info_callback(const SSL *ssl, int cb, int val)
646 + cbs = "SSL_CB_LOOP";
649 + cbs = "SSL_CB_EXIT";
652 + cbs = "SSL_CB_READ";
655 + cbs = "SSL_CB_WRITE";
658 + cbs = "SSL_CB_ALERT";
660 + case SSL_CB_READ_ALERT:
661 + cbs = "SSL_CB_READ_ALERT";
663 + case SSL_CB_WRITE_ALERT:
664 + cbs = "SSL_CB_WRITE_ALERT";
666 + case SSL_CB_ACCEPT_LOOP:
667 + cbs = "SSL_CB_ACCEPT_LOOP";
669 + case SSL_CB_ACCEPT_EXIT:
670 + cbs = "SSL_CB_ACCEPT_EXIT";
672 + case SSL_CB_CONNECT_LOOP:
673 + cbs = "SSL_CB_CONNECT_LOOP";
675 + case SSL_CB_CONNECT_EXIT:
676 + cbs = "SSL_CB_CONNECT_EXIT";
678 + case SSL_CB_HANDSHAKE_START:
679 + cbs = "SSL_CB_HANDSHAKE_START";
681 + case SSL_CB_HANDSHAKE_DONE:
682 + cbs = "SSL_CB_HANDSHAKE_DONE";
685 + snprintf(buf, sizeof buf, "??? (%d)", cb);
689 + if (DEBUG_GTE(CONNECT, 1)) {
690 + rprintf(FLOG, "SSL: info_callback(%p,%s,%d)\n", ssl, cbs, val);
691 + if (cb == SSL_CB_HANDSHAKE_DONE) {
692 + SSL_CIPHER_description(SSL_get_current_cipher((SSL*)ssl),
694 + rprintf(FLOG, "SSL: cipher: %s", buf);
700 + * Initializes the SSL context for TLSv1 connections; returns zero on
707 + SSL_library_init();
708 + SSL_load_error_strings();
709 + ssl_ctx = SSL_CTX_new(TLSv1_method());
712 + SSL_CTX_set_info_callback(ssl_ctx, info_callback);
714 + SSL_CTX_set_options(ssl_ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS|SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
716 + /* Sets the certificate sent to the other party. */
717 + if (ssl_cert_path != NULL
718 + && SSL_CTX_use_certificate_file(ssl_ctx, ssl_cert_path,
719 + SSL_FILETYPE_PEM) != 1)
721 + /* Set up the simple non-interactive callback if the password
722 + * was supplied on the command line. */
723 + if (ssl_key_passwd != NULL)
724 + SSL_CTX_set_default_passwd_cb(ssl_ctx, default_password_cb);
725 + /* Sets the private key that matches the public certificate. */
726 + if (ssl_key_path != NULL) {
727 + if (SSL_CTX_use_PrivateKey_file(ssl_ctx, ssl_key_path,
728 + SSL_FILETYPE_PEM) != 1)
730 + if (SSL_CTX_check_private_key(ssl_ctx) != 1)
733 + if (ssl_ca_path != NULL
734 + && !SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_path, NULL))
741 + * Returns the error string for the current SSL error, if any.
743 +char *get_ssl_error(void)
745 + return ERR_error_string(ERR_get_error(), NULL);
749 + * Returns the input file descriptor for the SSL connection.
751 +int get_tls_rfd(void)
753 + return tls_read[0];
757 + * Returns the output file descriptor for the SSL connection.
759 +int get_tls_wfd(void)
761 + return tls_write[1];
765 + * Signal handler that ends the SSL connection.
767 +static RETSIGTYPE tls_sigusr1(int UNUSED(val))
772 +/* Signal handler that starts record-size buffering. */
773 +static RETSIGTYPE tls_sigusr2(int UNUSED(val))
775 + ssl_min_send_size = SSL_MAX_RECORD_SIZE;
779 + * Negotiates the TLS connection, creates a socket pair for communicating
780 + * with the rsync process, then forks into a new process that will handle
781 + * the communication.
783 + * 0 is returned on success.
784 + * rsync to network algorithm:
785 + * A buffer ring of two buffers is maintained. Data is read from the local
786 + * socket into the current buffer. The buffer is eligible for sending if
787 + * enough data has been buffered, or enough time has passed. Once the buffer
788 + * becomes eligible for sending it is marked "ready" and buffering continues
789 + * on the other buffer (assuming it's "unready"). This algorithm tries to
790 + * maximize SSL record size.
792 + * network to rsync algorithm:
793 + * One receive buffer twice the size of the SSL max record size. Reading
794 + * from the network is attempted only if there's enough space for a whole
795 + * record (this is done to optimize OpenSSL per-call overhead).
796 + * As bytes enter the buffer sending to rsync begins, when the buffer becomes
797 + * full we wait for sending to rsync to finish.
799 + * A graceful stop is attempted on both directions. So if the pipe from rsync
800 + * is gracefully shut down, we try to send all data to the network before closing
801 + * the connection and if the SSL connection is gracefully shut down we try to
802 + * send everything to rsync before closing the rsync pipe.
804 +int start_tls(int f_in, int f_out)
807 + unsigned char buf_tonetwork[2][SSL_MAX_RECORD_SIZE], buf_fromnetwork[2*SSL_MAX_RECORD_SIZE];
808 + int tonet_ready[2] = {0}, tonet_size[2] = {0}, write_tonet = 0, tonet_fill_idx = 0, tonet_send_idx = 0;
809 + struct timeval buffering_start, now, timeout, *tp;
810 + int avail_fromnet = 0, write_fromnet = 0;
811 + int want_read_fromnet = 1, want_write_tonet = 0;
812 + int want_read_fromrsync = 1, want_write_torsync = 0;
813 + int write_tonet_blocks = 0, read_fromnet_blocks = 0;
814 + int write_torsync_blocks = 0, read_fromrsync_blocks = 0;
815 + int ssl_readfd_blocks = 0, ssl_writefd_blocks = 0;
816 + int ssl_write_count = 0;
818 + int net_closed = 0, rsync_closed = 0;
821 + const char *ssl_ciphers;
823 + if (fd_pair(tls_read))
825 + if (fd_pair(tls_write))
828 + set_blocking(tls_read[0]);
829 + set_nonblocking(tls_read[1]);
830 + set_nonblocking(tls_write[0]);
831 + set_blocking(tls_write[1]);
832 + set_nonblocking(f_in);
833 + set_nonblocking(f_out);
835 + ssl_pid = do_fork();
838 + if (ssl_pid != 0) {
839 + close(tls_write[0]);
840 + close(tls_read[1]);
846 + close(tls_write[1]);
847 + close(tls_read[0]);
849 + SIGACTION(SIGUSR1, tls_sigusr1);
850 + SIGACTION(SIGUSR2, tls_sigusr2);
851 + ssl = SSL_new(ssl_ctx);
854 + if (am_daemon || am_server)
855 + SSL_set_accept_state(ssl);
857 + SSL_set_connect_state(ssl);
858 + ssl_ciphers = getenv("RSYNC_SSL_CIPHERS");
860 + SSL_set_cipher_list(ssl, ssl_ciphers);
863 + SSL_set_rfd(ssl, f_in);
864 + SSL_set_wfd(ssl, f_out);
867 + n = MAX(tls_read[1], n);
869 + n = MAX(f_out, n) + 1;
873 + while (ssl_running) {
874 + ++loopcount; /* the loopcount prevents starvation of one transfer direction by the other */
877 + if (want_read_fromrsync && !read_fromrsync_blocks) {
878 + int cur_buf_size = tonet_size[tonet_fill_idx];
879 + r = read(tls_write[0], buf_tonetwork[tonet_fill_idx]+cur_buf_size, sizeof(buf_tonetwork[0])-cur_buf_size);
883 + if (cur_buf_size == 0)
884 + gettimeofday(&buffering_start, NULL);
886 + tonet_size[tonet_fill_idx] = cur_buf_size;
887 + if (cur_buf_size >= ssl_min_send_size) {
888 + want_write_tonet = 1;
889 + tonet_ready[tonet_fill_idx] = 1;
890 + tonet_fill_idx = !tonet_fill_idx;
891 + if (tonet_ready[tonet_fill_idx])
892 + want_read_fromrsync = 0;
895 + } else if (r < 0 && errno == EWOULDBLOCK)
896 + read_fromrsync_blocks = 1;
898 + rprintf(FERROR, "pipe read error: %s\n",
903 + if (cur_buf_size) {
904 + want_write_tonet = 1;
905 + tonet_ready[tonet_fill_idx] = 1; /* close current buffer */
907 + want_read_fromrsync = 0; /* don't read */
908 + want_write_torsync = 0; /* don't write */
909 + read_fromrsync_blocks = 0; /* don't select */
910 + write_torsync_blocks = 0;
911 + want_read_fromnet = 1; /* purge incoming data from network */
913 + if (net_closed || !want_write_tonet)
918 + if (want_read_fromnet && !read_fromnet_blocks) {
919 + r = SSL_read(ssl, buf_fromnetwork+avail_fromnet, SSL_MAX_RECORD_SIZE);
922 + if (!rsync_closed) {
923 + avail_fromnet += r;
924 + want_write_torsync = 1;
925 + if (avail_fromnet >= (int)(sizeof(buf_fromnetwork)-SSL_MAX_RECORD_SIZE))
926 + want_read_fromnet = 0;
929 + switch (SSL_get_error(ssl, r)) {
930 + case SSL_ERROR_ZERO_RETURN:
932 + want_read_fromnet = 0; /* don't read */
933 + want_write_tonet = 0; /* don't write */
934 + ssl_readfd_blocks = 0; /* and for heaven's sake - don't select() */
935 + ssl_writefd_blocks = 0;
936 + want_read_fromrsync = 1; /* and purge stuff from rsync side */
937 + tonet_size[tonet_fill_idx] = 0;
938 + tonet_ready[tonet_fill_idx] = 0;
939 + if (rsync_closed || !want_write_torsync)
940 + goto graceful_stop;
942 + case SSL_ERROR_WANT_READ:
943 + ssl_readfd_blocks = 1;
944 + read_fromnet_blocks = 1;
946 + case SSL_ERROR_WANT_WRITE:
947 + ssl_writefd_blocks = 1;
948 + read_fromnet_blocks = 1;
950 + case SSL_ERROR_SYSCALL:
952 + rprintf(FERROR, "SSL spurious EOF\n");
954 + rprintf(FERROR, "SSL I/O error: %s\n",
957 + case SSL_ERROR_SSL:
958 + rprintf(FERROR, "SSL %s\n",
959 + ERR_error_string(ERR_get_error(), NULL));
962 + rprintf(FERROR, "unexpected ssl error %d\n", r);
968 + if (want_write_torsync && !write_torsync_blocks) {
969 + r = write(tls_read[1], buf_fromnetwork+write_fromnet, avail_fromnet-write_fromnet);
972 + write_fromnet += r;
973 + if (write_fromnet >= avail_fromnet) {
978 + want_read_fromnet = 1;
979 + want_write_torsync = 0;
982 + else if (errno == EWOULDBLOCK)
983 + write_torsync_blocks = 1;
985 + if (errno != EPIPE)
986 + rprintf(FERROR, "pipe write error: %s\n", strerror(errno));
991 + if (want_write_tonet && !write_tonet_blocks) {
992 + /* lock the write count, 'cause if SSL_write fails on non-blocking IO, it
993 + * must be repeated with same parameters. */
994 + if (ssl_write_count == 0)
995 + ssl_write_count = tonet_size[tonet_send_idx] - write_tonet;
996 + r = SSL_write(ssl, buf_tonetwork[tonet_send_idx]+write_tonet, ssl_write_count);
1000 + ssl_write_count = 0;
1001 + if (write_tonet >= tonet_size[tonet_send_idx]) {
1003 + tonet_size[tonet_send_idx] = 0;
1004 + tonet_ready[tonet_send_idx] = 0;
1005 + if (!rsync_closed)
1006 + want_read_fromrsync = 1;
1007 + tonet_send_idx = !tonet_send_idx;
1008 + if (!tonet_ready[tonet_send_idx]) {
1009 + want_write_tonet = 0;
1015 + switch (SSL_get_error(ssl, r)) {
1016 + case SSL_ERROR_ZERO_RETURN:
1017 + goto graceful_stop;
1018 + case SSL_ERROR_WANT_READ:
1019 + ssl_readfd_blocks = 1;
1020 + write_tonet_blocks = 1;
1022 + case SSL_ERROR_WANT_WRITE:
1023 + ssl_writefd_blocks = 1;
1024 + write_tonet_blocks = 1;
1026 + case SSL_ERROR_SYSCALL:
1028 + rprintf(FERROR, "SSL: spurious EOF\n");
1030 + rprintf(FERROR, "SSL: I/O error: %s\n", strerror(errno));
1032 + case SSL_ERROR_SSL:
1033 + rprintf(FERROR, "SSL: %s\n",
1034 + ERR_error_string(ERR_get_error(), NULL));
1037 + rprintf(FERROR, "unexpected ssl error %d\n", r);
1043 + if (!want_more_io || (loopcount&31) == 0) {
1044 + int has_buffered = 0;
1045 + if (!net_closed && !tonet_ready[tonet_fill_idx] && tonet_size[tonet_fill_idx]) {
1047 + unsigned long buffering_time;
1048 + gettimeofday(&now,NULL);
1049 + buffering_time = msdiff(&buffering_start,&now);
1050 + if (buffering_time >= MAX_BUFFERING_TIME_MS) {
1051 + want_write_tonet = 1;
1053 + tonet_ready[tonet_fill_idx] = 1;
1054 + tonet_fill_idx = !tonet_fill_idx;
1055 + if (tonet_ready[tonet_fill_idx])
1056 + want_read_fromrsync = 0;
1060 + int waiting_on_something = 0;
1063 + if (read_fromrsync_blocks) {
1064 + waiting_on_something = 1;
1065 + FD_SET(tls_write[0], &rd);
1067 + if (write_torsync_blocks) {
1068 + waiting_on_something = 1;
1069 + FD_SET(tls_read[1], &wd);
1071 + if (ssl_readfd_blocks) {
1072 + waiting_on_something = 1;
1073 + FD_SET(f_in, &rd);
1075 + if (ssl_writefd_blocks) {
1076 + waiting_on_something = 1;
1077 + FD_SET(f_out, &wd);
1080 + if (want_more_io) {
1081 + /* just poll to see if some sockets became non-blocking*/
1082 + timeout.tv_sec = 0;
1083 + timeout.tv_usec = 0;
1085 + } else if (waiting_on_something && !has_buffered)
1086 + tp = NULL; /*infinite wait until a socket becomes available*/
1088 + timeout.tv_sec = MAX_BUFFERING_TIME_MS/1000;
1089 + timeout.tv_usec = (MAX_BUFFERING_TIME_MS%1000)*1000;
1093 + if (waiting_on_something || !want_more_io) {
1094 + r = select(n, &rd, &wd, NULL, tp);
1097 + if (errno != EINTR) {
1098 + rprintf(FERROR, "select error: %s\n",
1105 + if (FD_ISSET(tls_write[0], &rd))
1106 + read_fromrsync_blocks = 0;
1107 + if (FD_ISSET(f_in,&rd)) {
1108 + read_fromnet_blocks = 0;
1109 + write_tonet_blocks = 0;
1110 + ssl_readfd_blocks = 0;
1112 + if (FD_ISSET(tls_read[1],&wd))
1113 + write_torsync_blocks = 0;
1114 + if (FD_ISSET(f_out,&wd)) {
1115 + read_fromnet_blocks = 0;
1116 + write_tonet_blocks = 0;
1117 + ssl_writefd_blocks = 0;
1125 + /* The SSL shutdown API looks pretty broken with respect to corner cases
1126 + * where the underlying socket is blocking. This is a "best effort". */
1127 + if (SSL_shutdown(ssl) != 1)
1128 + SSL_shutdown(ssl);
1132 + /* We're finished. */
1134 + close(tls_read[1]);
1135 + close(tls_write[0]);
1137 + if (f_out != f_in)
1142 +void start_tls_buffering(void)
1145 + kill(ssl_pid, SIGUSR2);
1149 + * Ends the TLS connection.
1153 + if (ssl_pid > 0) {
1155 + /* try a graceful stop - this makes sure all data is sent, and
1156 + * also causes our side to send a close_notify alert, as required
1157 + * by TLS specs. */
1158 + close(get_tls_rfd());
1159 + if (get_tls_wfd() != get_tls_rfd())
1160 + close(get_tls_wfd());
1161 + terminate_process(ssl_pid, &status, SIGUSR1, 1);