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