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