d4dbc9f7979f627b8de17126a91cbf47a701122b
[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 *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, 
242                sin->sin_addr.s_addr, sin->sin_port, 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     char *save_ptr, *host_name, *port_string;
273     struct sockaddr_in sin;
274     int retval;
275     int fd;
276
277     retval = ssl_init();
278     if (retval) {
279         return retval;
280     }
281
282     host_name = strtok_r(suffix, ":", &save_ptr);
283     port_string = strtok_r(NULL, ":", &save_ptr);
284     if (!host_name) {
285         ovs_error(0, "%s: bad peer name format", name);
286         return EAFNOSUPPORT;
287     }
288
289     memset(&sin, 0, sizeof sin);
290     sin.sin_family = AF_INET;
291     if (lookup_ip(host_name, &sin.sin_addr)) {
292         return ENOENT;
293     }
294     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
295                          : OFP_SSL_PORT);
296
297     /* Create socket. */
298     fd = socket(AF_INET, SOCK_STREAM, 0);
299     if (fd < 0) {
300         VLOG_ERR("%s: socket: %s", name, strerror(errno));
301         return errno;
302     }
303     retval = set_nonblocking(fd);
304     if (retval) {
305         close(fd);
306         return retval;
307     }
308
309     /* Connect socket. */
310     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
311     if (retval < 0) {
312         if (errno == EINPROGRESS) {
313             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
314                                  &sin, vconnp);
315         } else {
316             int error = errno;
317             VLOG_ERR("%s: connect: %s", name, strerror(error));
318             close(fd);
319             return error;
320         }
321     } else {
322         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
323                              &sin, vconnp);
324     }
325 }
326
327 static int
328 do_ca_cert_bootstrap(struct vconn *vconn)
329 {
330     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
331     STACK_OF(X509) *chain;
332     X509 *ca_cert;
333     FILE *file;
334     int error;
335     int fd;
336
337     chain = SSL_get_peer_cert_chain(sslv->ssl);
338     if (!chain || !sk_X509_num(chain)) {
339         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
340                  "peer");
341         return EPROTO;
342     }
343     ca_cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
344
345     /* Check that 'ca_cert' is self-signed.  Otherwise it is not a CA
346      * certificate and we should not attempt to use it as one. */
347     error = X509_check_issued(ca_cert, ca_cert);
348     if (error) {
349         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
350                  "not self-signed (%s)",
351                  X509_verify_cert_error_string(error));
352         if (sk_X509_num(chain) < 2) {
353             VLOG_ERR("only one certificate was received, so probably the peer "
354                      "is not configured to send its CA certificate");
355         }
356         return EPROTO;
357     }
358
359     fd = open(ca_cert_file, O_CREAT | O_EXCL | O_WRONLY, 0444);
360     if (fd < 0) {
361         VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
362                  ca_cert_file, strerror(errno));
363         return errno;
364     }
365
366     file = fdopen(fd, "w");
367     if (!file) {
368         int error = errno;
369         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
370                  strerror(error));
371         unlink(ca_cert_file);
372         return error;
373     }
374
375     if (!PEM_write_X509(file, ca_cert)) {
376         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
377                  "%s", ca_cert_file, ERR_error_string(ERR_get_error(), NULL));
378         fclose(file);
379         unlink(ca_cert_file);
380         return EIO;
381     }
382
383     if (fclose(file)) {
384         int error = errno;
385         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
386                  ca_cert_file, strerror(error));
387         unlink(ca_cert_file);
388         return error;
389     }
390
391     VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert_file);
392     log_ca_cert(ca_cert_file, ca_cert);
393     bootstrap_ca_cert = false;
394     has_ca_cert = true;
395
396     /* SSL_CTX_add_client_CA makes a copy of ca_cert's relevant data. */
397     SSL_CTX_add_client_CA(ctx, ca_cert);
398
399     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
400      * 'ca_cert' is owned by sslv->ssl, so we need to duplicate it. */
401     ca_cert = X509_dup(ca_cert);
402     if (!ca_cert) {
403         out_of_memory();
404     }
405     if (SSL_CTX_load_verify_locations(ctx, ca_cert_file, NULL) != 1) {
406         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
407                  ERR_error_string(ERR_get_error(), NULL));
408         return EPROTO;
409     }
410     VLOG_INFO("killing successful connection to retry using CA cert");
411     return EPROTO;
412 }
413
414 static int
415 ssl_connect(struct vconn *vconn)
416 {
417     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
418     int retval;
419
420     switch (sslv->state) {
421     case STATE_TCP_CONNECTING:
422         retval = check_connection_completion(sslv->fd);
423         if (retval) {
424             return retval;
425         }
426         sslv->state = STATE_SSL_CONNECTING;
427         /* Fall through. */
428
429     case STATE_SSL_CONNECTING: {
430         struct sockaddr_in local_addr;
431         socklen_t addrlen = sizeof(local_addr);
432
433         /* Get the local IP and port information */
434         retval = getsockname(sslv->fd, (struct sockaddr *)&local_addr, 
435                              &addrlen);
436         if (retval) {
437             memset(&local_addr, 0, sizeof local_addr);
438         }
439         vconn_set_local_ip(vconn, local_addr.sin_addr.s_addr);
440         vconn_set_local_port(vconn, local_addr.sin_port);
441
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     }
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_clear_txbuf(sslv);
486     ofpbuf_delete(sslv->rxbuf);
487     SSL_free(sslv->ssl);
488     close(sslv->fd);
489     free(sslv);
490 }
491
492 static int
493 interpret_ssl_error(const char *function, int ret, int error,
494                     int *want)
495 {
496     *want = SSL_NOTHING;
497
498     switch (error) {
499     case SSL_ERROR_NONE:
500         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
501         break;
502
503     case SSL_ERROR_ZERO_RETURN:
504         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
505         break;
506
507     case SSL_ERROR_WANT_READ:
508         *want = SSL_READING;
509         return EAGAIN;
510
511     case SSL_ERROR_WANT_WRITE:
512         *want = SSL_WRITING;
513         return EAGAIN;
514
515     case SSL_ERROR_WANT_CONNECT:
516         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
517         break;
518
519     case SSL_ERROR_WANT_ACCEPT:
520         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
521         break;
522
523     case SSL_ERROR_WANT_X509_LOOKUP:
524         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
525                     function);
526         break;
527
528     case SSL_ERROR_SYSCALL: {
529         int queued_error = ERR_get_error();
530         if (queued_error == 0) {
531             if (ret < 0) {
532                 int status = errno;
533                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
534                              function, strerror(status));
535                 return status;
536             } else {
537                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
538                              function);
539                 return EPROTO;
540             }
541         } else {
542             VLOG_WARN_RL(&rl, "%s: %s",
543                          function, ERR_error_string(queued_error, NULL));
544             break;
545         }
546     }
547
548     case SSL_ERROR_SSL: {
549         int queued_error = ERR_get_error();
550         if (queued_error != 0) {
551             VLOG_WARN_RL(&rl, "%s: %s",
552                          function, ERR_error_string(queued_error, NULL));
553         } else {
554             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
555                         function);
556         }
557         break;
558     }
559
560     default:
561         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
562         break;
563     }
564     return EIO;
565 }
566
567 static int
568 ssl_recv(struct vconn *vconn, struct ofpbuf **bufferp)
569 {
570     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
571     struct ofpbuf *rx;
572     size_t want_bytes;
573     int old_state;
574     ssize_t ret;
575
576     if (sslv->rxbuf == NULL) {
577         sslv->rxbuf = ofpbuf_new(1564);
578     }
579     rx = sslv->rxbuf;
580
581 again:
582     if (sizeof(struct ofp_header) > rx->size) {
583         want_bytes = sizeof(struct ofp_header) - rx->size;
584     } else {
585         struct ofp_header *oh = rx->data;
586         size_t length = ntohs(oh->length);
587         if (length < sizeof(struct ofp_header)) {
588             VLOG_ERR_RL(&rl, "received too-short ofp_header (%zu bytes)",
589                         length);
590             return EPROTO;
591         }
592         want_bytes = length - rx->size;
593         if (!want_bytes) {
594             *bufferp = rx;
595             sslv->rxbuf = NULL;
596             return 0;
597         }
598     }
599     ofpbuf_prealloc_tailroom(rx, want_bytes);
600
601     /* Behavior of zero-byte SSL_read is poorly defined. */
602     assert(want_bytes > 0);
603
604     old_state = SSL_get_state(sslv->ssl);
605     ret = SSL_read(sslv->ssl, ofpbuf_tail(rx), want_bytes);
606     if (old_state != SSL_get_state(sslv->ssl)) {
607         sslv->tx_want = SSL_NOTHING;
608         if (sslv->tx_waiter) {
609             poll_cancel(sslv->tx_waiter);
610             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
611         }
612     }
613     sslv->rx_want = SSL_NOTHING;
614
615     if (ret > 0) {
616         rx->size += ret;
617         if (ret == want_bytes) {
618             if (rx->size > sizeof(struct ofp_header)) {
619                 *bufferp = rx;
620                 sslv->rxbuf = NULL;
621                 return 0;
622             } else {
623                 goto again;
624             }
625         }
626         return EAGAIN;
627     } else {
628         int error = SSL_get_error(sslv->ssl, ret);
629         if (error == SSL_ERROR_ZERO_RETURN) {
630             /* Connection closed (EOF). */
631             if (rx->size) {
632                 VLOG_WARN_RL(&rl, "SSL_read: unexpected connection close");
633                 return EPROTO;
634             } else {
635                 return EOF;
636             }
637         } else {
638             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
639         }
640     }
641 }
642
643 static void
644 ssl_clear_txbuf(struct ssl_vconn *sslv)
645 {
646     ofpbuf_delete(sslv->txbuf);
647     sslv->txbuf = NULL;
648     sslv->tx_waiter = NULL;
649 }
650
651 static void
652 ssl_register_tx_waiter(struct vconn *vconn)
653 {
654     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
655     sslv->tx_waiter = poll_fd_callback(sslv->fd,
656                                        want_to_poll_events(sslv->tx_want),
657                                        ssl_tx_poll_callback, vconn);
658 }
659
660 static int
661 ssl_do_tx(struct vconn *vconn)
662 {
663     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
664
665     for (;;) {
666         int old_state = SSL_get_state(sslv->ssl);
667         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
668         if (old_state != SSL_get_state(sslv->ssl)) {
669             sslv->rx_want = SSL_NOTHING;
670         }
671         sslv->tx_want = SSL_NOTHING;
672         if (ret > 0) {
673             ofpbuf_pull(sslv->txbuf, ret);
674             if (sslv->txbuf->size == 0) {
675                 return 0;
676             }
677         } else {
678             int ssl_error = SSL_get_error(sslv->ssl, ret);
679             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
680                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
681                 return EPIPE;
682             } else {
683                 return interpret_ssl_error("SSL_write", ret, ssl_error,
684                                            &sslv->tx_want);
685             }
686         }
687     }
688 }
689
690 static void
691 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
692 {
693     struct vconn *vconn = vconn_;
694     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
695     int error = ssl_do_tx(vconn);
696     if (error != EAGAIN) {
697         ssl_clear_txbuf(sslv);
698     } else {
699         ssl_register_tx_waiter(vconn);
700     }
701 }
702
703 static int
704 ssl_send(struct vconn *vconn, struct ofpbuf *buffer)
705 {
706     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
707
708     if (sslv->txbuf) {
709         return EAGAIN;
710     } else {
711         int error;
712
713         sslv->txbuf = buffer;
714         error = ssl_do_tx(vconn);
715         switch (error) {
716         case 0:
717             ssl_clear_txbuf(sslv);
718             return 0;
719         case EAGAIN:
720             leak_checker_claim(buffer);
721             ssl_register_tx_waiter(vconn);
722             return 0;
723         default:
724             sslv->txbuf = NULL;
725             return error;
726         }
727     }
728 }
729
730 static void
731 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
732 {
733     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
734
735     switch (wait) {
736     case WAIT_CONNECT:
737         if (vconn_connect(vconn) != EAGAIN) {
738             poll_immediate_wake();
739         } else {
740             switch (sslv->state) {
741             case STATE_TCP_CONNECTING:
742                 poll_fd_wait(sslv->fd, POLLOUT);
743                 break;
744
745             case STATE_SSL_CONNECTING:
746                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
747                  * set up the status that we test here. */
748                 poll_fd_wait(sslv->fd,
749                              want_to_poll_events(SSL_want(sslv->ssl)));
750                 break;
751
752             default:
753                 NOT_REACHED();
754             }
755         }
756         break;
757
758     case WAIT_RECV:
759         if (sslv->rx_want != SSL_NOTHING) {
760             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
761         } else {
762             poll_immediate_wake();
763         }
764         break;
765
766     case WAIT_SEND:
767         if (!sslv->txbuf) {
768             /* We have room in our tx queue. */
769             poll_immediate_wake();
770         } else {
771             /* The call to ssl_tx_poll_callback() will wake us up. */
772         }
773         break;
774
775     default:
776         NOT_REACHED();
777     }
778 }
779
780 struct vconn_class ssl_vconn_class = {
781     "ssl",                      /* name */
782     ssl_open,                   /* open */
783     ssl_close,                  /* close */
784     ssl_connect,                /* connect */
785     ssl_recv,                   /* recv */
786     ssl_send,                   /* send */
787     ssl_wait,                   /* wait */
788 };
789 \f
790 /* Passive SSL. */
791
792 struct pssl_pvconn
793 {
794     struct pvconn pvconn;
795     int fd;
796 };
797
798 struct pvconn_class pssl_pvconn_class;
799
800 static struct pssl_pvconn *
801 pssl_pvconn_cast(struct pvconn *pvconn)
802 {
803     pvconn_assert_class(pvconn, &pssl_pvconn_class);
804     return CONTAINER_OF(pvconn, struct pssl_pvconn, pvconn);
805 }
806
807 static int
808 pssl_open(const char *name, char *suffix, struct pvconn **pvconnp)
809 {
810     struct sockaddr_in sin;
811     struct pssl_pvconn *pssl;
812     int retval;
813     int fd;
814     unsigned int yes = 1;
815
816     retval = ssl_init();
817     if (retval) {
818         return retval;
819     }
820
821     /* Create socket. */
822     fd = socket(AF_INET, SOCK_STREAM, 0);
823     if (fd < 0) {
824         int error = errno;
825         VLOG_ERR("%s: socket: %s", name, strerror(error));
826         return error;
827     }
828
829     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
830         int error = errno;
831         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
832         return error;
833     }
834
835     memset(&sin, 0, sizeof sin);
836     sin.sin_family = AF_INET;
837     sin.sin_addr.s_addr = htonl(INADDR_ANY);
838     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
839     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
840     if (retval < 0) {
841         int error = errno;
842         VLOG_ERR("%s: bind: %s", name, strerror(error));
843         close(fd);
844         return error;
845     }
846
847     retval = listen(fd, 10);
848     if (retval < 0) {
849         int error = errno;
850         VLOG_ERR("%s: listen: %s", name, strerror(error));
851         close(fd);
852         return error;
853     }
854
855     retval = set_nonblocking(fd);
856     if (retval) {
857         close(fd);
858         return retval;
859     }
860
861     pssl = xmalloc(sizeof *pssl);
862     pvconn_init(&pssl->pvconn, &pssl_pvconn_class, name);
863     pssl->fd = fd;
864     *pvconnp = &pssl->pvconn;
865     return 0;
866 }
867
868 static void
869 pssl_close(struct pvconn *pvconn)
870 {
871     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
872     close(pssl->fd);
873     free(pssl);
874 }
875
876 static int
877 pssl_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
878 {
879     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
880     struct sockaddr_in sin;
881     socklen_t sin_len = sizeof sin;
882     char name[128];
883     int new_fd;
884     int error;
885
886     new_fd = accept(pssl->fd, &sin, &sin_len);
887     if (new_fd < 0) {
888         int error = errno;
889         if (error != EAGAIN) {
890             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
891         }
892         return error;
893     }
894
895     error = set_nonblocking(new_fd);
896     if (error) {
897         close(new_fd);
898         return error;
899     }
900
901     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
902     if (sin.sin_port != htons(OFP_SSL_PORT)) {
903         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
904     }
905     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
906                          new_vconnp);
907 }
908
909 static void
910 pssl_wait(struct pvconn *pvconn)
911 {
912     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
913     poll_fd_wait(pssl->fd, POLLIN);
914 }
915
916 struct pvconn_class pssl_pvconn_class = {
917     "pssl",
918     pssl_open,
919     pssl_close,
920     pssl_accept,
921     pssl_wait,
922 };
923 \f
924 /*
925  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
926  * OpenSSL is requesting that we call it back when the socket is ready for read
927  * or writing, respectively.
928  */
929 static bool
930 ssl_wants_io(int ssl_error)
931 {
932     return (ssl_error == SSL_ERROR_WANT_WRITE
933             || ssl_error == SSL_ERROR_WANT_READ);
934 }
935
936 static int
937 ssl_init(void)
938 {
939     static int init_status = -1;
940     if (init_status < 0) {
941         init_status = do_ssl_init();
942         assert(init_status >= 0);
943     }
944     return init_status;
945 }
946
947 static int
948 do_ssl_init(void)
949 {
950     SSL_METHOD *method;
951
952     SSL_library_init();
953     SSL_load_error_strings();
954
955     method = TLSv1_method();
956     if (method == NULL) {
957         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
958         return ENOPROTOOPT;
959     }
960
961     ctx = SSL_CTX_new(method);
962     if (ctx == NULL) {
963         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
964         return ENOPROTOOPT;
965     }
966     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
967     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
968     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
969     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
970     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
971                        NULL);
972
973     return 0;
974 }
975
976 static DH *
977 tmp_dh_callback(SSL *ssl UNUSED, int is_export UNUSED, int keylength)
978 {
979     struct dh {
980         int keylength;
981         DH *dh;
982         DH *(*constructor)(void);
983     };
984
985     static struct dh dh_table[] = {
986         {1024, NULL, get_dh1024},
987         {2048, NULL, get_dh2048},
988         {4096, NULL, get_dh4096},
989     };
990
991     struct dh *dh;
992
993     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
994         if (dh->keylength == keylength) {
995             if (!dh->dh) {
996                 dh->dh = dh->constructor();
997                 if (!dh->dh) {
998                     ovs_fatal(ENOMEM, "out of memory constructing "
999                               "Diffie-Hellman parameters");
1000                 }
1001             }
1002             return dh->dh;
1003         }
1004     }
1005     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
1006                 keylength);
1007     return NULL;
1008 }
1009
1010 /* Returns true if SSL is at least partially configured. */
1011 bool
1012 vconn_ssl_is_configured(void) 
1013 {
1014     return has_private_key || has_certificate || has_ca_cert;
1015 }
1016
1017 void
1018 vconn_ssl_set_private_key_file(const char *file_name)
1019 {
1020     if (ssl_init()) {
1021         return;
1022     }
1023     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
1024         VLOG_ERR("SSL_use_PrivateKey_file: %s",
1025                  ERR_error_string(ERR_get_error(), NULL));
1026         return;
1027     }
1028     has_private_key = true;
1029 }
1030
1031 void
1032 vconn_ssl_set_certificate_file(const char *file_name)
1033 {
1034     if (ssl_init()) {
1035         return;
1036     }
1037     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
1038         VLOG_ERR("SSL_use_certificate_file: %s",
1039                  ERR_error_string(ERR_get_error(), NULL));
1040         return;
1041     }
1042     has_certificate = true;
1043 }
1044
1045 /* Reads the X509 certificate or certificates in file 'file_name'.  On success,
1046  * stores the address of the first element in an array of pointers to
1047  * certificates in '*certs' and the number of certificates in the array in
1048  * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
1049  * in '*n_certs', and returns a positive errno value.
1050  *
1051  * The caller is responsible for freeing '*certs'. */
1052 static int
1053 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
1054 {
1055     FILE *file;
1056     size_t allocated_certs = 0;
1057
1058     *certs = NULL;
1059     *n_certs = 0;
1060
1061     file = fopen(file_name, "r");
1062     if (!file) {
1063         VLOG_ERR("failed to open %s for reading: %s",
1064                  file_name, strerror(errno));
1065         return errno;
1066     }
1067
1068     for (;;) {
1069         X509 *certificate;
1070         int c;
1071
1072         /* Read certificate from file. */
1073         certificate = PEM_read_X509(file, NULL, NULL, NULL);
1074         if (!certificate) {
1075             size_t i;
1076
1077             VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1078                      file_name, ERR_error_string(ERR_get_error(), NULL));
1079             for (i = 0; i < *n_certs; i++) {
1080                 X509_free((*certs)[i]);
1081             }
1082             free(*certs);
1083             *certs = NULL;
1084             *n_certs = 0;
1085             return EIO;
1086         }
1087
1088         /* Add certificate to array. */
1089         if (*n_certs >= allocated_certs) {
1090             *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1091         }
1092         (*certs)[(*n_certs)++] = certificate;
1093
1094         /* Are there additional certificates in the file? */
1095         do {
1096             c = getc(file);
1097         } while (isspace(c));
1098         if (c == EOF) {
1099             break;
1100         }
1101         ungetc(c, file);
1102     }
1103     fclose(file);
1104     return 0;
1105 }
1106
1107
1108 /* Sets 'file_name' as the name of a file containing one or more X509
1109  * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1110  * certificate to the peer, which enables a switch to pick up the controller's
1111  * CA certificate on its first connection. */
1112 void
1113 vconn_ssl_set_peer_ca_cert_file(const char *file_name)
1114 {
1115     X509 **certs;
1116     size_t n_certs;
1117     size_t i;
1118
1119     if (ssl_init()) {
1120         return;
1121     }
1122
1123     if (!read_cert_file(file_name, &certs, &n_certs)) {
1124         for (i = 0; i < n_certs; i++) {
1125             if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1126                 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1127                          ERR_error_string(ERR_get_error(), NULL));
1128             }
1129         }
1130         free(certs);
1131     }
1132 }
1133
1134 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1135 static void
1136 log_ca_cert(const char *file_name, X509 *cert)
1137 {
1138     unsigned char digest[EVP_MAX_MD_SIZE];
1139     unsigned int n_bytes;
1140     struct ds fp;
1141     char *subject;
1142
1143     ds_init(&fp);
1144     if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1145         ds_put_cstr(&fp, "<out of memory>");
1146     } else {
1147         unsigned int i;
1148         for (i = 0; i < n_bytes; i++) {
1149             if (i) {
1150                 ds_put_char(&fp, ':');
1151             }
1152             ds_put_format(&fp, "%02hhx", digest[i]);
1153         }
1154     }
1155     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1156     VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1157               subject ? subject : "<out of memory>", ds_cstr(&fp));
1158     free(subject);
1159     ds_destroy(&fp);
1160 }
1161
1162 /* Sets 'file_name' as the name of the file from which to read the CA
1163  * certificate used to verify the peer within SSL connections.  If 'bootstrap'
1164  * is false, the file must exist.  If 'bootstrap' is false, then the file is
1165  * read if it is exists; if it does not, then it will be created from the CA
1166  * certificate received from the peer on the first SSL connection. */
1167 void
1168 vconn_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1169 {
1170     X509 **certs;
1171     size_t n_certs;
1172     struct stat s;
1173
1174     if (ssl_init()) {
1175         return;
1176     }
1177
1178     if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1179         bootstrap_ca_cert = true;
1180         ca_cert_file = xstrdup(file_name);
1181     } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1182         size_t i;
1183
1184         /* Set up list of CAs that the server will accept from the client. */
1185         for (i = 0; i < n_certs; i++) {
1186             /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1187             if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1188                 VLOG_ERR("failed to add client certificate %d from %s: %s",
1189                          i, file_name,
1190                          ERR_error_string(ERR_get_error(), NULL));
1191             } else {
1192                 log_ca_cert(file_name, certs[i]);
1193             }
1194             X509_free(certs[i]);
1195         }
1196
1197         /* Set up CAs for OpenSSL to trust in verifying the peer's
1198          * certificate. */
1199         if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1200             VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1201                      ERR_error_string(ERR_get_error(), NULL));
1202             return;
1203         }
1204
1205         has_ca_cert = true;
1206     }
1207 }