vconn: New function vconn_ssl_is_configured().
[openvswitch] / 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 "vconn-ssl.h"
35 #include "dhparams.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <string.h>
40 #include <netinet/tcp.h>
41 #include <openssl/err.h>
42 #include <openssl/ssl.h>
43 #include <poll.h>
44 #include <unistd.h>
45 #include "buffer.h"
46 #include "socket-util.h"
47 #include "util.h"
48 #include "openflow.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "ofp-print.h"
52 #include "socket-util.h"
53 #include "vconn.h"
54
55 #include "vlog.h"
56 #define THIS_MODULE VLM_vconn_ssl
57
58 /* Active SSL. */
59
60 enum ssl_state {
61     STATE_TCP_CONNECTING,
62     STATE_SSL_CONNECTING
63 };
64
65 enum session_type {
66     CLIENT,
67     SERVER
68 };
69
70 struct ssl_vconn
71 {
72     struct vconn vconn;
73     enum ssl_state state;
74     int connect_error;
75     enum session_type type;
76     int fd;
77     SSL *ssl;
78     struct buffer *rxbuf;
79     struct buffer *txbuf;
80     struct poll_waiter *tx_waiter;
81
82     /* rx_want and tx_want record the result of the last call to SSL_read()
83      * and SSL_write(), respectively:
84      *
85      *    - If the call reported that data needed to be read from the file
86      *      descriptor, the corresponding member is set to SSL_READING.
87      *
88      *    - If the call reported that data needed to be written to the file
89      *      descriptor, the corresponding member is set to SSL_WRITING.
90      *
91      *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
92      *      call completed successfully (or with an error) and that there is no
93      *      need to block.
94      *
95      * These are needed because there is no way to ask OpenSSL what a data read
96      * or write would require without giving it a buffer to receive into or
97      * data to send, respectively.  (Note that the SSL_want() status is
98      * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
99      * its value.)
100      *
101      * A single call to SSL_read() or SSL_write() can perform both reading
102      * and writing and thus invalidate not one of these values but actually
103      * both.  Consider this situation, for example:
104      *
105      *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
106      *
107      *    - SSL_read() laters succeeds reading from 'fd' and clears out the
108      *      whole receive buffer, so rx_want gets SSL_READING.
109      *
110      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
111      *      blocks.
112      *
113      *    - Now we're stuck blocking until the peer sends us data, even though
114      *      SSL_write() could now succeed, which could easily be a deadlock
115      *      condition.
116      *
117      * On the other hand, we can't reset both tx_want and rx_want on every call
118      * to SSL_read() or SSL_write(), because that would produce livelock,
119      * e.g. in this situation:
120      *
121      *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
122      *
123      *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
124      *      but tx_want gets reset to SSL_NOTHING.
125      *
126      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
127      *      blocks.
128      *
129      *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
130      *      that no blocking is necessary.
131      *
132      * The solution we adopt here is to set tx_want to SSL_NOTHING after
133      * calling SSL_read() only if the SSL state of the connection changed,
134      * which indicates that an SSL-level renegotiation made some progress, and
135      * similarly for rx_want and SSL_write().  This prevents both the
136      * deadlock and livelock situations above.
137      */
138     int rx_want, tx_want;
139 };
140
141 /* SSL context created by ssl_init(). */
142 static SSL_CTX *ctx;
143
144 /* Required configuration. */
145 static bool has_private_key, has_certificate, has_ca_cert;
146
147 static int ssl_init(void);
148 static int do_ssl_init(void);
149 static bool ssl_wants_io(int ssl_error);
150 static void ssl_close(struct vconn *);
151 static int interpret_ssl_error(const char *function, int ret, int error,
152                                int *want);
153 static void ssl_tx_poll_callback(int fd, short int revents, void *vconn_);
154 static DH *tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength);
155
156 short int
157 want_to_poll_events(int want)
158 {
159     switch (want) {
160     case SSL_NOTHING:
161         NOT_REACHED();
162
163     case SSL_READING:
164         return POLLIN;
165
166     case SSL_WRITING:
167         return POLLOUT;
168
169     default:
170         NOT_REACHED();
171     }
172 }
173
174 static int
175 new_ssl_vconn(const char *name, int fd, enum session_type type,
176               enum ssl_state state, const struct sockaddr_in *sin,
177               struct vconn **vconnp)
178 {
179     struct ssl_vconn *sslv;
180     SSL *ssl = NULL;
181     int on = 1;
182     int retval;
183
184     /* Check for all the needful configuration. */
185     if (!has_private_key) {
186         VLOG_ERR("Private key must be configured to use SSL");
187         goto error;
188     }
189     if (!has_certificate) {
190         VLOG_ERR("Certificate must be configured to use SSL");
191         goto error;
192     }
193     if (!has_ca_cert) {
194         VLOG_ERR("CA certificate must be configured to use SSL");
195         goto error;
196     }
197     if (!SSL_CTX_check_private_key(ctx)) {
198         VLOG_ERR("Private key does not match certificate public key");
199         goto error;
200     }
201
202     /* Disable Nagle. */
203     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
204     if (retval) {
205         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
206         close(fd);
207         return errno;
208     }
209
210     /* Create and configure OpenSSL stream. */
211     ssl = SSL_new(ctx);
212     if (ssl == NULL) {
213         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
214         close(fd);
215         return ENOPROTOOPT;
216     }
217     if (SSL_set_fd(ssl, fd) == 0) {
218         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
219         goto error;
220     }
221
222     /* Create and return the ssl_vconn. */
223     sslv = xmalloc(sizeof *sslv);
224     sslv->vconn.class = &ssl_vconn_class;
225     sslv->vconn.connect_status = EAGAIN;
226     sslv->vconn.ip = sin->sin_addr.s_addr;
227     sslv->state = state;
228     sslv->type = type;
229     sslv->fd = fd;
230     sslv->ssl = ssl;
231     sslv->rxbuf = NULL;
232     sslv->txbuf = NULL;
233     sslv->tx_waiter = NULL;
234     sslv->rx_want = sslv->tx_want = SSL_NOTHING;
235     *vconnp = &sslv->vconn;
236     return 0;
237
238 error:
239     if (ssl) {
240         SSL_free(ssl);
241     }
242     close(fd);
243     return ENOPROTOOPT;
244 }
245
246 static struct ssl_vconn *
247 ssl_vconn_cast(struct vconn *vconn)
248 {
249     assert(vconn->class == &ssl_vconn_class);
250     return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
251 }
252
253 static int
254 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
255 {
256     char *save_ptr, *host_name, *port_string;
257     struct sockaddr_in sin;
258     int retval;
259     int fd;
260
261     retval = ssl_init();
262     if (retval) {
263         return retval;
264     }
265
266     /* Glibc 2.7 has a bug in strtok_r when compiling with optimization that
267      * can cause segfaults here:
268      * http://sources.redhat.com/bugzilla/show_bug.cgi?id=5614.
269      * Using "::" instead of the obvious ":" works around it. */
270     host_name = strtok_r(suffix, "::", &save_ptr);
271     port_string = strtok_r(NULL, "::", &save_ptr);
272     if (!host_name) {
273         fatal(0, "%s: bad peer name format", name);
274     }
275
276     memset(&sin, 0, sizeof sin);
277     sin.sin_family = AF_INET;
278     if (lookup_ip(host_name, &sin.sin_addr)) {
279         return ENOENT;
280     }
281     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
282                          : OFP_SSL_PORT);
283
284     /* Create socket. */
285     fd = socket(AF_INET, SOCK_STREAM, 0);
286     if (fd < 0) {
287         VLOG_ERR("%s: socket: %s", name, strerror(errno));
288         return errno;
289     }
290     retval = set_nonblocking(fd);
291     if (retval) {
292         close(fd);
293         return retval;
294     }
295
296     /* Connect socket. */
297     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
298     if (retval < 0) {
299         if (errno == EINPROGRESS) {
300             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
301                                  &sin, vconnp);
302         } else {
303             int error = errno;
304             VLOG_ERR("%s: connect: %s", name, strerror(error));
305             close(fd);
306             return error;
307         }
308     } else {
309         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
310                              &sin, vconnp);
311     }
312 }
313
314 static int
315 ssl_connect(struct vconn *vconn)
316 {
317     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
318     int retval;
319
320     switch (sslv->state) {
321     case STATE_TCP_CONNECTING:
322         retval = check_connection_completion(sslv->fd);
323         if (retval) {
324             return retval;
325         }
326         sslv->state = STATE_SSL_CONNECTING;
327         /* Fall through. */
328
329     case STATE_SSL_CONNECTING:
330         retval = (sslv->type == CLIENT
331                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
332         if (retval != 1) {
333             int error = SSL_get_error(sslv->ssl, retval);
334             if (retval < 0 && ssl_wants_io(error)) {
335                 return EAGAIN;
336             } else {
337                 int unused;
338                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
339                                      : "SSL_accept"), retval, error, &unused);
340                 shutdown(sslv->fd, SHUT_RDWR);
341                 return EPROTO;
342             }
343         } else {
344             return 0;
345         }
346     }
347
348     NOT_REACHED();
349 }
350
351 static void
352 ssl_close(struct vconn *vconn)
353 {
354     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
355     poll_cancel(sslv->tx_waiter);
356     SSL_free(sslv->ssl);
357     close(sslv->fd);
358     free(sslv);
359 }
360
361 static int
362 interpret_ssl_error(const char *function, int ret, int error,
363                     int *want)
364 {
365     *want = SSL_NOTHING;
366
367     switch (error) {
368     case SSL_ERROR_NONE:
369         VLOG_ERR("%s: unexpected SSL_ERROR_NONE", function);
370         break;
371
372     case SSL_ERROR_ZERO_RETURN:
373         VLOG_ERR("%s: unexpected SSL_ERROR_ZERO_RETURN", function);
374         break;
375
376     case SSL_ERROR_WANT_READ:
377         *want = SSL_READING;
378         return EAGAIN;
379
380     case SSL_ERROR_WANT_WRITE:
381         *want = SSL_WRITING;
382         return EAGAIN;
383
384     case SSL_ERROR_WANT_CONNECT:
385         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_CONNECT", function);
386         break;
387
388     case SSL_ERROR_WANT_ACCEPT:
389         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
390         break;
391
392     case SSL_ERROR_WANT_X509_LOOKUP:
393         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_X509_LOOKUP", function);
394         break;
395
396     case SSL_ERROR_SYSCALL: {
397         int queued_error = ERR_get_error();
398         if (queued_error == 0) {
399             if (ret < 0) {
400                 int status = errno;
401                 VLOG_WARN("%s: system error (%s)", function, strerror(status));
402                 return status;
403             } else {
404                 VLOG_WARN("%s: unexpected SSL connection close", function);
405                 return EPROTO;
406             }
407         } else {
408             VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
409             break;
410         }
411     }
412
413     case SSL_ERROR_SSL: {
414         int queued_error = ERR_get_error();
415         if (queued_error != 0) {
416             VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
417         } else {
418             VLOG_ERR("%s: SSL_ERROR_SSL without queued error", function);
419         }
420         break;
421     }
422
423     default:
424         VLOG_ERR("%s: bad SSL error code %d", function, error);
425         break;
426     }
427     return EIO;
428 }
429
430 static int
431 ssl_recv(struct vconn *vconn, struct buffer **bufferp)
432 {
433     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
434     struct buffer *rx;
435     size_t want_bytes;
436     int old_state;
437     ssize_t ret;
438
439     if (sslv->rxbuf == NULL) {
440         sslv->rxbuf = buffer_new(1564);
441     }
442     rx = sslv->rxbuf;
443
444 again:
445     if (sizeof(struct ofp_header) > rx->size) {
446         want_bytes = sizeof(struct ofp_header) - rx->size;
447     } else {
448         struct ofp_header *oh = rx->data;
449         size_t length = ntohs(oh->length);
450         if (length < sizeof(struct ofp_header)) {
451             VLOG_ERR("received too-short ofp_header (%zu bytes)", length);
452             return EPROTO;
453         }
454         want_bytes = length - rx->size;
455         if (!want_bytes) {
456             *bufferp = rx;
457             sslv->rxbuf = NULL;
458             return 0;
459         }
460     }
461     buffer_prealloc_tailroom(rx, want_bytes);
462
463     /* Behavior of zero-byte SSL_read is poorly defined. */
464     assert(want_bytes > 0);
465
466     old_state = SSL_get_state(sslv->ssl);
467     ret = SSL_read(sslv->ssl, buffer_tail(rx), want_bytes);
468     if (old_state != SSL_get_state(sslv->ssl)) {
469         sslv->tx_want = SSL_NOTHING;
470         if (sslv->tx_waiter) {
471             poll_cancel(sslv->tx_waiter);
472             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
473         }
474     }
475     sslv->rx_want = SSL_NOTHING;
476
477     if (ret > 0) {
478         rx->size += ret;
479         if (ret == want_bytes) {
480             if (rx->size > sizeof(struct ofp_header)) {
481                 *bufferp = rx;
482                 sslv->rxbuf = NULL;
483                 return 0;
484             } else {
485                 goto again;
486             }
487         }
488         return EAGAIN;
489     } else {
490         int error = SSL_get_error(sslv->ssl, ret);
491         if (error == SSL_ERROR_ZERO_RETURN) {
492             /* Connection closed (EOF). */
493             if (rx->size) {
494                 VLOG_WARN("SSL_read: unexpected connection close");
495                 return EPROTO;
496             } else {
497                 return EOF;
498             }
499         } else {
500             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
501         }
502     }
503 }
504
505 static void
506 ssl_clear_txbuf(struct ssl_vconn *sslv)
507 {
508     buffer_delete(sslv->txbuf);
509     sslv->txbuf = NULL;
510     sslv->tx_waiter = NULL;
511 }
512
513 static void
514 ssl_register_tx_waiter(struct vconn *vconn)
515 {
516     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
517     sslv->tx_waiter = poll_fd_callback(sslv->fd,
518                                        want_to_poll_events(sslv->tx_want),
519                                        ssl_tx_poll_callback, vconn);
520 }
521
522 static int
523 ssl_do_tx(struct vconn *vconn)
524 {
525     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
526
527     for (;;) {
528         int old_state = SSL_get_state(sslv->ssl);
529         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
530         if (old_state != SSL_get_state(sslv->ssl)) {
531             sslv->rx_want = SSL_NOTHING;
532         }
533         sslv->tx_want = SSL_NOTHING;
534         if (ret > 0) {
535             buffer_pull(sslv->txbuf, ret);
536             if (sslv->txbuf->size == 0) {
537                 return 0;
538             }
539         } else {
540             int ssl_error = SSL_get_error(sslv->ssl, ret);
541             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
542                 VLOG_WARN("SSL_write: connection closed");
543                 return EPIPE;
544             } else {
545                 return interpret_ssl_error("SSL_write", ret, ssl_error,
546                                            &sslv->tx_want);
547             }
548         }
549     }
550 }
551
552 static void
553 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
554 {
555     struct vconn *vconn = vconn_;
556     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
557     int error = ssl_do_tx(vconn);
558     if (error != EAGAIN) {
559         ssl_clear_txbuf(sslv);
560     } else {
561         ssl_register_tx_waiter(vconn);
562     }
563 }
564
565 static int
566 ssl_send(struct vconn *vconn, struct buffer *buffer)
567 {
568     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
569
570     if (sslv->txbuf) {
571         return EAGAIN;
572     } else {
573         int error;
574
575         sslv->txbuf = buffer;
576         error = ssl_do_tx(vconn);
577         switch (error) {
578         case 0:
579             ssl_clear_txbuf(sslv);
580             return 0;
581         case EAGAIN:
582             ssl_register_tx_waiter(vconn);
583             return 0;
584         default:
585             sslv->txbuf = NULL;
586             return error;
587         }
588     }
589 }
590
591 static void
592 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
593 {
594     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
595
596     switch (wait) {
597     case WAIT_CONNECT:
598         if (vconn_connect(vconn) != EAGAIN) {
599             poll_immediate_wake();
600         } else {
601             switch (sslv->state) {
602             case STATE_TCP_CONNECTING:
603                 poll_fd_wait(sslv->fd, POLLOUT);
604                 break;
605
606             case STATE_SSL_CONNECTING:
607                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
608                  * set up the status that we test here. */
609                 poll_fd_wait(sslv->fd,
610                              want_to_poll_events(SSL_want(sslv->ssl)));
611                 break;
612
613             default:
614                 NOT_REACHED();
615             }
616         }
617         break;
618
619     case WAIT_RECV:
620         if (sslv->rx_want != SSL_NOTHING) {
621             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
622         } else {
623             poll_immediate_wake();
624         }
625         break;
626
627     case WAIT_SEND:
628         if (!sslv->txbuf) {
629             /* We have room in our tx queue. */
630             poll_immediate_wake();
631         } else {
632             /* The call to ssl_tx_poll_callback() will wake us up. */
633         }
634         break;
635
636     default:
637         NOT_REACHED();
638     }
639 }
640
641 struct vconn_class ssl_vconn_class = {
642     .name = "ssl",
643     .open = ssl_open,
644     .close = ssl_close,
645     .connect = ssl_connect,
646     .recv = ssl_recv,
647     .send = ssl_send,
648     .wait = ssl_wait,
649 };
650 \f
651 /* Passive SSL. */
652
653 struct pssl_vconn
654 {
655     struct vconn vconn;
656     int fd;
657 };
658
659 static struct pssl_vconn *
660 pssl_vconn_cast(struct vconn *vconn)
661 {
662     assert(vconn->class == &pssl_vconn_class);
663     return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
664 }
665
666 static int
667 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
668 {
669     struct sockaddr_in sin;
670     struct pssl_vconn *pssl;
671     int retval;
672     int fd;
673     unsigned int yes = 1;
674
675     retval = ssl_init();
676     if (retval) {
677         return retval;
678     }
679
680     /* Create socket. */
681     fd = socket(AF_INET, SOCK_STREAM, 0);
682     if (fd < 0) {
683         int error = errno;
684         VLOG_ERR("%s: socket: %s", name, strerror(error));
685         return error;
686     }
687
688     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
689         int error = errno;
690         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
691         return error;
692     }
693
694     memset(&sin, 0, sizeof sin);
695     sin.sin_family = AF_INET;
696     sin.sin_addr.s_addr = htonl(INADDR_ANY);
697     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
698     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
699     if (retval < 0) {
700         int error = errno;
701         VLOG_ERR("%s: bind: %s", name, strerror(error));
702         close(fd);
703         return error;
704     }
705
706     retval = listen(fd, 10);
707     if (retval < 0) {
708         int error = errno;
709         VLOG_ERR("%s: listen: %s", name, strerror(error));
710         close(fd);
711         return error;
712     }
713
714     retval = set_nonblocking(fd);
715     if (retval) {
716         close(fd);
717         return retval;
718     }
719
720     pssl = xmalloc(sizeof *pssl);
721     pssl->vconn.class = &pssl_vconn_class;
722     pssl->vconn.connect_status = 0;
723     pssl->fd = fd;
724     *vconnp = &pssl->vconn;
725     return 0;
726 }
727
728 static void
729 pssl_close(struct vconn *vconn)
730 {
731     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
732     close(pssl->fd);
733     free(pssl);
734 }
735
736 static int
737 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
738 {
739     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
740     struct sockaddr_in sin;
741     socklen_t sin_len = sizeof sin;
742     char name[128];
743     int new_fd;
744     int error;
745
746     new_fd = accept(pssl->fd, &sin, &sin_len);
747     if (new_fd < 0) {
748         int error = errno;
749         if (error != EAGAIN) {
750             VLOG_DBG("accept: %s", strerror(error));
751         }
752         return error;
753     }
754
755     error = set_nonblocking(new_fd);
756     if (error) {
757         close(new_fd);
758         return error;
759     }
760
761     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
762     if (sin.sin_port != htons(OFP_SSL_PORT)) {
763         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
764     }
765     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
766                          new_vconnp);
767 }
768
769 static void
770 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
771 {
772     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
773     assert(wait == WAIT_ACCEPT);
774     poll_fd_wait(pssl->fd, POLLIN);
775 }
776
777 struct vconn_class pssl_vconn_class = {
778     .name = "pssl",
779     .open = pssl_open,
780     .close = pssl_close,
781     .accept = pssl_accept,
782     .wait = pssl_wait,
783 };
784 \f
785 /*
786  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
787  * OpenSSL is requesting that we call it back when the socket is ready for read
788  * or writing, respectively.
789  */
790 static bool
791 ssl_wants_io(int ssl_error)
792 {
793     return (ssl_error == SSL_ERROR_WANT_WRITE
794             || ssl_error == SSL_ERROR_WANT_READ);
795 }
796
797 static int
798 ssl_init(void)
799 {
800     static int init_status = -1;
801     if (init_status < 0) {
802         init_status = do_ssl_init();
803         assert(init_status >= 0);
804     }
805     return init_status;
806 }
807
808 static int
809 do_ssl_init(void)
810 {
811     SSL_METHOD *method;
812
813     SSL_library_init();
814     SSL_load_error_strings();
815
816     method = TLSv1_method();
817     if (method == NULL) {
818         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
819         return ENOPROTOOPT;
820     }
821
822     ctx = SSL_CTX_new(method);
823     if (ctx == NULL) {
824         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
825         return ENOPROTOOPT;
826     }
827     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
828     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
829     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
830     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
831     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
832                        NULL);
833
834     return 0;
835 }
836
837 static DH *
838 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
839 {
840     struct dh {
841         int keylength;
842         DH *dh;
843         DH *(*constructor)(void);
844     };
845
846     static struct dh dh_table[] = {
847         {1024, NULL, get_dh1024},
848         {2048, NULL, get_dh2048},
849         {4096, NULL, get_dh4096},
850     };
851
852     struct dh *dh;
853
854     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
855         if (dh->keylength == keylength) {
856             if (!dh->dh) {
857                 dh->dh = dh->constructor();
858                 if (!dh->dh) {
859                     fatal(ENOMEM, "out of memory constructing "
860                           "Diffie-Hellman parameters");
861                 }
862             }
863             return dh->dh;
864         }
865     }
866     VLOG_ERR("no Diffie-Hellman parameters for key length %d", keylength);
867     return NULL;
868 }
869
870 /* Returns true if SSL is at least partially configured. */
871 bool
872 vconn_ssl_is_configured(void) 
873 {
874     return has_private_key || has_certificate || has_ca_cert;
875 }
876
877 void
878 vconn_ssl_set_private_key_file(const char *file_name)
879 {
880     if (ssl_init()) {
881         return;
882     }
883     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
884         VLOG_ERR("SSL_use_PrivateKey_file: %s",
885                  ERR_error_string(ERR_get_error(), NULL));
886         return;
887     }
888     has_private_key = true;
889 }
890
891 void
892 vconn_ssl_set_certificate_file(const char *file_name)
893 {
894     if (ssl_init()) {
895         return;
896     }
897     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
898         VLOG_ERR("SSL_use_certificate_file: %s",
899                  ERR_error_string(ERR_get_error(), NULL));
900         return;
901     }
902     has_certificate = true;
903 }
904
905 void
906 vconn_ssl_set_ca_cert_file(const char *file_name)
907 {
908     STACK_OF(X509_NAME) *ca_list;
909
910     if (ssl_init()) {
911         return;
912     }
913
914     /* Set up list of CAs that the server will accept from the client. */
915     ca_list = SSL_load_client_CA_file(file_name);
916     if (ca_list == NULL) {
917         VLOG_ERR("SSL_load_client_CA_file: %s",
918                  ERR_error_string(ERR_get_error(), NULL));
919         return;
920     }
921     SSL_CTX_set_client_CA_list(ctx, ca_list);
922
923     /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
924     if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
925         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
926                  ERR_error_string(ERR_get_error(), NULL));
927         return;
928     }
929
930     has_ca_cert = true;
931 }