Adding group-auth patch; updating patches.
[rsync-patches.git] / openssl-support.diff
1 Casey Marshall wrote:
2
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:
6
7   1. The SSL code is added as a "layer" that is forked into its own
8      process.
9
10   2. An SSL connection is established by the client issuing the
11      command:
12
13        #starttls
14
15      And, if the daemon allows SSL, it replies with
16
17        @RSYNCD: starttls
18
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.
22
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.
25
26   4. There are a number of details not implemented.
27
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.
30
31 To use this patch, run these commands for a successful build:
32
33     patch -p1 <patches/openssl-support.diff
34     ./prepare-source
35     ./configure
36     make
37
38 based-on: 3b8f8192227b14e708bf535072485e50f4362270
39 diff --git a/Makefile.in b/Makefile.in
40 --- a/Makefile.in
41 +++ 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@
48  
49  TLS_OBJ = tls.o syscall.o lib/compat.o lib/snprintf.o lib/permstring.o lib/sysxattrs.o @BUILD_POPT@
50  
51 diff --git a/cleanup.c b/cleanup.c
52 --- a/cleanup.c
53 +++ b/cleanup.c
54 @@ -25,6 +25,9 @@
55  extern int am_server;
56  extern int am_daemon;
57  extern int io_error;
58 +#ifdef HAVE_OPENSSL
59 +extern int use_ssl;
60 +#endif
61  extern int keep_partial;
62  extern int got_xfer_error;
63  extern int output_needs_newline;
64 @@ -127,6 +130,14 @@ NORETURN void _exit_cleanup(int code, const char *file, int line)
65                                 code, file, line);
66                 }
67  
68 +#ifdef HAVE_OPENSSL
69 +               /* FALLTHROUGH */
70 +#include "case_N.h"
71 +
72 +               if (use_ssl)
73 +                       end_tls();
74 +#endif
75 +
76                 /* FALLTHROUGH */
77  #include "case_N.h"
78  
79 diff --git a/clientserver.c b/clientserver.c
80 --- a/clientserver.c
81 +++ b/clientserver.c
82 @@ -30,6 +30,9 @@ extern int am_sender;
83  extern int am_server;
84  extern int am_daemon;
85  extern int am_root;
86 +#ifdef HAVE_OPENSSL
87 +extern int use_ssl;
88 +#endif
89  extern int rsync_port;
90  extern int protect_args;
91  extern int ignore_errors;
92 @@ -134,8 +137,18 @@ int start_socket_client(char *host, int remote_argc, char *remote_argv[],
93  #endif
94  
95         ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
96 +       if (ret)
97 +               return ret;
98 +
99 +#ifdef HAVE_OPENSSL
100 +       if (use_ssl) {
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);
104 +       }
105 +#endif
106  
107 -       return ret ? ret : client_run(fd, fd, -1, argc, argv);
108 +       return client_run(fd, fd, -1, argc, argv);
109  }
110  
111  static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
112 @@ -278,6 +291,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);
115  
116 +#ifdef HAVE_OPENSSL
117 +       if (use_ssl) {
118 +               io_printf(f_out, "#starttls\n");
119 +               while (1) {
120 +                       if (!read_line_old(f_in, line, sizeof line)) {
121 +                               rprintf(FERROR, "rsync: did not receive reply to #starttls\n");
122 +                               return -1;
123 +                       }
124 +                       if (strncmp(line, "@ERROR", 6) == 0) {
125 +                               rprintf(FERROR, "%s\n", line);
126 +                               return -1;
127 +                       }
128 +                       if (strcmp(line, "@RSYNCD: starttls") == 0)
129 +                               break;
130 +                       rprintf(FINFO, "%s\n", line);
131 +               }
132 +               if (start_tls(f_in, f_out)) {
133 +                       rprintf(FERROR, "rsync: error during SSL handshake: %s\n",
134 +                               get_ssl_error());
135 +                       return -1;
136 +               }
137 +               f_in = get_tls_rfd();
138 +               f_out = get_tls_wfd();
139 +       }
140 +#endif
141 +
142         io_printf(f_out, "%.*s\n", modlen, modname);
143  
144         /* Old servers may just drop the connection here,
145 @@ -303,6 +342,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. */
149 +#ifdef HAVE_OPENSSL
150 +                       if (use_ssl)
151 +                               end_tls();
152 +#endif
153                         exit(0);
154                 }
155  
156 @@ -310,6 +353,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. */
160 +#ifdef HAVE_OPENSSL
161 +                       if (use_ssl)
162 +                               end_tls();
163 +#endif
164                         return -1;
165                 }
166  
167 @@ -1025,6 +1072,9 @@ int start_daemon(int f_in, int f_out)
168         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
169                 return -1;
170  
171 +#ifdef HAVE_OPENSSL
172 +retry:
173 +#endif
174         line[0] = 0;
175         if (!read_line_old(f_in, line, sizeof line))
176                 return -1;
177 @@ -1036,6 +1086,20 @@ int start_daemon(int f_in, int f_out)
178                 return -1;
179         }
180  
181 +#ifdef HAVE_OPENSSL
182 +       if (use_ssl && strcmp(line, "#starttls") == 0) {
183 +               io_printf(f_out, "@RSYNCD: starttls\n");
184 +               if (start_tls(f_in, f_out)) {
185 +                       rprintf(FLOG, "SSL connection failed: %s\n",
186 +                               get_ssl_error());
187 +                       return -1;
188 +               }
189 +               f_in = get_tls_rfd();
190 +               f_out = get_tls_wfd();
191 +               goto retry;
192 +       }
193 +#endif
194 +
195         if (*line == '#') {
196                 /* it's some sort of command that I don't understand */
197                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
198 diff --git a/configure.in b/configure.in
199 --- a/configure.in
200 +++ b/configure.in
201 @@ -303,6 +303,21 @@ if test x"$enable_locale" != x"no"; then
202         AC_DEFINE(CONFIG_LOCALE)
203  fi
204  
205 +AC_ARG_ENABLE(openssl,
206 +              AC_HELP_STRING([--enable-openssl], [compile SSL support with OpenSSL.]))
207 +
208 +if test "x$enable_openssl" != xno
209 +then
210 +       have_ssl=yes
211 +       AC_CHECK_LIB(ssl, SSL_library_init, , [have_ssl=no])
212 +       if test "x$have_ssl" = xyes
213 +       then
214 +               AC_DEFINE(HAVE_OPENSSL, 1, [true if you want to use SSL.])
215 +               SSL_OBJS=ssl.o
216 +               AC_SUBST(SSL_OBJS)
217 +       fi
218 +fi
219 +
220  AC_MSG_CHECKING([whether to call shutdown on all sockets])
221  case $host_os in
222         *cygwin* ) AC_MSG_RESULT(yes)
223 diff --git a/options.c b/options.c
224 --- a/options.c
225 +++ b/options.c
226 @@ -191,6 +191,14 @@ int logfile_format_has_o_or_i = 0;
227  int always_checksum = 0;
228  int list_only = 0;
229  
230 +#ifdef HAVE_OPENSSL
231 +int use_ssl = 0;
232 +char *ssl_cert_path = NULL;
233 +char *ssl_key_path = NULL;
234 +char *ssl_key_passwd = NULL;
235 +char *ssl_ca_path = NULL;
236 +#endif
237 +
238  #define MAX_BATCH_NAME_LEN 256 /* Must be less than MAXPATHLEN-13 */
239  char *batch_name = NULL;
240  
241 @@ -567,6 +575,7 @@ static void print_rsync_version(enum logcode f)
242         char const *links = "no ";
243         char const *iconv = "no ";
244         char const *ipv6 = "no ";
245 +       char const *ssl = "no ";
246         STRUCT_STAT *dumstat;
247  
248  #if SUBPROTOCOL_VERSION != 0
249 @@ -600,6 +609,9 @@ static void print_rsync_version(enum logcode f)
250  #ifdef CAN_SET_SYMLINK_TIMES
251         symtimes = "";
252  #endif
253 +#ifdef HAVE_OPENSSL
254 +       ssl = "";
255 +#endif
256  
257         rprintf(f, "%s  version %s  protocol version %d%s\n",
258                 RSYNC_NAME, RSYNC_VERSION, PROTOCOL_VERSION, subprotocol);
259 @@ -613,8 +625,8 @@ static void print_rsync_version(enum logcode f)
260                 (int)(sizeof (int64) * 8));
261         rprintf(f, "    %ssocketpairs, %shardlinks, %ssymlinks, %sIPv6, batchfiles, %sinplace,\n",
262                 got_socketpair, hardlinks, links, ipv6, have_inplace);
263 -       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes\n",
264 -               have_inplace, acls, xattrs, iconv, symtimes);
265 +       rprintf(f, "    %sappend, %sACLs, %sxattrs, %siconv, %ssymtimes, %sSSL\n",
266 +               have_inplace, acls, xattrs, iconv, symtimes, ssl);
267  
268  #ifdef MAINTAINER_MODE
269         rprintf(f, "Panic Action: \"%s\"\n", get_panic_action());
270 @@ -785,6 +797,13 @@ void usage(enum logcode F)
271  #endif
272    rprintf(F," -4, --ipv4                  prefer IPv4\n");
273    rprintf(F," -6, --ipv6                  prefer IPv6\n");
274 +#ifdef HAVE_OPENSSL
275 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
276 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
277 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
278 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
279 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
280 +#endif
281    rprintf(F,"     --version               print version number\n");
282    rprintf(F,"(-h) --help                  show this help (-h works with no other options)\n");
283  
284 @@ -799,7 +818,7 @@ enum {OPT_VERSION = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
285        OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
286        OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
287        OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG,
288 -      OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN,
289 +      OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_USE_SSL,
290        OPT_SERVER, OPT_REFUSED_BASE = 9000};
291  
292  static struct poptOption long_options[] = {
293 @@ -1013,6 +1032,13 @@ static struct poptOption long_options[] = {
294    {"checksum-seed",    0,  POPT_ARG_INT,    &checksum_seed, 0, 0, 0 },
295    {"server",           0,  POPT_ARG_NONE,   0, OPT_SERVER, 0, 0 },
296    {"sender",           0,  POPT_ARG_NONE,   0, OPT_SENDER, 0, 0 },
297 +#ifdef HAVE_OPENSSL
298 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
299 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
300 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
301 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
302 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
303 +#endif
304    /* All the following options switch us into daemon-mode option-parsing. */
305    {"config",           0,  POPT_ARG_STRING, 0, OPT_DAEMON, 0, 0 },
306    {"daemon",           0,  POPT_ARG_NONE,   0, OPT_DAEMON, 0, 0 },
307 @@ -1040,6 +1066,13 @@ static void daemon_usage(enum logcode F)
308    rprintf(F," -v, --verbose               increase verbosity\n");
309    rprintf(F," -4, --ipv4                  prefer IPv4\n");
310    rprintf(F," -6, --ipv6                  prefer IPv6\n");
311 +#ifdef HAVE_OPENSSL
312 +  rprintf(F,"     --ssl                   allow socket connections to use SSL\n");
313 +  rprintf(F,"     --ssl-cert=FILE         path to daemon's SSL certificate\n");
314 +  rprintf(F,"     --ssl-key=FILE          path to daemon's SSL private key\n");
315 +  rprintf(F,"     --ssl-key-passwd=PASS   password for PEM-encoded private key\n");
316 +  rprintf(F,"     --ssl-ca-certs=FILE     path to trusted CA certificates\n");
317 +#endif
318    rprintf(F,"     --help                  show this help screen\n");
319  
320    rprintf(F,"\n");
321 @@ -1065,6 +1098,13 @@ static struct poptOption long_daemon_options[] = {
322    {"protocol",         0,  POPT_ARG_INT,    &protocol_version, 0, 0, 0 },
323    {"server",           0,  POPT_ARG_NONE,   &am_server, 0, 0, 0 },
324    {"temp-dir",        'T', POPT_ARG_STRING, &tmpdir, 0, 0, 0 },
325 +#ifdef HAVE_OPENSSL
326 +  {"ssl",              0,  POPT_ARG_NONE,   0, OPT_USE_SSL, 0, 0},
327 +  {"ssl-cert",         0,  POPT_ARG_STRING, &ssl_cert_path, OPT_USE_SSL, 0, 0},
328 +  {"ssl-key",          0,  POPT_ARG_STRING, &ssl_key_path, OPT_USE_SSL, 0, 0},
329 +  {"ssl-key-passwd",   0,  POPT_ARG_STRING, &ssl_key_passwd, OPT_USE_SSL, 0, 0},
330 +  {"ssl-ca-certs",     0,  POPT_ARG_STRING, &ssl_ca_path, OPT_USE_SSL, 0, 0},
331 +#endif
332    {"verbose",         'v', POPT_ARG_NONE,   0, 'v', 0, 0 },
333    {"no-verbose",       0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
334    {"no-v",             0,  POPT_ARG_VAL,    &verbose, 0, 0, 0 },
335 @@ -1359,6 +1399,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
336                                         verbose++;
337                                         break;
338  
339 +#ifdef HAVE_OPENSSL
340 +                               case OPT_USE_SSL:
341 +                                       use_ssl = 1;
342 +                                       break;
343 +#endif
344 +
345                                 default:
346                                         rprintf(FERROR,
347                                             "rsync: %s: %s (in daemon mode)\n",
348 @@ -1385,6 +1431,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
349                                 exit_cleanup(RERR_SYNTAX);
350                         }
351  
352 +#ifdef HAVE_OPENSSL
353 +                       if (use_ssl) {
354 +                               if (init_tls()) {
355 +                                       snprintf(err_buf, sizeof(err_buf),
356 +                                                "Openssl error: %s\n",
357 +                                                get_ssl_error());
358 +                                       return 0;
359 +                               }
360 +                       }
361 +#endif
362 +
363                         *argv_p = argv = poptGetArgs(pc);
364                         *argc_p = argc = count_args(argv);
365                         am_starting_up = 0;
366 @@ -1744,6 +1801,12 @@ int parse_arguments(int *argc_p, const char ***argv_p)
367                         return 0;
368  #endif
369  
370 +#ifdef HAVE_OPENSSL
371 +               case OPT_USE_SSL:
372 +                       use_ssl = 1;
373 +                       break;
374 +#endif
375 +
376                 default:
377                         /* A large opt value means that set_refuse_options()
378                          * turned this option off. */
379 @@ -2126,6 +2189,17 @@ int parse_arguments(int *argc_p, const char ***argv_p)
380         if (delay_updates && !partial_dir)
381                 partial_dir = tmp_partialdir;
382  
383 +#ifdef HAVE_OPENSSL
384 +       if (use_ssl) {
385 +               if (init_tls()) {
386 +                       snprintf(err_buf, sizeof(err_buf),
387 +                                "Openssl error: %s\n",
388 +                                get_ssl_error());
389 +                       return 0;
390 +               }
391 +       }
392 +#endif
393 +
394         if (inplace) {
395  #ifdef HAVE_FTRUNCATE
396                 if (partial_dir) {
397 @@ -2716,9 +2790,18 @@ char *check_for_hostspec(char *s, char **host_ptr, int *port_ptr)
398  {
399         char *path;
400  
401 -       if (port_ptr && strncasecmp(URL_PREFIX, s, strlen(URL_PREFIX)) == 0) {
402 -               *host_ptr = parse_hostspec(s + strlen(URL_PREFIX), &path, port_ptr);
403 -               if (*host_ptr) {
404 +       if (port_ptr) {
405 +               int url_prefix_len;
406 +               if (strncasecmp(URL_PREFIX, s, sizeof URL_PREFIX - 1) == 0)
407 +                       url_prefix_len = sizeof URL_PREFIX - 1;
408 +               else if (strncasecmp(SSL_URL_PREFIX, s, sizeof SSL_URL_PREFIX - 1) == 0) {
409 +                       if (!use_ssl)
410 +                               init_tls();
411 +                       use_ssl = 1;
412 +                       url_prefix_len = sizeof SSL_URL_PREFIX - 1;
413 +               } else
414 +                       url_prefix_len = 0;
415 +               if (url_prefix_len && (*host_ptr = parse_hostspec(s + url_prefix_len, &path, port_ptr))) {
416                         if (!*port_ptr)
417                                 *port_ptr = RSYNC_PORT;
418                         return path;
419 diff --git a/rsync.h b/rsync.h
420 --- a/rsync.h
421 +++ b/rsync.h
422 @@ -31,6 +31,7 @@
423  
424  #define DEFAULT_LOCK_FILE "/var/run/rsyncd.lock"
425  #define URL_PREFIX "rsync://"
426 +#define SSL_URL_PREFIX "rsyncs://"
427  
428  #define SYMLINK_PREFIX "/rsyncd-munged/"  /* This MUST have a trailing slash! */
429  #define SYMLINK_PREFIX_LEN ((int)sizeof SYMLINK_PREFIX - 1)
430 @@ -577,6 +578,11 @@ typedef unsigned int size_t;
431  # define SIZEOF_INT64 SIZEOF_OFF_T
432  #endif
433  
434 +#ifdef HAVE_OPENSSL
435 +#include <openssl/ssl.h>
436 +#include <openssl/err.h>
437 +#endif
438 +
439  struct hashtable {
440         void *nodes;
441         int32 size, entries;
442 diff --git a/ssl.c b/ssl.c
443 new file mode 100644
444 --- /dev/null
445 +++ b/ssl.c
446 @@ -0,0 +1,369 @@
447 +/* -*- c-file-style: "linux" -*-
448 + * ssl.c: operations for negotiating SSL rsync connections.
449 + *
450 + * Copyright (C) 2003  Casey Marshall <rsdio@metastatic.org>
451 + *
452 + * This program is free software; you can redistribute it and/or modify
453 + * it under the terms of the GNU General Public License as published by
454 + * the Free Software Foundation; either version 2 of the License, or
455 + * (at your option) any later version.
456 + *
457 + * This program is distributed in the hope that it will be useful,
458 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
459 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
460 + * GNU General Public License for more details.
461 + *
462 + * You should have received a copy of the GNU General Public License
463 + * along with this program; if not, write to the Free Software
464 + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
465 + */
466 +
467 +#include "rsync.h"
468 +
469 +#ifdef HAVE_SYS_SELECT_H
470 +#include <sys/select.h>
471 +#else
472 +#include <sys/time.h>
473 +#include <sys/types.h>
474 +#include <unistd.h>
475 +#endif
476 +#include <string.h>
477 +
478 +#define BUF_SIZE 1024
479 +
480 +extern int am_daemon;
481 +extern int am_server;
482 +
483 +extern char *ssl_cert_path;
484 +extern char *ssl_key_path;
485 +extern char *ssl_key_passwd;
486 +extern char *ssl_ca_path;
487 +
488 +static SSL_CTX *ssl_ctx;
489 +static SSL *ssl;
490 +static int tls_read[2] = { -1, -1 };
491 +static int tls_write[2] = { -1, -1 };
492 +static int ssl_running;
493 +static int ssl_pid = -1;
494 +
495 +#ifdef HAVE_SIGACTION
496 +static struct sigaction sigact;
497 +#endif
498 +
499 +/**
500 + * A non-interactive callback to be passed to SSL_CTX_set_default_password_cb,
501 + * which merely copies the value of ssl_key_passwd into buf. This is
502 + * used for when the private key password is supplied via an option.
503 + */
504 +static int default_password_cb(char *buf, int n, UNUSED(int f), UNUSED(void *u))
505 +{
506 +       if (ssl_key_passwd == NULL || n < (int)strlen(ssl_key_passwd))
507 +               return 0;
508 +       strncpy(buf, ssl_key_passwd, n-1);
509 +       return strlen(ssl_key_passwd);
510 +}
511 +
512 +/**
513 + * If verbose, this method traces the status of the SSL handshake.
514 + */
515 +static void info_callback(const SSL *ssl, int cb, int val)
516 +{
517 +       char buf[128];
518 +       char *cbs;
519 +
520 +       switch (cb) {
521 +       case SSL_CB_LOOP:
522 +               cbs = "SSL_CB_LOOP";
523 +               break;
524 +       case SSL_CB_EXIT:
525 +               cbs = "SSL_CB_EXIT";
526 +               break;
527 +       case SSL_CB_READ:
528 +               cbs = "SSL_CB_READ";
529 +               break;
530 +       case SSL_CB_WRITE:
531 +               cbs = "SSL_CB_WRITE";
532 +               break;
533 +       case SSL_CB_ALERT:
534 +               cbs = "SSL_CB_ALERT";
535 +               break;
536 +       case SSL_CB_READ_ALERT:
537 +               cbs = "SSL_CB_READ_ALERT";
538 +               break;
539 +       case SSL_CB_WRITE_ALERT:
540 +               cbs = "SSL_CB_WRITE_ALERT";
541 +               break;
542 +       case SSL_CB_ACCEPT_LOOP:
543 +               cbs = "SSL_CB_ACCEPT_LOOP";
544 +               break;
545 +       case SSL_CB_ACCEPT_EXIT:
546 +               cbs = "SSL_CB_ACCEPT_EXIT";
547 +               break;
548 +       case SSL_CB_CONNECT_LOOP:
549 +               cbs = "SSL_CB_CONNECT_LOOP";
550 +               break;
551 +       case SSL_CB_CONNECT_EXIT:
552 +               cbs = "SSL_CB_CONNECT_EXIT";
553 +               break;
554 +       case SSL_CB_HANDSHAKE_START:
555 +               cbs = "SSL_CB_HANDSHAKE_START";
556 +               break;
557 +       case SSL_CB_HANDSHAKE_DONE:
558 +               cbs = "SSL_CB_HANDSHAKE_DONE";
559 +               break;
560 +       default:
561 +               snprintf(buf, sizeof buf, "??? (%d)", cb);
562 +               cbs = buf;
563 +               break;
564 +       }
565 +       if (DEBUG_GTE(CONNECT, 1)) {
566 +               rprintf(FLOG, "SSL: info_callback(%p,%s,%d)\n", ssl, cbs, val);
567 +               if (cb == SSL_CB_HANDSHAKE_DONE) {
568 +                       SSL_CIPHER_description(SSL_get_current_cipher((SSL*)ssl),
569 +                                              buf, sizeof buf);
570 +                       rprintf(FLOG, "SSL: cipher: %s", buf);
571 +               }
572 +       }
573 +}
574 +
575 +/**
576 + * Initializes the SSL context for TLSv1 connections; returns zero on
577 + * success.
578 + */
579 +int init_tls(void)
580 +{
581 +       if (ssl_ctx)
582 +               return 0;
583 +       SSL_library_init();
584 +       SSL_load_error_strings();
585 +       ssl_ctx = SSL_CTX_new(TLSv1_method());
586 +       if (!ssl_ctx)
587 +               return 1;
588 +       SSL_CTX_set_info_callback(ssl_ctx, info_callback);
589 +
590 +       /* Sets the certificate sent to the other party. */
591 +       if (ssl_cert_path != NULL
592 +           && SSL_CTX_use_certificate_file(ssl_ctx, ssl_cert_path,
593 +                                           SSL_FILETYPE_PEM) != 1)
594 +               return 1;
595 +       /* Set up the simple non-interactive callback if the password
596 +        * was supplied on the command line. */
597 +       if (ssl_key_passwd != NULL)
598 +               SSL_CTX_set_default_passwd_cb(ssl_ctx, default_password_cb);
599 +       /* Sets the private key that matches the public certificate. */
600 +       if (ssl_key_path != NULL) {
601 +               if (SSL_CTX_use_PrivateKey_file(ssl_ctx, ssl_key_path,
602 +                                               SSL_FILETYPE_PEM) != 1)
603 +                       return 1;
604 +               if (SSL_CTX_check_private_key(ssl_ctx) != 1)
605 +                       return 1;
606 +       }
607 +       if (ssl_ca_path != NULL
608 +           && !SSL_CTX_load_verify_locations(ssl_ctx, ssl_ca_path, NULL))
609 +               return 1;
610 +
611 +       return 0;
612 +}
613 +
614 +/**
615 + * Returns the error string for the current SSL error, if any.
616 + */
617 +char *get_ssl_error(void)
618 +{
619 +       return ERR_error_string(ERR_get_error(), NULL);
620 +}
621 +
622 +/**
623 + * Returns the input file descriptor for the SSL connection.
624 + */
625 +int get_tls_rfd(void)
626 +{
627 +       return tls_read[0];
628 +}
629 +
630 +/**
631 + * Returns the output file descriptor for the SSL connection.
632 + */
633 +int get_tls_wfd(void)
634 +{
635 +       return tls_write[1];
636 +}
637 +
638 +/**
639 + * Signal handler that ends the SSL connection.
640 + */
641 +static RETSIGTYPE tls_sigusr1(int UNUSED(val))
642 +{
643 +       if (ssl) {
644 +               SSL_shutdown(ssl);
645 +               SSL_free(ssl);
646 +               ssl = NULL;
647 +       }
648 +       ssl_running = 0;
649 +}
650 +
651 +/**
652 + * Negotiates the TLS connection, creates a socket pair for communicating
653 + * with the rsync process, then forks into a new process that will handle
654 + * the communication.
655 + *
656 + * 0 is returned on success.
657 + */
658 +int start_tls(int f_in, int f_out)
659 +{
660 +       int tls_fd;
661 +       int n = 0, r;
662 +       unsigned char buf1[BUF_SIZE], buf2[BUF_SIZE];
663 +       int avail1 = 0, avail2 = 0, write1 = 0, write2 = 0;
664 +       fd_set rd, wd;
665 +
666 +       if (fd_pair(tls_read))
667 +               return 1;
668 +       if (fd_pair(tls_write))
669 +               return 1;
670 +
671 +       set_blocking(tls_read[0]);
672 +       set_blocking(tls_read[1]);
673 +       set_blocking(tls_write[0]);
674 +       set_blocking(tls_write[1]);
675 +       set_blocking(f_in);
676 +       set_blocking(f_out);
677 +
678 +       ssl_pid = do_fork();
679 +       if (ssl_pid < 0)
680 +               return -1;
681 +       if (ssl_pid != 0) {
682 +               close(tls_write[0]);
683 +               close(tls_read[1]);
684 +               return 0;
685 +       }
686 +
687 +       SIGACTION(SIGUSR1, tls_sigusr1);
688 +       ssl = SSL_new(ssl_ctx);
689 +       if (!ssl)
690 +               goto closed;
691 +       if (am_daemon || am_server)
692 +               SSL_set_accept_state(ssl);
693 +       else
694 +               SSL_set_connect_state(ssl);
695 +       SSL_set_rfd(ssl, f_in);
696 +       SSL_set_wfd(ssl, f_out);
697 +
698 +       tls_fd = SSL_get_fd(ssl);
699 +       n = tls_write[0];
700 +       n = MAX(tls_read[1], n);
701 +       n = MAX(tls_fd, n) + 1;
702 +
703 +       ssl_running = 1;
704 +       while (ssl_running) {
705 +               FD_ZERO(&rd);
706 +               FD_ZERO(&wd);
707 +               FD_SET(tls_write[0], &rd);
708 +               FD_SET(tls_read[1], &wd);
709 +               FD_SET(tls_fd, &rd);
710 +               FD_SET(tls_fd, &wd);
711 +
712 +               r = select(n, &rd, &wd, NULL, NULL);
713 +
714 +               if (r == -1 && errno == EINTR)
715 +                       continue;
716 +               if (FD_ISSET(tls_write[0], &rd)) {
717 +                       r = read(tls_write[0], buf1+avail1, BUF_SIZE-avail1);
718 +                       if (r >= 0)
719 +                               avail1 += r;
720 +                       else {
721 +                               rprintf(FERROR, "pipe read error: %s\n",
722 +                                       strerror(errno));
723 +                               break;
724 +                       }
725 +               }
726 +               if (FD_ISSET(tls_fd, &rd)) {
727 +                       r = SSL_read(ssl, buf2+avail2, BUF_SIZE-avail2);
728 +                       if (r > 0)
729 +                               avail2 += r;
730 +                       else {
731 +                               switch (SSL_get_error(ssl, r)) {
732 +                               case SSL_ERROR_ZERO_RETURN:
733 +                                       goto closed;
734 +                               case SSL_ERROR_WANT_READ:
735 +                               case SSL_ERROR_WANT_WRITE:
736 +                                       break;
737 +                               case SSL_ERROR_SYSCALL:
738 +                                       if (r == 0)
739 +                                               rprintf(FERROR, "SSL spurious EOF\n");
740 +                                       else
741 +                                               rprintf(FERROR, "SSL I/O error: %s\n",
742 +                                                       strerror(errno));
743 +                                       goto closed;
744 +                               case SSL_ERROR_SSL:
745 +                                       rprintf(FERROR, "SSL: %s\n",
746 +                                               ERR_error_string(ERR_get_error(), NULL));
747 +                                       goto closed;
748 +                               default:
749 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
750 +                                       goto closed;
751 +                               }
752 +                       }
753 +               }
754 +               if (FD_ISSET(tls_read[1], &wd) && write2 < avail2) {
755 +                       r = write(tls_read[1], buf2+write2, avail2-write2);
756 +                       if (r >= 0)
757 +                               write2 += r;
758 +                       else {
759 +                               rprintf(FERROR, "pipe write error: %s\n",
760 +                                       strerror(errno));
761 +                               break;
762 +                       }
763 +               }
764 +               if (FD_ISSET(tls_fd, &wd) && write1 < avail1) {
765 +                       r = SSL_write(ssl, buf1+write1, avail1-write1);
766 +                       if (r > 0)
767 +                               write1 += r;
768 +                       else {
769 +                               switch (SSL_get_error(ssl, r)) {
770 +                               case SSL_ERROR_ZERO_RETURN:
771 +                                       goto closed;
772 +                               case SSL_ERROR_WANT_READ:
773 +                               case SSL_ERROR_WANT_WRITE:
774 +                                       break;
775 +                               case SSL_ERROR_SYSCALL:
776 +                                       if (r == 0)
777 +                                               rprintf(FERROR, "SSL: spurious EOF\n");
778 +                                       else
779 +                                               rprintf(FERROR, "SSL: I/O error: %s\n",
780 +                                                       strerror(errno));
781 +                                       goto closed;
782 +                               case SSL_ERROR_SSL:
783 +                                       rprintf(FERROR, "SSL: %s\n",
784 +                                               ERR_error_string(ERR_get_error(), NULL));
785 +                                       goto closed;
786 +                               default:
787 +                                       rprintf(FERROR, "unexpected ssl error %d\n", r);
788 +                                       goto closed;
789 +                               }
790 +                       }
791 +               }
792 +               if (avail1 == write1)
793 +                       avail1 = write1 = 0;
794 +               if (avail2 == write2)
795 +                       avail2 = write2 = 0;
796 +       }
797 +
798 +       /* XXX I'm pretty sure that there is a lot that I am not considering
799 +          here. Bugs? Yes, probably. */
800 +
801 +       /* We're finished. */
802 +    closed:
803 +       close(tls_read[1]);
804 +       close(tls_write[0]);
805 +       exit(0);
806 +}
807 +
808 +/**
809 + * Ends the TLS connection.
810 + */
811 +void end_tls(void)
812 +{
813 +       if (ssl_pid > 0)
814 +               kill(ssl_pid, SIGUSR1);
815 +}