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