brcompatd: Delete VLAN tags only for the correct port in del_port().
[sliver-openvswitch.git] / lib / vconn-ssl.c
1 /*
2  * Copyright (c) 2008, 2009 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 "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 *remote,
185               struct vconn **vconnp)
186 {
187     struct sockaddr_in local;
188     socklen_t local_len = sizeof local;
189     struct ssl_vconn *sslv;
190     SSL *ssl = NULL;
191     int on = 1;
192     int retval;
193
194     /* Check for all the needful configuration. */
195     retval = 0;
196     if (!has_private_key) {
197         VLOG_ERR("Private key must be configured to use SSL");
198         retval = ENOPROTOOPT;
199     }
200     if (!has_certificate) {
201         VLOG_ERR("Certificate must be configured to use SSL");
202         retval = ENOPROTOOPT;
203     }
204     if (!has_ca_cert && !bootstrap_ca_cert) {
205         VLOG_ERR("CA certificate must be configured to use SSL");
206         retval = ENOPROTOOPT;
207     }
208     if (!SSL_CTX_check_private_key(ctx)) {
209         VLOG_ERR("Private key does not match certificate public key: %s",
210                  ERR_error_string(ERR_get_error(), NULL));
211         retval = ENOPROTOOPT;
212     }
213     if (retval) {
214         goto error;
215     }
216
217     /* Get the local IP and port information */
218     retval = getsockname(fd, (struct sockaddr *) &local, &local_len);
219     if (retval) {
220         memset(&local, 0, sizeof local);
221     }
222
223     /* Disable Nagle. */
224     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
225     if (retval) {
226         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
227         retval = errno;
228         goto error;
229     }
230
231     /* Create and configure OpenSSL stream. */
232     ssl = SSL_new(ctx);
233     if (ssl == NULL) {
234         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
235         retval = ENOPROTOOPT;
236         goto error;
237     }
238     if (SSL_set_fd(ssl, fd) == 0) {
239         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
240         retval = ENOPROTOOPT;
241         goto error;
242     }
243     if (bootstrap_ca_cert && type == CLIENT) {
244         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
245     }
246
247     /* Create and return the ssl_vconn. */
248     sslv = xmalloc(sizeof *sslv);
249     vconn_init(&sslv->vconn, &ssl_vconn_class, EAGAIN, name, true);
250     vconn_set_remote_ip(&sslv->vconn, remote->sin_addr.s_addr);
251     vconn_set_remote_port(&sslv->vconn, remote->sin_port);
252     vconn_set_local_ip(&sslv->vconn, local.sin_addr.s_addr);
253     vconn_set_local_port(&sslv->vconn, local.sin_port);
254     sslv->state = state;
255     sslv->type = type;
256     sslv->fd = fd;
257     sslv->ssl = ssl;
258     sslv->rxbuf = NULL;
259     sslv->txbuf = NULL;
260     sslv->tx_waiter = NULL;
261     sslv->rx_want = sslv->tx_want = SSL_NOTHING;
262     *vconnp = &sslv->vconn;
263     return 0;
264
265 error:
266     if (ssl) {
267         SSL_free(ssl);
268     }
269     close(fd);
270     return retval;
271 }
272
273 static struct ssl_vconn *
274 ssl_vconn_cast(struct vconn *vconn)
275 {
276     vconn_assert_class(vconn, &ssl_vconn_class);
277     return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
278 }
279
280 static int
281 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
282 {
283     char *save_ptr = NULL;
284     char *host_name, *port_string;
285     struct sockaddr_in sin;
286     int retval;
287     int fd;
288
289     retval = ssl_init();
290     if (retval) {
291         return retval;
292     }
293
294     host_name = strtok_r(suffix, ":", &save_ptr);
295     port_string = strtok_r(NULL, ":", &save_ptr);
296     if (!host_name) {
297         ovs_error(0, "%s: bad peer name format", name);
298         return EAFNOSUPPORT;
299     }
300
301     memset(&sin, 0, sizeof sin);
302     sin.sin_family = AF_INET;
303     if (lookup_ip(host_name, &sin.sin_addr)) {
304         return ENOENT;
305     }
306     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
307                          : OFP_SSL_PORT);
308
309     /* Create socket. */
310     fd = socket(AF_INET, SOCK_STREAM, 0);
311     if (fd < 0) {
312         VLOG_ERR("%s: socket: %s", name, strerror(errno));
313         return errno;
314     }
315     retval = set_nonblocking(fd);
316     if (retval) {
317         close(fd);
318         return retval;
319     }
320
321     /* Connect socket. */
322     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
323     if (retval < 0) {
324         if (errno == EINPROGRESS) {
325             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
326                                  &sin, vconnp);
327         } else {
328             int error = errno;
329             VLOG_ERR("%s: connect: %s", name, strerror(error));
330             close(fd);
331             return error;
332         }
333     } else {
334         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
335                              &sin, vconnp);
336     }
337 }
338
339 static int
340 do_ca_cert_bootstrap(struct vconn *vconn)
341 {
342     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
343     STACK_OF(X509) *chain;
344     X509 *ca_cert;
345     FILE *file;
346     int error;
347     int fd;
348
349     chain = SSL_get_peer_cert_chain(sslv->ssl);
350     if (!chain || !sk_X509_num(chain)) {
351         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
352                  "peer");
353         return EPROTO;
354     }
355     ca_cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
356
357     /* Check that 'ca_cert' is self-signed.  Otherwise it is not a CA
358      * certificate and we should not attempt to use it as one. */
359     error = X509_check_issued(ca_cert, ca_cert);
360     if (error) {
361         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
362                  "not self-signed (%s)",
363                  X509_verify_cert_error_string(error));
364         if (sk_X509_num(chain) < 2) {
365             VLOG_ERR("only one certificate was received, so probably the peer "
366                      "is not configured to send its CA certificate");
367         }
368         return EPROTO;
369     }
370
371     fd = open(ca_cert_file, O_CREAT | O_EXCL | O_WRONLY, 0444);
372     if (fd < 0) {
373         VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
374                  ca_cert_file, strerror(errno));
375         return errno;
376     }
377
378     file = fdopen(fd, "w");
379     if (!file) {
380         int error = errno;
381         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
382                  strerror(error));
383         unlink(ca_cert_file);
384         return error;
385     }
386
387     if (!PEM_write_X509(file, ca_cert)) {
388         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
389                  "%s", ca_cert_file, ERR_error_string(ERR_get_error(), NULL));
390         fclose(file);
391         unlink(ca_cert_file);
392         return EIO;
393     }
394
395     if (fclose(file)) {
396         int error = errno;
397         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
398                  ca_cert_file, strerror(error));
399         unlink(ca_cert_file);
400         return error;
401     }
402
403     VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert_file);
404     log_ca_cert(ca_cert_file, ca_cert);
405     bootstrap_ca_cert = false;
406     has_ca_cert = true;
407
408     /* SSL_CTX_add_client_CA makes a copy of ca_cert's relevant data. */
409     SSL_CTX_add_client_CA(ctx, ca_cert);
410
411     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
412      * 'ca_cert' is owned by sslv->ssl, so we need to duplicate it. */
413     ca_cert = X509_dup(ca_cert);
414     if (!ca_cert) {
415         out_of_memory();
416     }
417     if (SSL_CTX_load_verify_locations(ctx, ca_cert_file, NULL) != 1) {
418         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
419                  ERR_error_string(ERR_get_error(), NULL));
420         return EPROTO;
421     }
422     VLOG_INFO("killing successful connection to retry using CA cert");
423     return EPROTO;
424 }
425
426 static int
427 ssl_connect(struct vconn *vconn)
428 {
429     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
430     int retval;
431
432     switch (sslv->state) {
433     case STATE_TCP_CONNECTING:
434         retval = check_connection_completion(sslv->fd);
435         if (retval) {
436             return retval;
437         }
438         sslv->state = STATE_SSL_CONNECTING;
439         /* Fall through. */
440
441     case STATE_SSL_CONNECTING:
442         retval = (sslv->type == CLIENT
443                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
444         if (retval != 1) {
445             int error = SSL_get_error(sslv->ssl, retval);
446             if (retval < 0 && ssl_wants_io(error)) {
447                 return EAGAIN;
448             } else {
449                 int unused;
450                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
451                                      : "SSL_accept"), retval, error, &unused);
452                 shutdown(sslv->fd, SHUT_RDWR);
453                 return EPROTO;
454             }
455         } else if (bootstrap_ca_cert) {
456             return do_ca_cert_bootstrap(vconn);
457         } else if ((SSL_get_verify_mode(sslv->ssl)
458                     & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
459                    != SSL_VERIFY_PEER) {
460             /* Two or more SSL connections completed at the same time while we
461              * were in bootstrap mode.  Only one of these can finish the
462              * bootstrap successfully.  The other one(s) must be rejected
463              * because they were not verified against the bootstrapped CA
464              * certificate.  (Alternatively we could verify them against the CA
465              * certificate, but that's more trouble than it's worth.  These
466              * connections will succeed the next time they retry, assuming that
467              * they have a certificate against the correct CA.) */
468             VLOG_ERR("rejecting SSL connection during bootstrap race window");
469             return EPROTO;
470         } else {
471             return 0;
472         }
473     }
474
475     NOT_REACHED();
476 }
477
478 static void
479 ssl_close(struct vconn *vconn)
480 {
481     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
482     poll_cancel(sslv->tx_waiter);
483     ssl_clear_txbuf(sslv);
484     ofpbuf_delete(sslv->rxbuf);
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             leak_checker_claim(buffer);
719             ssl_register_tx_waiter(vconn);
720             return 0;
721         default:
722             sslv->txbuf = NULL;
723             return error;
724         }
725     }
726 }
727
728 static void
729 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
730 {
731     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
732
733     switch (wait) {
734     case WAIT_CONNECT:
735         if (vconn_connect(vconn) != EAGAIN) {
736             poll_immediate_wake();
737         } else {
738             switch (sslv->state) {
739             case STATE_TCP_CONNECTING:
740                 poll_fd_wait(sslv->fd, POLLOUT);
741                 break;
742
743             case STATE_SSL_CONNECTING:
744                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
745                  * set up the status that we test here. */
746                 poll_fd_wait(sslv->fd,
747                              want_to_poll_events(SSL_want(sslv->ssl)));
748                 break;
749
750             default:
751                 NOT_REACHED();
752             }
753         }
754         break;
755
756     case WAIT_RECV:
757         if (sslv->rx_want != SSL_NOTHING) {
758             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
759         } else {
760             poll_immediate_wake();
761         }
762         break;
763
764     case WAIT_SEND:
765         if (!sslv->txbuf) {
766             /* We have room in our tx queue. */
767             poll_immediate_wake();
768         } else {
769             /* The call to ssl_tx_poll_callback() will wake us up. */
770         }
771         break;
772
773     default:
774         NOT_REACHED();
775     }
776 }
777
778 struct vconn_class ssl_vconn_class = {
779     "ssl",                      /* name */
780     ssl_open,                   /* open */
781     ssl_close,                  /* close */
782     ssl_connect,                /* connect */
783     ssl_recv,                   /* recv */
784     ssl_send,                   /* send */
785     ssl_wait,                   /* wait */
786 };
787 \f
788 /* Passive SSL. */
789
790 struct pssl_pvconn
791 {
792     struct pvconn pvconn;
793     int fd;
794 };
795
796 struct pvconn_class pssl_pvconn_class;
797
798 static struct pssl_pvconn *
799 pssl_pvconn_cast(struct pvconn *pvconn)
800 {
801     pvconn_assert_class(pvconn, &pssl_pvconn_class);
802     return CONTAINER_OF(pvconn, struct pssl_pvconn, pvconn);
803 }
804
805 static int
806 pssl_open(const char *name, char *suffix, struct pvconn **pvconnp)
807 {
808     struct sockaddr_in sin;
809     struct pssl_pvconn *pssl;
810     int retval;
811     int fd;
812     unsigned int yes = 1;
813
814     retval = ssl_init();
815     if (retval) {
816         return retval;
817     }
818
819     /* Create socket. */
820     fd = socket(AF_INET, SOCK_STREAM, 0);
821     if (fd < 0) {
822         int error = errno;
823         VLOG_ERR("%s: socket: %s", name, strerror(error));
824         return error;
825     }
826
827     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
828         int error = errno;
829         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
830         return error;
831     }
832
833     memset(&sin, 0, sizeof sin);
834     sin.sin_family = AF_INET;
835     sin.sin_addr.s_addr = htonl(INADDR_ANY);
836     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
837     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
838     if (retval < 0) {
839         int error = errno;
840         VLOG_ERR("%s: bind: %s", name, strerror(error));
841         close(fd);
842         return error;
843     }
844
845     retval = listen(fd, 10);
846     if (retval < 0) {
847         int error = errno;
848         VLOG_ERR("%s: listen: %s", name, strerror(error));
849         close(fd);
850         return error;
851     }
852
853     retval = set_nonblocking(fd);
854     if (retval) {
855         close(fd);
856         return retval;
857     }
858
859     pssl = xmalloc(sizeof *pssl);
860     pvconn_init(&pssl->pvconn, &pssl_pvconn_class, name);
861     pssl->fd = fd;
862     *pvconnp = &pssl->pvconn;
863     return 0;
864 }
865
866 static void
867 pssl_close(struct pvconn *pvconn)
868 {
869     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
870     close(pssl->fd);
871     free(pssl);
872 }
873
874 static int
875 pssl_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
876 {
877     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
878     struct sockaddr_in sin;
879     socklen_t sin_len = sizeof sin;
880     char name[128];
881     int new_fd;
882     int error;
883
884     new_fd = accept(pssl->fd, &sin, &sin_len);
885     if (new_fd < 0) {
886         int error = errno;
887         if (error != EAGAIN) {
888             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
889         }
890         return error;
891     }
892
893     error = set_nonblocking(new_fd);
894     if (error) {
895         close(new_fd);
896         return error;
897     }
898
899     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
900     if (sin.sin_port != htons(OFP_SSL_PORT)) {
901         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
902     }
903     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
904                          new_vconnp);
905 }
906
907 static void
908 pssl_wait(struct pvconn *pvconn)
909 {
910     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
911     poll_fd_wait(pssl->fd, POLLIN);
912 }
913
914 struct pvconn_class pssl_pvconn_class = {
915     "pssl",
916     pssl_open,
917     pssl_close,
918     pssl_accept,
919     pssl_wait,
920 };
921 \f
922 /*
923  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
924  * OpenSSL is requesting that we call it back when the socket is ready for read
925  * or writing, respectively.
926  */
927 static bool
928 ssl_wants_io(int ssl_error)
929 {
930     return (ssl_error == SSL_ERROR_WANT_WRITE
931             || ssl_error == SSL_ERROR_WANT_READ);
932 }
933
934 static int
935 ssl_init(void)
936 {
937     static int init_status = -1;
938     if (init_status < 0) {
939         init_status = do_ssl_init();
940         assert(init_status >= 0);
941     }
942     return init_status;
943 }
944
945 static int
946 do_ssl_init(void)
947 {
948     SSL_METHOD *method;
949
950     SSL_library_init();
951     SSL_load_error_strings();
952
953     method = TLSv1_method();
954     if (method == NULL) {
955         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
956         return ENOPROTOOPT;
957     }
958
959     ctx = SSL_CTX_new(method);
960     if (ctx == NULL) {
961         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
962         return ENOPROTOOPT;
963     }
964     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
965     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
966     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
967     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
968     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
969                        NULL);
970
971     return 0;
972 }
973
974 static DH *
975 tmp_dh_callback(SSL *ssl UNUSED, int is_export UNUSED, int keylength)
976 {
977     struct dh {
978         int keylength;
979         DH *dh;
980         DH *(*constructor)(void);
981     };
982
983     static struct dh dh_table[] = {
984         {1024, NULL, get_dh1024},
985         {2048, NULL, get_dh2048},
986         {4096, NULL, get_dh4096},
987     };
988
989     struct dh *dh;
990
991     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
992         if (dh->keylength == keylength) {
993             if (!dh->dh) {
994                 dh->dh = dh->constructor();
995                 if (!dh->dh) {
996                     ovs_fatal(ENOMEM, "out of memory constructing "
997                               "Diffie-Hellman parameters");
998                 }
999             }
1000             return dh->dh;
1001         }
1002     }
1003     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
1004                 keylength);
1005     return NULL;
1006 }
1007
1008 /* Returns true if SSL is at least partially configured. */
1009 bool
1010 vconn_ssl_is_configured(void) 
1011 {
1012     return has_private_key || has_certificate || has_ca_cert;
1013 }
1014
1015 void
1016 vconn_ssl_set_private_key_file(const char *file_name)
1017 {
1018     if (ssl_init()) {
1019         return;
1020     }
1021     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
1022         VLOG_ERR("SSL_use_PrivateKey_file: %s",
1023                  ERR_error_string(ERR_get_error(), NULL));
1024         return;
1025     }
1026     has_private_key = true;
1027 }
1028
1029 void
1030 vconn_ssl_set_certificate_file(const char *file_name)
1031 {
1032     if (ssl_init()) {
1033         return;
1034     }
1035     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
1036         VLOG_ERR("SSL_use_certificate_file: %s",
1037                  ERR_error_string(ERR_get_error(), NULL));
1038         return;
1039     }
1040     has_certificate = true;
1041 }
1042
1043 /* Reads the X509 certificate or certificates in file 'file_name'.  On success,
1044  * stores the address of the first element in an array of pointers to
1045  * certificates in '*certs' and the number of certificates in the array in
1046  * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
1047  * in '*n_certs', and returns a positive errno value.
1048  *
1049  * The caller is responsible for freeing '*certs'. */
1050 static int
1051 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
1052 {
1053     FILE *file;
1054     size_t allocated_certs = 0;
1055
1056     *certs = NULL;
1057     *n_certs = 0;
1058
1059     file = fopen(file_name, "r");
1060     if (!file) {
1061         VLOG_ERR("failed to open %s for reading: %s",
1062                  file_name, strerror(errno));
1063         return errno;
1064     }
1065
1066     for (;;) {
1067         X509 *certificate;
1068         int c;
1069
1070         /* Read certificate from file. */
1071         certificate = PEM_read_X509(file, NULL, NULL, NULL);
1072         if (!certificate) {
1073             size_t i;
1074
1075             VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1076                      file_name, ERR_error_string(ERR_get_error(), NULL));
1077             for (i = 0; i < *n_certs; i++) {
1078                 X509_free((*certs)[i]);
1079             }
1080             free(*certs);
1081             *certs = NULL;
1082             *n_certs = 0;
1083             return EIO;
1084         }
1085
1086         /* Add certificate to array. */
1087         if (*n_certs >= allocated_certs) {
1088             *certs = x2nrealloc(*certs, &allocated_certs, sizeof **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_INFO("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 }