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