Merge "citrix" branch into "master".
[sliver-openvswitch.git] / lib / stream-ssl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "stream-ssl.h"
19 #include "dhparams.h"
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <string.h>
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/ssl.h>
28 #include <openssl/x509v3.h>
29 #include <poll.h>
30 #include <sys/fcntl.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33 #include "dynamic-string.h"
34 #include "leak-checker.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "socket-util.h"
40 #include "socket-util.h"
41 #include "util.h"
42 #include "stream-provider.h"
43 #include "stream.h"
44 #include "timeval.h"
45
46 #include "vlog.h"
47 #define THIS_MODULE VLM_stream_ssl
48
49 /* Active SSL. */
50
51 enum ssl_state {
52     STATE_TCP_CONNECTING,
53     STATE_SSL_CONNECTING
54 };
55
56 enum session_type {
57     CLIENT,
58     SERVER
59 };
60
61 struct ssl_stream
62 {
63     struct stream stream;
64     enum ssl_state state;
65     int connect_error;
66     enum session_type type;
67     int fd;
68     SSL *ssl;
69     struct ofpbuf *txbuf;
70
71     /* rx_want and tx_want record the result of the last call to SSL_read()
72      * and SSL_write(), respectively:
73      *
74      *    - If the call reported that data needed to be read from the file
75      *      descriptor, the corresponding member is set to SSL_READING.
76      *
77      *    - If the call reported that data needed to be written to the file
78      *      descriptor, the corresponding member is set to SSL_WRITING.
79      *
80      *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
81      *      call completed successfully (or with an error) and that there is no
82      *      need to block.
83      *
84      * These are needed because there is no way to ask OpenSSL what a data read
85      * or write would require without giving it a buffer to receive into or
86      * data to send, respectively.  (Note that the SSL_want() status is
87      * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
88      * its value.)
89      *
90      * A single call to SSL_read() or SSL_write() can perform both reading
91      * and writing and thus invalidate not one of these values but actually
92      * both.  Consider this situation, for example:
93      *
94      *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
95      *
96      *    - SSL_read() laters succeeds reading from 'fd' and clears out the
97      *      whole receive buffer, so rx_want gets SSL_READING.
98      *
99      *    - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
100      *      and blocks.
101      *
102      *    - Now we're stuck blocking until the peer sends us data, even though
103      *      SSL_write() could now succeed, which could easily be a deadlock
104      *      condition.
105      *
106      * On the other hand, we can't reset both tx_want and rx_want on every call
107      * to SSL_read() or SSL_write(), because that would produce livelock,
108      * e.g. in this situation:
109      *
110      *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
111      *
112      *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
113      *      but tx_want gets reset to SSL_NOTHING.
114      *
115      *    - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
116      *      and blocks.
117      *
118      *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
119      *      that no blocking is necessary.
120      *
121      * The solution we adopt here is to set tx_want to SSL_NOTHING after
122      * calling SSL_read() only if the SSL state of the connection changed,
123      * which indicates that an SSL-level renegotiation made some progress, and
124      * similarly for rx_want and SSL_write().  This prevents both the
125      * deadlock and livelock situations above.
126      */
127     int rx_want, tx_want;
128 };
129
130 /* SSL context created by ssl_init(). */
131 static SSL_CTX *ctx;
132
133 struct ssl_config_file {
134     bool read;                  /* Whether the file was successfully read. */
135     char *file_name;            /* Configured file name, if any. */
136     struct timespec mtime;      /* File mtime as of last time we read it. */
137 };
138
139 /* SSL configuration files. */
140 static struct ssl_config_file private_key;
141 static struct ssl_config_file certificate;
142 static struct ssl_config_file ca_cert;
143
144 /* Ordinarily, we require a CA certificate for the peer to be locally
145  * available.  We can, however, bootstrap the CA certificate from the peer at
146  * the beginning of our first connection then use that certificate on all
147  * subsequent connections, saving it to a file for use in future runs also.  In
148  * this case, 'bootstrap_ca_cert' is true. */
149 static bool bootstrap_ca_cert;
150
151 /* Who knows what can trigger various SSL errors, so let's throttle them down
152  * quite a bit. */
153 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
154
155 static int ssl_init(void);
156 static int do_ssl_init(void);
157 static bool ssl_wants_io(int ssl_error);
158 static void ssl_close(struct stream *);
159 static void ssl_clear_txbuf(struct ssl_stream *);
160 static int interpret_ssl_error(const char *function, int ret, int error,
161                                int *want);
162 static DH *tmp_dh_callback(SSL *ssl, int is_export OVS_UNUSED, int keylength);
163 static void log_ca_cert(const char *file_name, X509 *cert);
164 static void stream_ssl_set_ca_cert_file__(const char *file_name,
165                                           bool bootstrap);
166
167 static short int
168 want_to_poll_events(int want)
169 {
170     switch (want) {
171     case SSL_NOTHING:
172         NOT_REACHED();
173
174     case SSL_READING:
175         return POLLIN;
176
177     case SSL_WRITING:
178         return POLLOUT;
179
180     default:
181         NOT_REACHED();
182     }
183 }
184
185 static int
186 new_ssl_stream(const char *name, int fd, enum session_type type,
187               enum ssl_state state, const struct sockaddr_in *remote,
188               struct stream **streamp)
189 {
190     struct sockaddr_in local;
191     socklen_t local_len = sizeof local;
192     struct ssl_stream *sslv;
193     SSL *ssl = NULL;
194     int on = 1;
195     int retval;
196
197     /* Check for all the needful configuration. */
198     retval = 0;
199     if (!private_key.read) {
200         VLOG_ERR("Private key must be configured to use SSL");
201         retval = ENOPROTOOPT;
202     }
203     if (!certificate.read) {
204         VLOG_ERR("Certificate must be configured to use SSL");
205         retval = ENOPROTOOPT;
206     }
207     if (!ca_cert.read && !bootstrap_ca_cert) {
208         VLOG_ERR("CA certificate must be configured to use SSL");
209         retval = ENOPROTOOPT;
210     }
211     if (!SSL_CTX_check_private_key(ctx)) {
212         VLOG_ERR("Private key does not match certificate public key: %s",
213                  ERR_error_string(ERR_get_error(), NULL));
214         retval = ENOPROTOOPT;
215     }
216     if (retval) {
217         goto error;
218     }
219
220     /* Get the local IP and port information */
221     retval = getsockname(fd, (struct sockaddr *) &local, &local_len);
222     if (retval) {
223         memset(&local, 0, sizeof local);
224     }
225
226     /* Disable Nagle. */
227     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
228     if (retval) {
229         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
230         retval = errno;
231         goto error;
232     }
233
234     /* Create and configure OpenSSL stream. */
235     ssl = SSL_new(ctx);
236     if (ssl == NULL) {
237         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
238         retval = ENOPROTOOPT;
239         goto error;
240     }
241     if (SSL_set_fd(ssl, fd) == 0) {
242         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
243         retval = ENOPROTOOPT;
244         goto error;
245     }
246     if (bootstrap_ca_cert && type == CLIENT) {
247         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
248     }
249
250     /* Create and return the ssl_stream. */
251     sslv = xmalloc(sizeof *sslv);
252     stream_init(&sslv->stream, &ssl_stream_class, EAGAIN, name);
253     stream_set_remote_ip(&sslv->stream, remote->sin_addr.s_addr);
254     stream_set_remote_port(&sslv->stream, remote->sin_port);
255     stream_set_local_ip(&sslv->stream, local.sin_addr.s_addr);
256     stream_set_local_port(&sslv->stream, local.sin_port);
257     sslv->state = state;
258     sslv->type = type;
259     sslv->fd = fd;
260     sslv->ssl = ssl;
261     sslv->txbuf = NULL;
262     sslv->rx_want = sslv->tx_want = SSL_NOTHING;
263     *streamp = &sslv->stream;
264     return 0;
265
266 error:
267     if (ssl) {
268         SSL_free(ssl);
269     }
270     close(fd);
271     return retval;
272 }
273
274 static struct ssl_stream *
275 ssl_stream_cast(struct stream *stream)
276 {
277     stream_assert_class(stream, &ssl_stream_class);
278     return CONTAINER_OF(stream, struct ssl_stream, stream);
279 }
280
281 static int
282 ssl_open(const char *name, char *suffix, struct stream **streamp)
283 {
284     struct sockaddr_in sin;
285     int error, fd;
286
287     error = ssl_init();
288     if (error) {
289         return error;
290     }
291
292     error = inet_open_active(SOCK_STREAM, suffix, OFP_SSL_PORT, &sin, &fd);
293     if (fd >= 0) {
294         int state = error ? STATE_TCP_CONNECTING : STATE_SSL_CONNECTING;
295         return new_ssl_stream(name, fd, CLIENT, state, &sin, streamp);
296     } else {
297         VLOG_ERR("%s: connect: %s", name, strerror(error));
298         return error;
299     }
300 }
301
302 static int
303 do_ca_cert_bootstrap(struct stream *stream)
304 {
305     struct ssl_stream *sslv = ssl_stream_cast(stream);
306     STACK_OF(X509) *chain;
307     X509 *cert;
308     FILE *file;
309     int error;
310     int fd;
311
312     chain = SSL_get_peer_cert_chain(sslv->ssl);
313     if (!chain || !sk_X509_num(chain)) {
314         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
315                  "peer");
316         return EPROTO;
317     }
318     cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
319
320     /* Check that 'cert' is self-signed.  Otherwise it is not a CA
321      * certificate and we should not attempt to use it as one. */
322     error = X509_check_issued(cert, cert);
323     if (error) {
324         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
325                  "not self-signed (%s)",
326                  X509_verify_cert_error_string(error));
327         if (sk_X509_num(chain) < 2) {
328             VLOG_ERR("only one certificate was received, so probably the peer "
329                      "is not configured to send its CA certificate");
330         }
331         return EPROTO;
332     }
333
334     fd = open(ca_cert.file_name, O_CREAT | O_EXCL | O_WRONLY, 0444);
335     if (fd < 0) {
336         if (errno == EEXIST) {
337             VLOG_INFO("CA cert %s created by another process",
338                       ca_cert.file_name);
339             /* We'll read it the next time around the main loop because
340              * update_ssl_config() will see that it now exists. */
341             return EPROTO;
342         } else {
343             VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
344                      ca_cert.file_name, strerror(errno));
345             return errno;
346         }
347     }
348
349     file = fdopen(fd, "w");
350     if (!file) {
351         int error = errno;
352         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
353                  strerror(error));
354         unlink(ca_cert.file_name);
355         return error;
356     }
357
358     if (!PEM_write_X509(file, cert)) {
359         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
360                  "%s", ca_cert.file_name,
361                  ERR_error_string(ERR_get_error(), NULL));
362         fclose(file);
363         unlink(ca_cert.file_name);
364         return EIO;
365     }
366
367     if (fclose(file)) {
368         int error = errno;
369         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
370                  ca_cert.file_name, strerror(error));
371         unlink(ca_cert.file_name);
372         return error;
373     }
374
375     VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert.file_name);
376     log_ca_cert(ca_cert.file_name, cert);
377     bootstrap_ca_cert = false;
378     ca_cert.read = true;
379
380     /* SSL_CTX_add_client_CA makes a copy of cert's relevant data. */
381     SSL_CTX_add_client_CA(ctx, cert);
382
383     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
384      * 'cert' is owned by sslv->ssl, so we need to duplicate it. */
385     cert = X509_dup(cert);
386     if (!cert) {
387         out_of_memory();
388     }
389     if (SSL_CTX_load_verify_locations(ctx, ca_cert.file_name, NULL) != 1) {
390         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
391                  ERR_error_string(ERR_get_error(), NULL));
392         return EPROTO;
393     }
394     VLOG_INFO("killing successful connection to retry using CA cert");
395     return EPROTO;
396 }
397
398 static int
399 ssl_connect(struct stream *stream)
400 {
401     struct ssl_stream *sslv = ssl_stream_cast(stream);
402     int retval;
403
404     switch (sslv->state) {
405     case STATE_TCP_CONNECTING:
406         retval = check_connection_completion(sslv->fd);
407         if (retval) {
408             return retval;
409         }
410         sslv->state = STATE_SSL_CONNECTING;
411         /* Fall through. */
412
413     case STATE_SSL_CONNECTING:
414         retval = (sslv->type == CLIENT
415                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
416         if (retval != 1) {
417             int error = SSL_get_error(sslv->ssl, retval);
418             if (retval < 0 && ssl_wants_io(error)) {
419                 return EAGAIN;
420             } else {
421                 int unused;
422                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
423                                      : "SSL_accept"), retval, error, &unused);
424                 shutdown(sslv->fd, SHUT_RDWR);
425                 return EPROTO;
426             }
427         } else if (bootstrap_ca_cert) {
428             return do_ca_cert_bootstrap(stream);
429         } else if ((SSL_get_verify_mode(sslv->ssl)
430                     & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
431                    != SSL_VERIFY_PEER) {
432             /* Two or more SSL connections completed at the same time while we
433              * were in bootstrap mode.  Only one of these can finish the
434              * bootstrap successfully.  The other one(s) must be rejected
435              * because they were not verified against the bootstrapped CA
436              * certificate.  (Alternatively we could verify them against the CA
437              * certificate, but that's more trouble than it's worth.  These
438              * connections will succeed the next time they retry, assuming that
439              * they have a certificate against the correct CA.) */
440             VLOG_ERR("rejecting SSL connection during bootstrap race window");
441             return EPROTO;
442         } else {
443             return 0;
444         }
445     }
446
447     NOT_REACHED();
448 }
449
450 static void
451 ssl_close(struct stream *stream)
452 {
453     struct ssl_stream *sslv = ssl_stream_cast(stream);
454     ssl_clear_txbuf(sslv);
455
456     /* Attempt clean shutdown of the SSL connection.  This will work most of
457      * the time, as long as the kernel send buffer has some free space and the
458      * SSL connection isn't renegotiating, etc.  That has to be good enough,
459      * since we don't have any way to continue the close operation in the
460      * background. */
461     SSL_shutdown(sslv->ssl);
462
463     SSL_free(sslv->ssl);
464     close(sslv->fd);
465     free(sslv);
466 }
467
468 static int
469 interpret_ssl_error(const char *function, int ret, int error,
470                     int *want)
471 {
472     *want = SSL_NOTHING;
473
474     switch (error) {
475     case SSL_ERROR_NONE:
476         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
477         break;
478
479     case SSL_ERROR_ZERO_RETURN:
480         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
481         break;
482
483     case SSL_ERROR_WANT_READ:
484         *want = SSL_READING;
485         return EAGAIN;
486
487     case SSL_ERROR_WANT_WRITE:
488         *want = SSL_WRITING;
489         return EAGAIN;
490
491     case SSL_ERROR_WANT_CONNECT:
492         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
493         break;
494
495     case SSL_ERROR_WANT_ACCEPT:
496         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
497         break;
498
499     case SSL_ERROR_WANT_X509_LOOKUP:
500         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
501                     function);
502         break;
503
504     case SSL_ERROR_SYSCALL: {
505         int queued_error = ERR_get_error();
506         if (queued_error == 0) {
507             if (ret < 0) {
508                 int status = errno;
509                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
510                              function, strerror(status));
511                 return status;
512             } else {
513                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
514                              function);
515                 return EPROTO;
516             }
517         } else {
518             VLOG_WARN_RL(&rl, "%s: %s",
519                          function, ERR_error_string(queued_error, NULL));
520             break;
521         }
522     }
523
524     case SSL_ERROR_SSL: {
525         int queued_error = ERR_get_error();
526         if (queued_error != 0) {
527             VLOG_WARN_RL(&rl, "%s: %s",
528                          function, ERR_error_string(queued_error, NULL));
529         } else {
530             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
531                         function);
532         }
533         break;
534     }
535
536     default:
537         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
538         break;
539     }
540     return EIO;
541 }
542
543 static ssize_t
544 ssl_recv(struct stream *stream, void *buffer, size_t n)
545 {
546     struct ssl_stream *sslv = ssl_stream_cast(stream);
547     int old_state;
548     ssize_t ret;
549
550     /* Behavior of zero-byte SSL_read is poorly defined. */
551     assert(n > 0);
552
553     old_state = SSL_get_state(sslv->ssl);
554     ret = SSL_read(sslv->ssl, buffer, n);
555     if (old_state != SSL_get_state(sslv->ssl)) {
556         sslv->tx_want = SSL_NOTHING;
557     }
558     sslv->rx_want = SSL_NOTHING;
559
560     if (ret > 0) {
561         return ret;
562     } else {
563         int error = SSL_get_error(sslv->ssl, ret);
564         if (error == SSL_ERROR_ZERO_RETURN) {
565             return 0;
566         } else {
567             return -interpret_ssl_error("SSL_read", ret, error,
568                                         &sslv->rx_want);
569         }
570     }
571 }
572
573 static void
574 ssl_clear_txbuf(struct ssl_stream *sslv)
575 {
576     ofpbuf_delete(sslv->txbuf);
577     sslv->txbuf = NULL;
578 }
579
580 static int
581 ssl_do_tx(struct stream *stream)
582 {
583     struct ssl_stream *sslv = ssl_stream_cast(stream);
584
585     for (;;) {
586         int old_state = SSL_get_state(sslv->ssl);
587         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
588         if (old_state != SSL_get_state(sslv->ssl)) {
589             sslv->rx_want = SSL_NOTHING;
590         }
591         sslv->tx_want = SSL_NOTHING;
592         if (ret > 0) {
593             ofpbuf_pull(sslv->txbuf, ret);
594             if (sslv->txbuf->size == 0) {
595                 return 0;
596             }
597         } else {
598             int ssl_error = SSL_get_error(sslv->ssl, ret);
599             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
600                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
601                 return EPIPE;
602             } else {
603                 return interpret_ssl_error("SSL_write", ret, ssl_error,
604                                            &sslv->tx_want);
605             }
606         }
607     }
608 }
609
610 static ssize_t
611 ssl_send(struct stream *stream, const void *buffer, size_t n)
612 {
613     struct ssl_stream *sslv = ssl_stream_cast(stream);
614
615     if (sslv->txbuf) {
616         return -EAGAIN;
617     } else {
618         int error;
619
620         sslv->txbuf = ofpbuf_clone_data(buffer, n);
621         error = ssl_do_tx(stream);
622         switch (error) {
623         case 0:
624             ssl_clear_txbuf(sslv);
625             return n;
626         case EAGAIN:
627             leak_checker_claim(buffer);
628             return n;
629         default:
630             sslv->txbuf = NULL;
631             return -error;
632         }
633     }
634 }
635
636 static void
637 ssl_run(struct stream *stream)
638 {
639     struct ssl_stream *sslv = ssl_stream_cast(stream);
640
641     if (sslv->txbuf && ssl_do_tx(stream) != EAGAIN) {
642         ssl_clear_txbuf(sslv);
643     }
644 }
645
646 static void
647 ssl_run_wait(struct stream *stream)
648 {
649     struct ssl_stream *sslv = ssl_stream_cast(stream);
650
651     if (sslv->tx_want != SSL_NOTHING) {
652         poll_fd_wait(sslv->fd, want_to_poll_events(sslv->tx_want));
653     }
654 }
655
656 static void
657 ssl_wait(struct stream *stream, enum stream_wait_type wait)
658 {
659     struct ssl_stream *sslv = ssl_stream_cast(stream);
660
661     switch (wait) {
662     case STREAM_CONNECT:
663         if (stream_connect(stream) != EAGAIN) {
664             poll_immediate_wake();
665         } else {
666             switch (sslv->state) {
667             case STATE_TCP_CONNECTING:
668                 poll_fd_wait(sslv->fd, POLLOUT);
669                 break;
670
671             case STATE_SSL_CONNECTING:
672                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
673                  * set up the status that we test here. */
674                 poll_fd_wait(sslv->fd,
675                              want_to_poll_events(SSL_want(sslv->ssl)));
676                 break;
677
678             default:
679                 NOT_REACHED();
680             }
681         }
682         break;
683
684     case STREAM_RECV:
685         if (sslv->rx_want != SSL_NOTHING) {
686             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
687         } else {
688             poll_immediate_wake();
689         }
690         break;
691
692     case STREAM_SEND:
693         if (!sslv->txbuf) {
694             /* We have room in our tx queue. */
695             poll_immediate_wake();
696         } else {
697             /* stream_run_wait() will do the right thing; don't bother with
698              * redundancy. */
699         }
700         break;
701
702     default:
703         NOT_REACHED();
704     }
705 }
706
707 struct stream_class ssl_stream_class = {
708     "ssl",                      /* name */
709     ssl_open,                   /* open */
710     ssl_close,                  /* close */
711     ssl_connect,                /* connect */
712     ssl_recv,                   /* recv */
713     ssl_send,                   /* send */
714     ssl_run,                    /* run */
715     ssl_run_wait,               /* run_wait */
716     ssl_wait,                   /* wait */
717 };
718 \f
719 /* Passive SSL. */
720
721 struct pssl_pstream
722 {
723     struct pstream pstream;
724     int fd;
725 };
726
727 struct pstream_class pssl_pstream_class;
728
729 static struct pssl_pstream *
730 pssl_pstream_cast(struct pstream *pstream)
731 {
732     pstream_assert_class(pstream, &pssl_pstream_class);
733     return CONTAINER_OF(pstream, struct pssl_pstream, pstream);
734 }
735
736 static int
737 pssl_open(const char *name OVS_UNUSED, char *suffix, struct pstream **pstreamp)
738 {
739     struct pssl_pstream *pssl;
740     struct sockaddr_in sin;
741     char bound_name[128];
742     int retval;
743     int fd;
744
745     retval = ssl_init();
746     if (retval) {
747         return retval;
748     }
749
750     fd = inet_open_passive(SOCK_STREAM, suffix, OFP_SSL_PORT, &sin);
751     if (fd < 0) {
752         return -fd;
753     }
754     sprintf(bound_name, "pssl:%"PRIu16":"IP_FMT,
755             ntohs(sin.sin_port), IP_ARGS(&sin.sin_addr.s_addr));
756
757     pssl = xmalloc(sizeof *pssl);
758     pstream_init(&pssl->pstream, &pssl_pstream_class, bound_name);
759     pssl->fd = fd;
760     *pstreamp = &pssl->pstream;
761     return 0;
762 }
763
764 static void
765 pssl_close(struct pstream *pstream)
766 {
767     struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
768     close(pssl->fd);
769     free(pssl);
770 }
771
772 static int
773 pssl_accept(struct pstream *pstream, struct stream **new_streamp)
774 {
775     struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
776     struct sockaddr_in sin;
777     socklen_t sin_len = sizeof sin;
778     char name[128];
779     int new_fd;
780     int error;
781
782     new_fd = accept(pssl->fd, &sin, &sin_len);
783     if (new_fd < 0) {
784         int error = errno;
785         if (error != EAGAIN) {
786             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
787         }
788         return error;
789     }
790
791     error = set_nonblocking(new_fd);
792     if (error) {
793         close(new_fd);
794         return error;
795     }
796
797     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
798     if (sin.sin_port != htons(OFP_SSL_PORT)) {
799         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
800     }
801     return new_ssl_stream(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
802                          new_streamp);
803 }
804
805 static void
806 pssl_wait(struct pstream *pstream)
807 {
808     struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
809     poll_fd_wait(pssl->fd, POLLIN);
810 }
811
812 struct pstream_class pssl_pstream_class = {
813     "pssl",
814     pssl_open,
815     pssl_close,
816     pssl_accept,
817     pssl_wait,
818 };
819 \f
820 /*
821  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
822  * OpenSSL is requesting that we call it back when the socket is ready for read
823  * or writing, respectively.
824  */
825 static bool
826 ssl_wants_io(int ssl_error)
827 {
828     return (ssl_error == SSL_ERROR_WANT_WRITE
829             || ssl_error == SSL_ERROR_WANT_READ);
830 }
831
832 static int
833 ssl_init(void)
834 {
835     static int init_status = -1;
836     if (init_status < 0) {
837         init_status = do_ssl_init();
838         assert(init_status >= 0);
839     }
840     return init_status;
841 }
842
843 static int
844 do_ssl_init(void)
845 {
846     SSL_METHOD *method;
847
848     SSL_library_init();
849     SSL_load_error_strings();
850
851     method = TLSv1_method();
852     if (method == NULL) {
853         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
854         return ENOPROTOOPT;
855     }
856
857     ctx = SSL_CTX_new(method);
858     if (ctx == NULL) {
859         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
860         return ENOPROTOOPT;
861     }
862     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
863     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
864     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
865     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
866     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
867                        NULL);
868
869     return 0;
870 }
871
872 static DH *
873 tmp_dh_callback(SSL *ssl OVS_UNUSED, int is_export OVS_UNUSED, int keylength)
874 {
875     struct dh {
876         int keylength;
877         DH *dh;
878         DH *(*constructor)(void);
879     };
880
881     static struct dh dh_table[] = {
882         {1024, NULL, get_dh1024},
883         {2048, NULL, get_dh2048},
884         {4096, NULL, get_dh4096},
885     };
886
887     struct dh *dh;
888
889     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
890         if (dh->keylength == keylength) {
891             if (!dh->dh) {
892                 dh->dh = dh->constructor();
893                 if (!dh->dh) {
894                     ovs_fatal(ENOMEM, "out of memory constructing "
895                               "Diffie-Hellman parameters");
896                 }
897             }
898             return dh->dh;
899         }
900     }
901     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
902                 keylength);
903     return NULL;
904 }
905
906 /* Returns true if SSL is at least partially configured. */
907 bool
908 stream_ssl_is_configured(void) 
909 {
910     return private_key.file_name || certificate.file_name || ca_cert.file_name;
911 }
912
913 static void
914 get_mtime(const char *file_name, struct timespec *mtime)
915 {
916     struct stat s;
917
918     if (!stat(file_name, &s)) {
919         mtime->tv_sec = s.st_mtime;
920
921 #if HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
922         mtime->tv_nsec = s.st_mtim.tv_nsec;
923 #elif HAVE_STRUCT_STAT_ST_MTIMENSEC
924         mtime->tv_nsec = s.st_mtimensec;
925 #else
926         mtime->tv_nsec = 0;
927 #endif
928     } else {
929         mtime->tv_sec = mtime->tv_nsec = 0;
930     }
931 }
932
933 static bool
934 update_ssl_config(struct ssl_config_file *config, const char *file_name)
935 {
936     struct timespec mtime;
937
938     if (ssl_init() || !file_name) {
939         return false;
940     }
941
942     /* If the file name hasn't changed and neither has the file contents, stop
943      * here. */
944     get_mtime(file_name, &mtime);
945     if (config->file_name
946         && !strcmp(config->file_name, file_name)
947         && mtime.tv_sec == config->mtime.tv_sec
948         && mtime.tv_nsec == config->mtime.tv_nsec) {
949         return false;
950     }
951
952     config->mtime = mtime;
953     free(config->file_name);
954     config->file_name = xstrdup(file_name);
955     return true;
956 }
957
958 void
959 stream_ssl_set_private_key_file(const char *file_name)
960 {
961     if (!update_ssl_config(&private_key, file_name)) {
962         return;
963     }
964     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
965         VLOG_ERR("SSL_use_PrivateKey_file: %s",
966                  ERR_error_string(ERR_get_error(), NULL));
967         return;
968     }
969     private_key.read = true;
970 }
971
972 void
973 stream_ssl_set_certificate_file(const char *file_name)
974 {
975     if (!update_ssl_config(&certificate, file_name)) {
976         return;
977     }
978     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
979         VLOG_ERR("SSL_use_certificate_file: %s",
980                  ERR_error_string(ERR_get_error(), NULL));
981         return;
982     }
983     certificate.read = true;
984 }
985
986 /* Reads the X509 certificate or certificates in file 'file_name'.  On success,
987  * stores the address of the first element in an array of pointers to
988  * certificates in '*certs' and the number of certificates in the array in
989  * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
990  * in '*n_certs', and returns a positive errno value.
991  *
992  * The caller is responsible for freeing '*certs'. */
993 static int
994 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
995 {
996     FILE *file;
997     size_t allocated_certs = 0;
998
999     *certs = NULL;
1000     *n_certs = 0;
1001
1002     file = fopen(file_name, "r");
1003     if (!file) {
1004         VLOG_ERR("failed to open %s for reading: %s",
1005                  file_name, strerror(errno));
1006         return errno;
1007     }
1008
1009     for (;;) {
1010         X509 *certificate;
1011         int c;
1012
1013         /* Read certificate from file. */
1014         certificate = PEM_read_X509(file, NULL, NULL, NULL);
1015         if (!certificate) {
1016             size_t i;
1017
1018             VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1019                      file_name, ERR_error_string(ERR_get_error(), NULL));
1020             for (i = 0; i < *n_certs; i++) {
1021                 X509_free((*certs)[i]);
1022             }
1023             free(*certs);
1024             *certs = NULL;
1025             *n_certs = 0;
1026             return EIO;
1027         }
1028
1029         /* Add certificate to array. */
1030         if (*n_certs >= allocated_certs) {
1031             *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1032         }
1033         (*certs)[(*n_certs)++] = certificate;
1034
1035         /* Are there additional certificates in the file? */
1036         do {
1037             c = getc(file);
1038         } while (isspace(c));
1039         if (c == EOF) {
1040             break;
1041         }
1042         ungetc(c, file);
1043     }
1044     fclose(file);
1045     return 0;
1046 }
1047
1048
1049 /* Sets 'file_name' as the name of a file containing one or more X509
1050  * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1051  * certificate to the peer, which enables a switch to pick up the controller's
1052  * CA certificate on its first connection. */
1053 void
1054 stream_ssl_set_peer_ca_cert_file(const char *file_name)
1055 {
1056     X509 **certs;
1057     size_t n_certs;
1058     size_t i;
1059
1060     if (ssl_init()) {
1061         return;
1062     }
1063
1064     if (!read_cert_file(file_name, &certs, &n_certs)) {
1065         for (i = 0; i < n_certs; i++) {
1066             if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1067                 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1068                          ERR_error_string(ERR_get_error(), NULL));
1069             }
1070         }
1071         free(certs);
1072     }
1073 }
1074
1075 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1076 static void
1077 log_ca_cert(const char *file_name, X509 *cert)
1078 {
1079     unsigned char digest[EVP_MAX_MD_SIZE];
1080     unsigned int n_bytes;
1081     struct ds fp;
1082     char *subject;
1083
1084     ds_init(&fp);
1085     if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1086         ds_put_cstr(&fp, "<out of memory>");
1087     } else {
1088         unsigned int i;
1089         for (i = 0; i < n_bytes; i++) {
1090             if (i) {
1091                 ds_put_char(&fp, ':');
1092             }
1093             ds_put_format(&fp, "%02hhx", digest[i]);
1094         }
1095     }
1096     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1097     VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1098               subject ? subject : "<out of memory>", ds_cstr(&fp));
1099     free(subject);
1100     ds_destroy(&fp);
1101 }
1102
1103 static void
1104 stream_ssl_set_ca_cert_file__(const char *file_name, bool bootstrap)
1105 {
1106     X509 **certs;
1107     size_t n_certs;
1108     struct stat s;
1109
1110     if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1111         bootstrap_ca_cert = true;
1112     } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1113         size_t i;
1114
1115         /* Set up list of CAs that the server will accept from the client. */
1116         for (i = 0; i < n_certs; i++) {
1117             /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1118             if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1119                 VLOG_ERR("failed to add client certificate %d from %s: %s",
1120                          i, file_name,
1121                          ERR_error_string(ERR_get_error(), NULL));
1122             } else {
1123                 log_ca_cert(file_name, certs[i]);
1124             }
1125             X509_free(certs[i]);
1126         }
1127         free(certs);
1128
1129         /* Set up CAs for OpenSSL to trust in verifying the peer's
1130          * certificate. */
1131         if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1132             VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1133                      ERR_error_string(ERR_get_error(), NULL));
1134             return;
1135         }
1136
1137         bootstrap_ca_cert = false;
1138     }
1139     ca_cert.read = true;
1140 }
1141
1142 /* Sets 'file_name' as the name of the file from which to read the CA
1143  * certificate used to verify the peer within SSL connections.  If 'bootstrap'
1144  * is false, the file must exist.  If 'bootstrap' is false, then the file is
1145  * read if it is exists; if it does not, then it will be created from the CA
1146  * certificate received from the peer on the first SSL connection. */
1147 void
1148 stream_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1149 {
1150     if (!update_ssl_config(&ca_cert, file_name)) {
1151         return;
1152     }
1153
1154     stream_ssl_set_ca_cert_file__(file_name, bootstrap);
1155 }
1156
1157