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