For SNAT, don't store the pre-fragment L2 header before actions are applied.
[sliver-openvswitch.git] / lib / vconn-ssl.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "vconn-ssl.h"
36 #include "dhparams.h"
37 #include <assert.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <inttypes.h>
41 #include <string.h>
42 #include <netinet/tcp.h>
43 #include <openssl/err.h>
44 #include <openssl/ssl.h>
45 #include <openssl/x509v3.h>
46 #include <poll.h>
47 #include <sys/fcntl.h>
48 #include <sys/stat.h>
49 #include <unistd.h>
50 #include "dynamic-string.h"
51 #include "ofpbuf.h"
52 #include "openflow/openflow.h"
53 #include "packets.h"
54 #include "poll-loop.h"
55 #include "socket-util.h"
56 #include "socket-util.h"
57 #include "util.h"
58 #include "vconn-provider.h"
59 #include "vconn.h"
60
61 #include "vlog.h"
62 #define THIS_MODULE VLM_vconn_ssl
63
64 /* Active SSL. */
65
66 enum ssl_state {
67     STATE_TCP_CONNECTING,
68     STATE_SSL_CONNECTING
69 };
70
71 enum session_type {
72     CLIENT,
73     SERVER
74 };
75
76 struct ssl_vconn
77 {
78     struct vconn vconn;
79     enum ssl_state state;
80     int connect_error;
81     enum session_type type;
82     int fd;
83     SSL *ssl;
84     struct ofpbuf *rxbuf;
85     struct ofpbuf *txbuf;
86     struct poll_waiter *tx_waiter;
87
88     /* rx_want and tx_want record the result of the last call to SSL_read()
89      * and SSL_write(), respectively:
90      *
91      *    - If the call reported that data needed to be read from the file
92      *      descriptor, the corresponding member is set to SSL_READING.
93      *
94      *    - If the call reported that data needed to be written to the file
95      *      descriptor, the corresponding member is set to SSL_WRITING.
96      *
97      *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
98      *      call completed successfully (or with an error) and that there is no
99      *      need to block.
100      *
101      * These are needed because there is no way to ask OpenSSL what a data read
102      * or write would require without giving it a buffer to receive into or
103      * data to send, respectively.  (Note that the SSL_want() status is
104      * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
105      * its value.)
106      *
107      * A single call to SSL_read() or SSL_write() can perform both reading
108      * and writing and thus invalidate not one of these values but actually
109      * both.  Consider this situation, for example:
110      *
111      *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
112      *
113      *    - SSL_read() laters succeeds reading from 'fd' and clears out the
114      *      whole receive buffer, so rx_want gets SSL_READING.
115      *
116      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
117      *      blocks.
118      *
119      *    - Now we're stuck blocking until the peer sends us data, even though
120      *      SSL_write() could now succeed, which could easily be a deadlock
121      *      condition.
122      *
123      * On the other hand, we can't reset both tx_want and rx_want on every call
124      * to SSL_read() or SSL_write(), because that would produce livelock,
125      * e.g. in this situation:
126      *
127      *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
128      *
129      *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
130      *      but tx_want gets reset to SSL_NOTHING.
131      *
132      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
133      *      blocks.
134      *
135      *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
136      *      that no blocking is necessary.
137      *
138      * The solution we adopt here is to set tx_want to SSL_NOTHING after
139      * calling SSL_read() only if the SSL state of the connection changed,
140      * which indicates that an SSL-level renegotiation made some progress, and
141      * similarly for rx_want and SSL_write().  This prevents both the
142      * deadlock and livelock situations above.
143      */
144     int rx_want, tx_want;
145 };
146
147 /* SSL context created by ssl_init(). */
148 static SSL_CTX *ctx;
149
150 /* Required configuration. */
151 static bool has_private_key, has_certificate, has_ca_cert;
152
153 /* Ordinarily, we require a CA certificate for the peer to be locally
154  * available.  'has_ca_cert' is true when this is the case, and neither of the
155  * following variables matter.
156  *
157  * We can, however, bootstrap the CA certificate from the peer at the beginning
158  * of our first connection then use that certificate on all subsequent
159  * connections, saving it to a file for use in future runs also.  In this case,
160  * 'has_ca_cert' is false, 'bootstrap_ca_cert' is true, and 'ca_cert_file'
161  * names the file to be saved. */
162 static bool bootstrap_ca_cert;
163 static char *ca_cert_file;
164
165 /* Who knows what can trigger various SSL errors, so let's throttle them down
166  * quite a bit. */
167 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
168
169 static int ssl_init(void);
170 static int do_ssl_init(void);
171 static bool ssl_wants_io(int ssl_error);
172 static void ssl_close(struct vconn *);
173 static void ssl_clear_txbuf(struct ssl_vconn *);
174 static int interpret_ssl_error(const char *function, int ret, int error,
175                                int *want);
176 static void ssl_tx_poll_callback(int fd, short int revents, void *vconn_);
177 static DH *tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength);
178 static void log_ca_cert(const char *file_name, X509 *cert);
179
180 short int
181 want_to_poll_events(int want)
182 {
183     switch (want) {
184     case SSL_NOTHING:
185         NOT_REACHED();
186
187     case SSL_READING:
188         return POLLIN;
189
190     case SSL_WRITING:
191         return POLLOUT;
192
193     default:
194         NOT_REACHED();
195     }
196 }
197
198 static int
199 new_ssl_vconn(const char *name, int fd, enum session_type type,
200               enum ssl_state state, const struct sockaddr_in *sin,
201               struct vconn **vconnp)
202 {
203     struct ssl_vconn *sslv;
204     SSL *ssl = NULL;
205     int on = 1;
206     int retval;
207
208     /* Check for all the needful configuration. */
209     if (!has_private_key) {
210         VLOG_ERR("Private key must be configured to use SSL");
211         goto error;
212     }
213     if (!has_certificate) {
214         VLOG_ERR("Certificate must be configured to use SSL");
215         goto error;
216     }
217     if (!has_ca_cert && !bootstrap_ca_cert) {
218         VLOG_ERR("CA certificate must be configured to use SSL");
219         goto error;
220     }
221     if (!SSL_CTX_check_private_key(ctx)) {
222         VLOG_ERR("Private key does not match certificate public key: %s",
223                  ERR_error_string(ERR_get_error(), NULL));
224         goto error;
225     }
226
227     /* Disable Nagle. */
228     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
229     if (retval) {
230         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
231         close(fd);
232         return errno;
233     }
234
235     /* Create and configure OpenSSL stream. */
236     ssl = SSL_new(ctx);
237     if (ssl == NULL) {
238         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
239         close(fd);
240         return ENOPROTOOPT;
241     }
242     if (SSL_set_fd(ssl, fd) == 0) {
243         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
244         goto error;
245     }
246     if (bootstrap_ca_cert && type == CLIENT) {
247         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
248     }
249
250     /* Create and return the ssl_vconn. */
251     sslv = xmalloc(sizeof *sslv);
252     vconn_init(&sslv->vconn, &ssl_vconn_class, EAGAIN, sin->sin_addr.s_addr,
253                name);
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 ENOPROTOOPT;
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, *host_name, *port_string;
284     struct sockaddr_in sin;
285     int retval;
286     int fd;
287
288     retval = ssl_init();
289     if (retval) {
290         return retval;
291     }
292
293     /* Glibc 2.7 has a bug in strtok_r when compiling with optimization that
294      * can cause segfaults here:
295      * http://sources.redhat.com/bugzilla/show_bug.cgi?id=5614.
296      * Using "::" instead of the obvious ":" works around it. */
297     host_name = strtok_r(suffix, "::", &save_ptr);
298     port_string = strtok_r(NULL, "::", &save_ptr);
299     if (!host_name) {
300         ofp_error(0, "%s: bad peer name format", name);
301         return EAFNOSUPPORT;
302     }
303
304     memset(&sin, 0, sizeof sin);
305     sin.sin_family = AF_INET;
306     if (lookup_ip(host_name, &sin.sin_addr)) {
307         return ENOENT;
308     }
309     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
310                          : OFP_SSL_PORT);
311
312     /* Create socket. */
313     fd = socket(AF_INET, SOCK_STREAM, 0);
314     if (fd < 0) {
315         VLOG_ERR("%s: socket: %s", name, strerror(errno));
316         return errno;
317     }
318     retval = set_nonblocking(fd);
319     if (retval) {
320         close(fd);
321         return retval;
322     }
323
324     /* Connect socket. */
325     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
326     if (retval < 0) {
327         if (errno == EINPROGRESS) {
328             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
329                                  &sin, vconnp);
330         } else {
331             int error = errno;
332             VLOG_ERR("%s: connect: %s", name, strerror(error));
333             close(fd);
334             return error;
335         }
336     } else {
337         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
338                              &sin, vconnp);
339     }
340 }
341
342 static int
343 do_ca_cert_bootstrap(struct vconn *vconn)
344 {
345     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
346     STACK_OF(X509) *chain;
347     X509 *ca_cert;
348     FILE *file;
349     int error;
350     int fd;
351
352     chain = SSL_get_peer_cert_chain(sslv->ssl);
353     if (!chain || !sk_X509_num(chain)) {
354         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
355                  "peer");
356         return EPROTO;
357     }
358     ca_cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
359
360     /* Check that 'ca_cert' is self-signed.  Otherwise it is not a CA
361      * certificate and we should not attempt to use it as one. */
362     error = X509_check_issued(ca_cert, ca_cert);
363     if (error) {
364         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
365                  "not self-signed (%s)",
366                  X509_verify_cert_error_string(error));
367         if (sk_X509_num(chain) < 2) {
368             VLOG_ERR("only one certificate was received, so probably the peer "
369                      "is not configured to send its CA certificate");
370         }
371         return EPROTO;
372     }
373
374     fd = open(ca_cert_file, O_CREAT | O_EXCL | O_WRONLY, 0444);
375     if (fd < 0) {
376         VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
377                  ca_cert_file, strerror(errno));
378         return errno;
379     }
380
381     file = fdopen(fd, "w");
382     if (!file) {
383         int error = errno;
384         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
385                  strerror(error));
386         unlink(ca_cert_file);
387         return error;
388     }
389
390     if (!PEM_write_X509(file, ca_cert)) {
391         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
392                  "%s", ca_cert_file, ERR_error_string(ERR_get_error(), NULL));
393         fclose(file);
394         unlink(ca_cert_file);
395         return EIO;
396     }
397
398     if (fclose(file)) {
399         int error = errno;
400         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
401                  ca_cert_file, strerror(error));
402         unlink(ca_cert_file);
403         return error;
404     }
405
406     VLOG_WARN("successfully bootstrapped CA cert to %s", ca_cert_file);
407     log_ca_cert(ca_cert_file, ca_cert);
408     bootstrap_ca_cert = false;
409     has_ca_cert = true;
410
411     /* SSL_CTX_add_client_CA makes a copy of ca_cert's relevant data. */
412     SSL_CTX_add_client_CA(ctx, ca_cert);
413
414     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
415      * 'ca_cert' is owned by sslv->ssl, so we need to duplicate it. */
416     ca_cert = X509_dup(ca_cert);
417     if (!ca_cert) {
418         out_of_memory();
419     }
420     if (SSL_CTX_load_verify_locations(ctx, ca_cert_file, NULL) != 1) {
421         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
422                  ERR_error_string(ERR_get_error(), NULL));
423         return EPROTO;
424     }
425     VLOG_WARN("killing successful connection to retry using CA cert");
426     return EPROTO;
427 }
428
429 static int
430 ssl_connect(struct vconn *vconn)
431 {
432     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
433     int retval;
434
435     switch (sslv->state) {
436     case STATE_TCP_CONNECTING:
437         retval = check_connection_completion(sslv->fd);
438         if (retval) {
439             return retval;
440         }
441         sslv->state = STATE_SSL_CONNECTING;
442         /* Fall through. */
443
444     case STATE_SSL_CONNECTING:
445         retval = (sslv->type == CLIENT
446                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
447         if (retval != 1) {
448             int error = SSL_get_error(sslv->ssl, retval);
449             if (retval < 0 && ssl_wants_io(error)) {
450                 return EAGAIN;
451             } else {
452                 int unused;
453                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
454                                      : "SSL_accept"), retval, error, &unused);
455                 shutdown(sslv->fd, SHUT_RDWR);
456                 return EPROTO;
457             }
458         } else if (bootstrap_ca_cert) {
459             return do_ca_cert_bootstrap(vconn);
460         } else if ((SSL_get_verify_mode(sslv->ssl)
461                     & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
462                    != SSL_VERIFY_PEER) {
463             /* Two or more SSL connections completed at the same time while we
464              * were in bootstrap mode.  Only one of these can finish the
465              * bootstrap successfully.  The other one(s) must be rejected
466              * because they were not verified against the bootstrapped CA
467              * certificate.  (Alternatively we could verify them against the CA
468              * certificate, but that's more trouble than it's worth.  These
469              * connections will succeed the next time they retry, assuming that
470              * they have a certificate against the correct CA.) */
471             VLOG_ERR("rejecting SSL connection during bootstrap race window");
472             return EPROTO;
473         } else {
474             return 0;
475         }
476     }
477
478     NOT_REACHED();
479 }
480
481 static void
482 ssl_close(struct vconn *vconn)
483 {
484     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
485     poll_cancel(sslv->tx_waiter);
486     ssl_clear_txbuf(sslv);
487     ofpbuf_delete(sslv->rxbuf);
488     SSL_free(sslv->ssl);
489     close(sslv->fd);
490     free(sslv);
491 }
492
493 static int
494 interpret_ssl_error(const char *function, int ret, int error,
495                     int *want)
496 {
497     *want = SSL_NOTHING;
498
499     switch (error) {
500     case SSL_ERROR_NONE:
501         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
502         break;
503
504     case SSL_ERROR_ZERO_RETURN:
505         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
506         break;
507
508     case SSL_ERROR_WANT_READ:
509         *want = SSL_READING;
510         return EAGAIN;
511
512     case SSL_ERROR_WANT_WRITE:
513         *want = SSL_WRITING;
514         return EAGAIN;
515
516     case SSL_ERROR_WANT_CONNECT:
517         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
518         break;
519
520     case SSL_ERROR_WANT_ACCEPT:
521         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
522         break;
523
524     case SSL_ERROR_WANT_X509_LOOKUP:
525         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
526                     function);
527         break;
528
529     case SSL_ERROR_SYSCALL: {
530         int queued_error = ERR_get_error();
531         if (queued_error == 0) {
532             if (ret < 0) {
533                 int status = errno;
534                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
535                              function, strerror(status));
536                 return status;
537             } else {
538                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
539                              function);
540                 return EPROTO;
541             }
542         } else {
543             VLOG_WARN_RL(&rl, "%s: %s",
544                          function, ERR_error_string(queued_error, NULL));
545             break;
546         }
547     }
548
549     case SSL_ERROR_SSL: {
550         int queued_error = ERR_get_error();
551         if (queued_error != 0) {
552             VLOG_WARN_RL(&rl, "%s: %s",
553                          function, ERR_error_string(queued_error, NULL));
554         } else {
555             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
556                         function);
557         }
558         break;
559     }
560
561     default:
562         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
563         break;
564     }
565     return EIO;
566 }
567
568 static int
569 ssl_recv(struct vconn *vconn, struct ofpbuf **bufferp)
570 {
571     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
572     struct ofpbuf *rx;
573     size_t want_bytes;
574     int old_state;
575     ssize_t ret;
576
577     if (sslv->rxbuf == NULL) {
578         sslv->rxbuf = ofpbuf_new(1564);
579     }
580     rx = sslv->rxbuf;
581
582 again:
583     if (sizeof(struct ofp_header) > rx->size) {
584         want_bytes = sizeof(struct ofp_header) - rx->size;
585     } else {
586         struct ofp_header *oh = rx->data;
587         size_t length = ntohs(oh->length);
588         if (length < sizeof(struct ofp_header)) {
589             VLOG_ERR_RL(&rl, "received too-short ofp_header (%zu bytes)",
590                         length);
591             return EPROTO;
592         }
593         want_bytes = length - rx->size;
594         if (!want_bytes) {
595             *bufferp = rx;
596             sslv->rxbuf = NULL;
597             return 0;
598         }
599     }
600     ofpbuf_prealloc_tailroom(rx, want_bytes);
601
602     /* Behavior of zero-byte SSL_read is poorly defined. */
603     assert(want_bytes > 0);
604
605     old_state = SSL_get_state(sslv->ssl);
606     ret = SSL_read(sslv->ssl, ofpbuf_tail(rx), want_bytes);
607     if (old_state != SSL_get_state(sslv->ssl)) {
608         sslv->tx_want = SSL_NOTHING;
609         if (sslv->tx_waiter) {
610             poll_cancel(sslv->tx_waiter);
611             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
612         }
613     }
614     sslv->rx_want = SSL_NOTHING;
615
616     if (ret > 0) {
617         rx->size += ret;
618         if (ret == want_bytes) {
619             if (rx->size > sizeof(struct ofp_header)) {
620                 *bufferp = rx;
621                 sslv->rxbuf = NULL;
622                 return 0;
623             } else {
624                 goto again;
625             }
626         }
627         return EAGAIN;
628     } else {
629         int error = SSL_get_error(sslv->ssl, ret);
630         if (error == SSL_ERROR_ZERO_RETURN) {
631             /* Connection closed (EOF). */
632             if (rx->size) {
633                 VLOG_WARN_RL(&rl, "SSL_read: unexpected connection close");
634                 return EPROTO;
635             } else {
636                 return EOF;
637             }
638         } else {
639             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
640         }
641     }
642 }
643
644 static void
645 ssl_clear_txbuf(struct ssl_vconn *sslv)
646 {
647     ofpbuf_delete(sslv->txbuf);
648     sslv->txbuf = NULL;
649     sslv->tx_waiter = NULL;
650 }
651
652 static void
653 ssl_register_tx_waiter(struct vconn *vconn)
654 {
655     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
656     sslv->tx_waiter = poll_fd_callback(sslv->fd,
657                                        want_to_poll_events(sslv->tx_want),
658                                        ssl_tx_poll_callback, vconn);
659 }
660
661 static int
662 ssl_do_tx(struct vconn *vconn)
663 {
664     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
665
666     for (;;) {
667         int old_state = SSL_get_state(sslv->ssl);
668         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
669         if (old_state != SSL_get_state(sslv->ssl)) {
670             sslv->rx_want = SSL_NOTHING;
671         }
672         sslv->tx_want = SSL_NOTHING;
673         if (ret > 0) {
674             ofpbuf_pull(sslv->txbuf, ret);
675             if (sslv->txbuf->size == 0) {
676                 return 0;
677             }
678         } else {
679             int ssl_error = SSL_get_error(sslv->ssl, ret);
680             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
681                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
682                 return EPIPE;
683             } else {
684                 return interpret_ssl_error("SSL_write", ret, ssl_error,
685                                            &sslv->tx_want);
686             }
687         }
688     }
689 }
690
691 static void
692 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
693 {
694     struct vconn *vconn = vconn_;
695     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
696     int error = ssl_do_tx(vconn);
697     if (error != EAGAIN) {
698         ssl_clear_txbuf(sslv);
699     } else {
700         ssl_register_tx_waiter(vconn);
701     }
702 }
703
704 static int
705 ssl_send(struct vconn *vconn, struct ofpbuf *buffer)
706 {
707     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
708
709     if (sslv->txbuf) {
710         return EAGAIN;
711     } else {
712         int error;
713
714         sslv->txbuf = buffer;
715         error = ssl_do_tx(vconn);
716         switch (error) {
717         case 0:
718             ssl_clear_txbuf(sslv);
719             return 0;
720         case EAGAIN:
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, 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                     ofp_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 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             allocated_certs = 1 + 2 * allocated_certs;
1091             *certs = xrealloc(*certs, sizeof *certs * allocated_certs);
1092         }
1093         (*certs)[(*n_certs)++] = certificate;
1094
1095         /* Are there additional certificates in the file? */
1096         do {
1097             c = getc(file);
1098         } while (isspace(c));
1099         if (c == EOF) {
1100             break;
1101         }
1102         ungetc(c, file);
1103     }
1104     fclose(file);
1105     return 0;
1106 }
1107
1108
1109 /* Sets 'file_name' as the name of a file containing one or more X509
1110  * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1111  * certificate to the peer, which enables a switch to pick up the controller's
1112  * CA certificate on its first connection. */
1113 void
1114 vconn_ssl_set_peer_ca_cert_file(const char *file_name)
1115 {
1116     X509 **certs;
1117     size_t n_certs;
1118     size_t i;
1119
1120     if (ssl_init()) {
1121         return;
1122     }
1123
1124     if (!read_cert_file(file_name, &certs, &n_certs)) {
1125         for (i = 0; i < n_certs; i++) {
1126             if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1127                 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1128                          ERR_error_string(ERR_get_error(), NULL));
1129             }
1130         }
1131         free(certs);
1132     }
1133 }
1134
1135 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1136 static void
1137 log_ca_cert(const char *file_name, X509 *cert)
1138 {
1139     unsigned char digest[EVP_MAX_MD_SIZE];
1140     unsigned int n_bytes;
1141     struct ds fp;
1142     char *subject;
1143
1144     ds_init(&fp);
1145     if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1146         ds_put_cstr(&fp, "<out of memory>");
1147     } else {
1148         unsigned int i;
1149         for (i = 0; i < n_bytes; i++) {
1150             if (i) {
1151                 ds_put_char(&fp, ':');
1152             }
1153             ds_put_format(&fp, "%02hhx", digest[i]);
1154         }
1155     }
1156     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1157     VLOG_WARN("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1158               subject ? subject : "<out of memory>", ds_cstr(&fp));
1159     free(subject);
1160     ds_destroy(&fp);
1161 }
1162
1163 /* Sets 'file_name' as the name of the file from which to read the CA
1164  * certificate used to verify the peer within SSL connections.  If 'bootstrap'
1165  * is false, the file must exist.  If 'bootstrap' is false, then the file is
1166  * read if it is exists; if it does not, then it will be created from the CA
1167  * certificate received from the peer on the first SSL connection. */
1168 void
1169 vconn_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1170 {
1171     X509 **certs;
1172     size_t n_certs;
1173     struct stat s;
1174
1175     if (ssl_init()) {
1176         return;
1177     }
1178
1179     if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1180         bootstrap_ca_cert = true;
1181         ca_cert_file = xstrdup(file_name);
1182     } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1183         size_t i;
1184
1185         /* Set up list of CAs that the server will accept from the client. */
1186         for (i = 0; i < n_certs; i++) {
1187             /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1188             if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1189                 VLOG_ERR("failed to add client certificate %d from %s: %s",
1190                          i, file_name,
1191                          ERR_error_string(ERR_get_error(), NULL));
1192             } else {
1193                 log_ca_cert(file_name, certs[i]);
1194             }
1195             X509_free(certs[i]);
1196         }
1197
1198         /* Set up CAs for OpenSSL to trust in verifying the peer's
1199          * certificate. */
1200         if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1201             VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1202                      ERR_error_string(ERR_get_error(), NULL));
1203             return;
1204         }
1205
1206         has_ca_cert = true;
1207     }
1208 }