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