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