Prevent deadlock in OpenSSL.
[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                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
334                                      : "SSL_accept"), retval, error, NULL);
335                 shutdown(sslv->fd, SHUT_RDWR);
336                 return EPROTO;
337             }
338         } else {
339             return 0;
340         }
341     }
342
343     NOT_REACHED();
344 }
345
346 static void
347 ssl_close(struct vconn *vconn)
348 {
349     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
350     poll_cancel(sslv->tx_waiter);
351     SSL_free(sslv->ssl);
352     close(sslv->fd);
353     free(sslv);
354 }
355
356 static int
357 interpret_ssl_error(const char *function, int ret, int error,
358                     int *want)
359 {
360     *want = SSL_NOTHING;
361
362     switch (error) {
363     case SSL_ERROR_NONE:
364         VLOG_ERR("%s: unexpected SSL_ERROR_NONE", function);
365         break;
366
367     case SSL_ERROR_ZERO_RETURN:
368         VLOG_ERR("%s: unexpected SSL_ERROR_ZERO_RETURN", function);
369         break;
370
371     case SSL_ERROR_WANT_READ:
372         *want = SSL_READING;
373         return EAGAIN;
374
375     case SSL_ERROR_WANT_WRITE:
376         *want = SSL_WRITING;
377         return EAGAIN;
378
379     case SSL_ERROR_WANT_CONNECT:
380         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_CONNECT", function);
381         break;
382
383     case SSL_ERROR_WANT_ACCEPT:
384         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
385         break;
386
387     case SSL_ERROR_WANT_X509_LOOKUP:
388         VLOG_ERR("%s: unexpected SSL_ERROR_WANT_X509_LOOKUP", function);
389         break;
390
391     case SSL_ERROR_SYSCALL: {
392         int queued_error = ERR_get_error();
393         if (queued_error == 0) {
394             if (ret < 0) {
395                 int status = errno;
396                 VLOG_WARN("%s: system error (%s)", function, strerror(status));
397                 return status;
398             } else {
399                 VLOG_WARN("%s: unexpected SSL connection close", function);
400                 return EPROTO;
401             }
402         } else {
403             VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
404             break;
405         }
406     }
407
408     case SSL_ERROR_SSL: {
409         int queued_error = ERR_get_error();
410         if (queued_error != 0) {
411             VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
412         } else {
413             VLOG_ERR("%s: SSL_ERROR_SSL without queued error", function);
414         }
415         break;
416     }
417
418     default:
419         VLOG_ERR("%s: bad SSL error code %d", function, error);
420         break;
421     }
422     return EIO;
423 }
424
425 static int
426 ssl_recv(struct vconn *vconn, struct buffer **bufferp)
427 {
428     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
429     struct buffer *rx;
430     size_t want_bytes;
431     int old_state;
432     ssize_t ret;
433
434     if (sslv->rxbuf == NULL) {
435         sslv->rxbuf = buffer_new(1564);
436     }
437     rx = sslv->rxbuf;
438
439 again:
440     if (sizeof(struct ofp_header) > rx->size) {
441         want_bytes = sizeof(struct ofp_header) - rx->size;
442     } else {
443         struct ofp_header *oh = rx->data;
444         size_t length = ntohs(oh->length);
445         if (length < sizeof(struct ofp_header)) {
446             VLOG_ERR("received too-short ofp_header (%zu bytes)", length);
447             return EPROTO;
448         }
449         want_bytes = length - rx->size;
450         if (!want_bytes) {
451             *bufferp = rx;
452             sslv->rxbuf = NULL;
453             return 0;
454         }
455     }
456     buffer_reserve_tailroom(rx, want_bytes);
457
458     /* Behavior of zero-byte SSL_read is poorly defined. */
459     assert(want_bytes > 0);
460
461     old_state = SSL_get_state(sslv->ssl);
462     ret = SSL_read(sslv->ssl, buffer_tail(rx), want_bytes);
463     if (old_state != SSL_get_state(sslv->ssl)) {
464         sslv->tx_want = SSL_NOTHING;
465         if (sslv->tx_waiter) {
466             poll_cancel(sslv->tx_waiter);
467             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
468         }
469     }
470     sslv->rx_want = SSL_NOTHING;
471
472     if (ret > 0) {
473         rx->size += ret;
474         if (ret == want_bytes) {
475             if (rx->size > sizeof(struct ofp_header)) {
476                 *bufferp = rx;
477                 sslv->rxbuf = NULL;
478                 return 0;
479             } else {
480                 goto again;
481             }
482         }
483         return EAGAIN;
484     } else {
485         int error = SSL_get_error(sslv->ssl, ret);
486         if (error == SSL_ERROR_ZERO_RETURN) {
487             /* Connection closed (EOF). */
488             if (rx->size) {
489                 VLOG_WARN("SSL_read: unexpected connection close");
490                 return EPROTO;
491             } else {
492                 return EOF;
493             }
494         } else {
495             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
496         }
497     }
498 }
499
500 static void
501 ssl_clear_txbuf(struct ssl_vconn *sslv)
502 {
503     buffer_delete(sslv->txbuf);
504     sslv->txbuf = NULL;
505     sslv->tx_waiter = NULL;
506 }
507
508 static void
509 ssl_register_tx_waiter(struct vconn *vconn)
510 {
511     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
512     sslv->tx_waiter = poll_fd_callback(sslv->fd,
513                                        want_to_poll_events(sslv->tx_want),
514                                        ssl_tx_poll_callback, vconn);
515 }
516
517 static int
518 ssl_do_tx(struct vconn *vconn)
519 {
520     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
521
522     for (;;) {
523         int old_state = SSL_get_state(sslv->ssl);
524         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
525         if (old_state != SSL_get_state(sslv->ssl)) {
526             sslv->rx_want = SSL_NOTHING;
527         }
528         sslv->tx_want = SSL_NOTHING;
529         if (ret > 0) {
530             buffer_pull(sslv->txbuf, ret);
531             if (sslv->txbuf->size == 0) {
532                 return 0;
533             }
534         } else {
535             int ssl_error = SSL_get_error(sslv->ssl, ret);
536             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
537                 VLOG_WARN("SSL_write: connection closed");
538                 return EPIPE;
539             } else {
540                 return interpret_ssl_error("SSL_write", ret, ssl_error,
541                                            &sslv->tx_want);
542             }
543         }
544     }
545 }
546
547 static void
548 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
549 {
550     struct vconn *vconn = vconn_;
551     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
552     int error = ssl_do_tx(vconn);
553     if (error != EAGAIN) {
554         ssl_clear_txbuf(sslv);
555     } else {
556         ssl_register_tx_waiter(vconn);
557     }
558 }
559
560 static int
561 ssl_send(struct vconn *vconn, struct buffer *buffer)
562 {
563     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
564
565     if (sslv->txbuf) {
566         return EAGAIN;
567     } else {
568         int error;
569
570         sslv->txbuf = buffer;
571         error = ssl_do_tx(vconn);
572         switch (error) {
573         case 0:
574             ssl_clear_txbuf(sslv);
575             return 0;
576         case EAGAIN:
577             ssl_register_tx_waiter(vconn);
578             return 0;
579         default:
580             sslv->txbuf = NULL;
581             return error;
582         }
583     }
584 }
585
586 static void
587 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
588 {
589     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
590
591     switch (wait) {
592     case WAIT_CONNECT:
593         if (vconn_connect(vconn) != EAGAIN) {
594             poll_immediate_wake();
595         } else {
596             switch (sslv->state) {
597             case STATE_TCP_CONNECTING:
598                 poll_fd_wait(sslv->fd, POLLOUT);
599                 break;
600
601             case STATE_SSL_CONNECTING:
602                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
603                  * set up the status that we test here. */
604                 poll_fd_wait(sslv->fd,
605                              want_to_poll_events(SSL_want(sslv->ssl)));
606                 break;
607
608             default:
609                 NOT_REACHED();
610             }
611         }
612         break;
613
614     case WAIT_RECV:
615         if (sslv->rx_want != SSL_NOTHING) {
616             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
617         } else {
618             poll_immediate_wake();
619         }
620         break;
621
622     case WAIT_SEND:
623         if (!sslv->txbuf) {
624             /* We have room in our tx queue. */
625             poll_immediate_wake();
626         } else {
627             /* The call to ssl_tx_poll_callback() will wake us up. */
628         }
629         break;
630
631     default:
632         NOT_REACHED();
633     }
634 }
635
636 struct vconn_class ssl_vconn_class = {
637     .name = "ssl",
638     .open = ssl_open,
639     .close = ssl_close,
640     .connect = ssl_connect,
641     .recv = ssl_recv,
642     .send = ssl_send,
643     .wait = ssl_wait,
644 };
645 \f
646 /* Passive SSL. */
647
648 struct pssl_vconn
649 {
650     struct vconn vconn;
651     int fd;
652 };
653
654 static struct pssl_vconn *
655 pssl_vconn_cast(struct vconn *vconn)
656 {
657     assert(vconn->class == &pssl_vconn_class);
658     return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
659 }
660
661 static int
662 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
663 {
664     struct sockaddr_in sin;
665     struct pssl_vconn *pssl;
666     int retval;
667     int fd;
668     unsigned int yes = 1;
669
670     retval = ssl_init();
671     if (retval) {
672         return retval;
673     }
674
675     /* Create socket. */
676     fd = socket(AF_INET, SOCK_STREAM, 0);
677     if (fd < 0) {
678         int error = errno;
679         VLOG_ERR("%s: socket: %s", name, strerror(error));
680         return error;
681     }
682
683     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
684         int error = errno;
685         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
686         return error;
687     }
688
689     memset(&sin, 0, sizeof sin);
690     sin.sin_family = AF_INET;
691     sin.sin_addr.s_addr = htonl(INADDR_ANY);
692     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
693     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
694     if (retval < 0) {
695         int error = errno;
696         VLOG_ERR("%s: bind: %s", name, strerror(error));
697         close(fd);
698         return error;
699     }
700
701     retval = listen(fd, 10);
702     if (retval < 0) {
703         int error = errno;
704         VLOG_ERR("%s: listen: %s", name, strerror(error));
705         close(fd);
706         return error;
707     }
708
709     retval = set_nonblocking(fd);
710     if (retval) {
711         close(fd);
712         return retval;
713     }
714
715     pssl = xmalloc(sizeof *pssl);
716     pssl->vconn.class = &pssl_vconn_class;
717     pssl->vconn.connect_status = 0;
718     pssl->fd = fd;
719     *vconnp = &pssl->vconn;
720     return 0;
721 }
722
723 static void
724 pssl_close(struct vconn *vconn)
725 {
726     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
727     close(pssl->fd);
728     free(pssl);
729 }
730
731 static int
732 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
733 {
734     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
735     int new_fd;
736     int error;
737
738     new_fd = accept(pssl->fd, NULL, NULL);
739     if (new_fd < 0) {
740         int error = errno;
741         if (error != EAGAIN) {
742             VLOG_DBG("accept: %s", strerror(error));
743         }
744         return error;
745     }
746
747     error = set_nonblocking(new_fd);
748     if (error) {
749         close(new_fd);
750         return error;
751     }
752
753     return new_ssl_vconn("ssl" /* FIXME */, new_fd,
754                          SERVER, STATE_SSL_CONNECTING, new_vconnp);
755 }
756
757 static void
758 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
759 {
760     struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
761     assert(wait == WAIT_ACCEPT);
762     poll_fd_wait(pssl->fd, POLLIN);
763 }
764
765 struct vconn_class pssl_vconn_class = {
766     .name = "pssl",
767     .open = pssl_open,
768     .close = pssl_close,
769     .accept = pssl_accept,
770     .wait = pssl_wait,
771 };
772 \f
773 /*
774  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
775  * OpenSSL is requesting that we call it back when the socket is ready for read
776  * or writing, respectively.
777  */
778 static bool
779 ssl_wants_io(int ssl_error)
780 {
781     return (ssl_error == SSL_ERROR_WANT_WRITE
782             || ssl_error == SSL_ERROR_WANT_READ);
783 }
784
785 static int
786 ssl_init(void)
787 {
788     static int init_status = -1;
789     if (init_status < 0) {
790         init_status = do_ssl_init();
791         assert(init_status >= 0);
792     }
793     return init_status;
794 }
795
796 static int
797 do_ssl_init(void)
798 {
799     SSL_METHOD *method;
800
801     SSL_library_init();
802     SSL_load_error_strings();
803
804     method = TLSv1_method();
805     if (method == NULL) {
806         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
807         return ENOPROTOOPT;
808     }
809
810     ctx = SSL_CTX_new(method);
811     if (ctx == NULL) {
812         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
813         return ENOPROTOOPT;
814     }
815     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
816     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
817     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
818     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
819     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
820                        NULL);
821
822     return 0;
823 }
824
825 static DH *
826 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
827 {
828     struct dh {
829         int keylength;
830         DH *dh;
831         DH *(*constructor)(void);
832     };
833
834     static struct dh dh_table[] = {
835         {1024, NULL, get_dh1024},
836         {2048, NULL, get_dh2048},
837         {4096, NULL, get_dh4096},
838     };
839
840     struct dh *dh;
841
842     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
843         if (dh->keylength == keylength) {
844             if (!dh->dh) {
845                 dh->dh = dh->constructor();
846                 if (!dh->dh) {
847                     fatal(ENOMEM, "out of memory constructing "
848                           "Diffie-Hellman parameters");
849                 }
850             }
851             return dh->dh;
852         }
853     }
854     VLOG_ERR("no Diffie-Hellman parameters for key length %d", keylength);
855     return NULL;
856 }
857
858 void
859 vconn_ssl_set_private_key_file(const char *file_name)
860 {
861     if (ssl_init()) {
862         return;
863     }
864     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
865         VLOG_ERR("SSL_use_PrivateKey_file: %s",
866                  ERR_error_string(ERR_get_error(), NULL));
867         return;
868     }
869     has_private_key = true;
870 }
871
872 void
873 vconn_ssl_set_certificate_file(const char *file_name)
874 {
875     if (ssl_init()) {
876         return;
877     }
878     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
879         VLOG_ERR("SSL_use_certificate_file: %s",
880                  ERR_error_string(ERR_get_error(), NULL));
881         return;
882     }
883     has_certificate = true;
884 }
885
886 void
887 vconn_ssl_set_ca_cert_file(const char *file_name)
888 {
889     STACK_OF(X509_NAME) *ca_list;
890
891     if (ssl_init()) {
892         return;
893     }
894
895     /* Set up list of CAs that the server will accept from the client. */
896     ca_list = SSL_load_client_CA_file(file_name);
897     if (ca_list == NULL) {
898         VLOG_ERR("SSL_load_client_CA_file: %s",
899                  ERR_error_string(ERR_get_error(), NULL));
900         return;
901     }
902     SSL_CTX_set_client_CA_list(ctx, ca_list);
903
904     /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
905     if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
906         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
907                  ERR_error_string(ERR_get_error(), NULL));
908         return;
909     }
910
911     has_ca_cert = true;
912 }