1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
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:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
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
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.
34 #include "vconn-ssl.h"
39 #include <netinet/tcp.h>
40 #include <openssl/err.h>
41 #include <openssl/ssl.h>
45 #include "socket-util.h"
48 #include "poll-loop.h"
49 #include "ofp-print.h"
50 #include "socket-util.h"
54 #define THIS_MODULE VLM_vconn_ssl
73 enum session_type type;
78 struct poll_waiter *tx_waiter;
80 /* rx_want and tx_want record the result of the last call to SSL_read()
81 * and SSL_write(), respectively:
83 * - If the call reported that data needed to be read from the file
84 * descriptor, the corresponding member is set to SSL_READING.
86 * - If the call reported that data needed to be written to the file
87 * descriptor, the corresponding member is set to SSL_WRITING.
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
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
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:
103 * - SSL_write() blocks on a read, so tx_want gets SSL_READING.
105 * - SSL_read() laters succeeds reading from 'fd' and clears out the
106 * whole receive buffer, so rx_want gets SSL_READING.
108 * - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
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
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:
119 * - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
121 * - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
122 * but tx_want gets reset to SSL_NOTHING.
124 * - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
127 * - Client wakes up immediately since SSL_NOTHING in tx_want indicates
128 * that no blocking is necessary.
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.
136 int rx_want, tx_want;
139 /* SSL context created by ssl_init(). */
142 /* Required configuration. */
143 static bool has_private_key, has_certificate, has_ca_cert;
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,
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);
155 want_to_poll_events(int want)
173 new_ssl_vconn(const char *name, int fd, enum session_type type,
174 enum ssl_state state, struct vconn **vconnp)
176 struct ssl_vconn *sslv;
181 /* Check for all the needful configuration. */
182 if (!has_private_key) {
183 VLOG_ERR("Private key must be configured to use SSL");
186 if (!has_certificate) {
187 VLOG_ERR("Certificate must be configured to use SSL");
191 VLOG_ERR("CA certificate must be configured to use SSL");
194 if (!SSL_CTX_check_private_key(ctx)) {
195 VLOG_ERR("Private key does not match certificate public key");
200 retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
202 VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
207 /* Create and configure OpenSSL stream. */
210 VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
214 if (SSL_set_fd(ssl, fd) == 0) {
215 VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
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;
229 sslv->tx_waiter = NULL;
230 sslv->rx_want = sslv->tx_want = SSL_NOTHING;
231 *vconnp = &sslv->vconn;
242 static struct ssl_vconn *
243 ssl_vconn_cast(struct vconn *vconn)
245 assert(vconn->class == &ssl_vconn_class);
246 return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
250 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
252 char *save_ptr, *host_name, *port_string;
253 struct sockaddr_in sin;
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);
269 fatal(0, "%s: bad peer name format", name);
272 memset(&sin, 0, sizeof sin);
273 sin.sin_family = AF_INET;
274 if (lookup_ip(host_name, &sin.sin_addr)) {
277 sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
281 fd = socket(AF_INET, SOCK_STREAM, 0);
283 VLOG_ERR("%s: socket: %s", name, strerror(errno));
286 retval = set_nonblocking(fd);
292 /* Connect socket. */
293 retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
295 if (errno == EINPROGRESS) {
296 return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
300 VLOG_ERR("%s: connect: %s", name, strerror(error));
305 return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
311 ssl_connect(struct vconn *vconn)
313 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
316 switch (sslv->state) {
317 case STATE_TCP_CONNECTING:
318 retval = check_connection_completion(sslv->fd);
322 sslv->state = STATE_SSL_CONNECTING;
325 case STATE_SSL_CONNECTING:
326 retval = (sslv->type == CLIENT
327 ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
329 int error = SSL_get_error(sslv->ssl, retval);
330 if (retval < 0 && ssl_wants_io(error)) {
334 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
335 : "SSL_accept"), retval, error, &unused);
336 shutdown(sslv->fd, SHUT_RDWR);
348 ssl_close(struct vconn *vconn)
350 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
351 poll_cancel(sslv->tx_waiter);
358 interpret_ssl_error(const char *function, int ret, int error,
365 VLOG_ERR("%s: unexpected SSL_ERROR_NONE", function);
368 case SSL_ERROR_ZERO_RETURN:
369 VLOG_ERR("%s: unexpected SSL_ERROR_ZERO_RETURN", function);
372 case SSL_ERROR_WANT_READ:
376 case SSL_ERROR_WANT_WRITE:
380 case SSL_ERROR_WANT_CONNECT:
381 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_CONNECT", function);
384 case SSL_ERROR_WANT_ACCEPT:
385 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
388 case SSL_ERROR_WANT_X509_LOOKUP:
389 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_X509_LOOKUP", function);
392 case SSL_ERROR_SYSCALL: {
393 int queued_error = ERR_get_error();
394 if (queued_error == 0) {
397 VLOG_WARN("%s: system error (%s)", function, strerror(status));
400 VLOG_WARN("%s: unexpected SSL connection close", function);
404 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
409 case SSL_ERROR_SSL: {
410 int queued_error = ERR_get_error();
411 if (queued_error != 0) {
412 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
414 VLOG_ERR("%s: SSL_ERROR_SSL without queued error", function);
420 VLOG_ERR("%s: bad SSL error code %d", function, error);
427 ssl_recv(struct vconn *vconn, struct buffer **bufferp)
429 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
435 if (sslv->rxbuf == NULL) {
436 sslv->rxbuf = buffer_new(1564);
441 if (sizeof(struct ofp_header) > rx->size) {
442 want_bytes = sizeof(struct ofp_header) - rx->size;
444 struct ofp_header *oh = rx->data;
445 size_t length = ntohs(oh->length);
446 if (length < sizeof(struct ofp_header)) {
447 VLOG_ERR("received too-short ofp_header (%zu bytes)", length);
450 want_bytes = length - rx->size;
457 buffer_reserve_tailroom(rx, want_bytes);
459 /* Behavior of zero-byte SSL_read is poorly defined. */
460 assert(want_bytes > 0);
462 old_state = SSL_get_state(sslv->ssl);
463 ret = SSL_read(sslv->ssl, buffer_tail(rx), want_bytes);
464 if (old_state != SSL_get_state(sslv->ssl)) {
465 sslv->tx_want = SSL_NOTHING;
466 if (sslv->tx_waiter) {
467 poll_cancel(sslv->tx_waiter);
468 ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
471 sslv->rx_want = SSL_NOTHING;
475 if (ret == want_bytes) {
476 if (rx->size > sizeof(struct ofp_header)) {
486 int error = SSL_get_error(sslv->ssl, ret);
487 if (error == SSL_ERROR_ZERO_RETURN) {
488 /* Connection closed (EOF). */
490 VLOG_WARN("SSL_read: unexpected connection close");
496 return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
502 ssl_clear_txbuf(struct ssl_vconn *sslv)
504 buffer_delete(sslv->txbuf);
506 sslv->tx_waiter = NULL;
510 ssl_register_tx_waiter(struct vconn *vconn)
512 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
513 sslv->tx_waiter = poll_fd_callback(sslv->fd,
514 want_to_poll_events(sslv->tx_want),
515 ssl_tx_poll_callback, vconn);
519 ssl_do_tx(struct vconn *vconn)
521 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
524 int old_state = SSL_get_state(sslv->ssl);
525 int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
526 if (old_state != SSL_get_state(sslv->ssl)) {
527 sslv->rx_want = SSL_NOTHING;
529 sslv->tx_want = SSL_NOTHING;
531 buffer_pull(sslv->txbuf, ret);
532 if (sslv->txbuf->size == 0) {
536 int ssl_error = SSL_get_error(sslv->ssl, ret);
537 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
538 VLOG_WARN("SSL_write: connection closed");
541 return interpret_ssl_error("SSL_write", ret, ssl_error,
549 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
551 struct vconn *vconn = vconn_;
552 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
553 int error = ssl_do_tx(vconn);
554 if (error != EAGAIN) {
555 ssl_clear_txbuf(sslv);
557 ssl_register_tx_waiter(vconn);
562 ssl_send(struct vconn *vconn, struct buffer *buffer)
564 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
571 sslv->txbuf = buffer;
572 error = ssl_do_tx(vconn);
575 ssl_clear_txbuf(sslv);
578 ssl_register_tx_waiter(vconn);
588 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
590 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
594 if (vconn_connect(vconn) != EAGAIN) {
595 poll_immediate_wake();
597 switch (sslv->state) {
598 case STATE_TCP_CONNECTING:
599 poll_fd_wait(sslv->fd, POLLOUT);
602 case STATE_SSL_CONNECTING:
603 /* ssl_connect() called SSL_accept() or SSL_connect(), which
604 * set up the status that we test here. */
605 poll_fd_wait(sslv->fd,
606 want_to_poll_events(SSL_want(sslv->ssl)));
616 if (sslv->rx_want != SSL_NOTHING) {
617 poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
619 poll_immediate_wake();
625 /* We have room in our tx queue. */
626 poll_immediate_wake();
628 /* The call to ssl_tx_poll_callback() will wake us up. */
637 struct vconn_class ssl_vconn_class = {
641 .connect = ssl_connect,
655 static struct pssl_vconn *
656 pssl_vconn_cast(struct vconn *vconn)
658 assert(vconn->class == &pssl_vconn_class);
659 return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
663 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
665 struct sockaddr_in sin;
666 struct pssl_vconn *pssl;
669 unsigned int yes = 1;
677 fd = socket(AF_INET, SOCK_STREAM, 0);
680 VLOG_ERR("%s: socket: %s", name, strerror(error));
684 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
686 VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
690 memset(&sin, 0, sizeof sin);
691 sin.sin_family = AF_INET;
692 sin.sin_addr.s_addr = htonl(INADDR_ANY);
693 sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
694 retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
697 VLOG_ERR("%s: bind: %s", name, strerror(error));
702 retval = listen(fd, 10);
705 VLOG_ERR("%s: listen: %s", name, strerror(error));
710 retval = set_nonblocking(fd);
716 pssl = xmalloc(sizeof *pssl);
717 pssl->vconn.class = &pssl_vconn_class;
718 pssl->vconn.connect_status = 0;
720 *vconnp = &pssl->vconn;
725 pssl_close(struct vconn *vconn)
727 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
733 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
735 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
739 new_fd = accept(pssl->fd, NULL, NULL);
742 if (error != EAGAIN) {
743 VLOG_DBG("accept: %s", strerror(error));
748 error = set_nonblocking(new_fd);
754 return new_ssl_vconn("ssl" /* FIXME */, new_fd,
755 SERVER, STATE_SSL_CONNECTING, new_vconnp);
759 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
761 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
762 assert(wait == WAIT_ACCEPT);
763 poll_fd_wait(pssl->fd, POLLIN);
766 struct vconn_class pssl_vconn_class = {
770 .accept = pssl_accept,
775 * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
776 * OpenSSL is requesting that we call it back when the socket is ready for read
777 * or writing, respectively.
780 ssl_wants_io(int ssl_error)
782 return (ssl_error == SSL_ERROR_WANT_WRITE
783 || ssl_error == SSL_ERROR_WANT_READ);
789 static int init_status = -1;
790 if (init_status < 0) {
791 init_status = do_ssl_init();
792 assert(init_status >= 0);
803 SSL_load_error_strings();
805 method = TLSv1_method();
806 if (method == NULL) {
807 VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
811 ctx = SSL_CTX_new(method);
813 VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
816 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
817 SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
818 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
819 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
820 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
827 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
832 DH *(*constructor)(void);
835 static struct dh dh_table[] = {
836 {1024, NULL, get_dh1024},
837 {2048, NULL, get_dh2048},
838 {4096, NULL, get_dh4096},
843 for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
844 if (dh->keylength == keylength) {
846 dh->dh = dh->constructor();
848 fatal(ENOMEM, "out of memory constructing "
849 "Diffie-Hellman parameters");
855 VLOG_ERR("no Diffie-Hellman parameters for key length %d", keylength);
860 vconn_ssl_set_private_key_file(const char *file_name)
865 if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
866 VLOG_ERR("SSL_use_PrivateKey_file: %s",
867 ERR_error_string(ERR_get_error(), NULL));
870 has_private_key = true;
874 vconn_ssl_set_certificate_file(const char *file_name)
879 if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
880 VLOG_ERR("SSL_use_certificate_file: %s",
881 ERR_error_string(ERR_get_error(), NULL));
884 has_certificate = true;
888 vconn_ssl_set_ca_cert_file(const char *file_name)
890 STACK_OF(X509_NAME) *ca_list;
896 /* Set up list of CAs that the server will accept from the client. */
897 ca_list = SSL_load_client_CA_file(file_name);
898 if (ca_list == NULL) {
899 VLOG_ERR("SSL_load_client_CA_file: %s",
900 ERR_error_string(ERR_get_error(), NULL));
903 SSL_CTX_set_client_CA_list(ctx, ca_list);
905 /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
906 if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
907 VLOG_ERR("SSL_CTX_load_verify_locations: %s",
908 ERR_error_string(ERR_get_error(), NULL));