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)) {
333 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
334 : "SSL_accept"), retval, error, NULL);
335 shutdown(sslv->fd, SHUT_RDWR);
347 ssl_close(struct vconn *vconn)
349 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
350 poll_cancel(sslv->tx_waiter);
357 interpret_ssl_error(const char *function, int ret, int error,
364 VLOG_ERR("%s: unexpected SSL_ERROR_NONE", function);
367 case SSL_ERROR_ZERO_RETURN:
368 VLOG_ERR("%s: unexpected SSL_ERROR_ZERO_RETURN", function);
371 case SSL_ERROR_WANT_READ:
375 case SSL_ERROR_WANT_WRITE:
379 case SSL_ERROR_WANT_CONNECT:
380 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_CONNECT", function);
383 case SSL_ERROR_WANT_ACCEPT:
384 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
387 case SSL_ERROR_WANT_X509_LOOKUP:
388 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_X509_LOOKUP", function);
391 case SSL_ERROR_SYSCALL: {
392 int queued_error = ERR_get_error();
393 if (queued_error == 0) {
396 VLOG_WARN("%s: system error (%s)", function, strerror(status));
399 VLOG_WARN("%s: unexpected SSL connection close", function);
403 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
408 case SSL_ERROR_SSL: {
409 int queued_error = ERR_get_error();
410 if (queued_error != 0) {
411 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
413 VLOG_ERR("%s: SSL_ERROR_SSL without queued error", function);
419 VLOG_ERR("%s: bad SSL error code %d", function, error);
426 ssl_recv(struct vconn *vconn, struct buffer **bufferp)
428 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
434 if (sslv->rxbuf == NULL) {
435 sslv->rxbuf = buffer_new(1564);
440 if (sizeof(struct ofp_header) > rx->size) {
441 want_bytes = sizeof(struct ofp_header) - rx->size;
443 struct ofp_header *oh = rx->data;
444 size_t length = ntohs(oh->length);
445 if (length < sizeof(struct ofp_header)) {
446 VLOG_ERR("received too-short ofp_header (%zu bytes)", length);
449 want_bytes = length - rx->size;
456 buffer_reserve_tailroom(rx, want_bytes);
458 /* Behavior of zero-byte SSL_read is poorly defined. */
459 assert(want_bytes > 0);
461 old_state = SSL_get_state(sslv->ssl);
462 ret = SSL_read(sslv->ssl, buffer_tail(rx), want_bytes);
463 if (old_state != SSL_get_state(sslv->ssl)) {
464 sslv->tx_want = SSL_NOTHING;
465 if (sslv->tx_waiter) {
466 poll_cancel(sslv->tx_waiter);
467 ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
470 sslv->rx_want = SSL_NOTHING;
474 if (ret == want_bytes) {
475 if (rx->size > sizeof(struct ofp_header)) {
485 int error = SSL_get_error(sslv->ssl, ret);
486 if (error == SSL_ERROR_ZERO_RETURN) {
487 /* Connection closed (EOF). */
489 VLOG_WARN("SSL_read: unexpected connection close");
495 return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
501 ssl_clear_txbuf(struct ssl_vconn *sslv)
503 buffer_delete(sslv->txbuf);
505 sslv->tx_waiter = NULL;
509 ssl_register_tx_waiter(struct vconn *vconn)
511 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
512 sslv->tx_waiter = poll_fd_callback(sslv->fd,
513 want_to_poll_events(sslv->tx_want),
514 ssl_tx_poll_callback, vconn);
518 ssl_do_tx(struct vconn *vconn)
520 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
523 int old_state = SSL_get_state(sslv->ssl);
524 int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
525 if (old_state != SSL_get_state(sslv->ssl)) {
526 sslv->rx_want = SSL_NOTHING;
528 sslv->tx_want = SSL_NOTHING;
530 buffer_pull(sslv->txbuf, ret);
531 if (sslv->txbuf->size == 0) {
535 int ssl_error = SSL_get_error(sslv->ssl, ret);
536 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
537 VLOG_WARN("SSL_write: connection closed");
540 return interpret_ssl_error("SSL_write", ret, ssl_error,
548 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
550 struct vconn *vconn = vconn_;
551 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
552 int error = ssl_do_tx(vconn);
553 if (error != EAGAIN) {
554 ssl_clear_txbuf(sslv);
556 ssl_register_tx_waiter(vconn);
561 ssl_send(struct vconn *vconn, struct buffer *buffer)
563 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
570 sslv->txbuf = buffer;
571 error = ssl_do_tx(vconn);
574 ssl_clear_txbuf(sslv);
577 ssl_register_tx_waiter(vconn);
587 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
589 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
593 if (vconn_connect(vconn) != EAGAIN) {
594 poll_immediate_wake();
596 switch (sslv->state) {
597 case STATE_TCP_CONNECTING:
598 poll_fd_wait(sslv->fd, POLLOUT);
601 case STATE_SSL_CONNECTING:
602 /* ssl_connect() called SSL_accept() or SSL_connect(), which
603 * set up the status that we test here. */
604 poll_fd_wait(sslv->fd,
605 want_to_poll_events(SSL_want(sslv->ssl)));
615 if (sslv->rx_want != SSL_NOTHING) {
616 poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
618 poll_immediate_wake();
624 /* We have room in our tx queue. */
625 poll_immediate_wake();
627 /* The call to ssl_tx_poll_callback() will wake us up. */
636 struct vconn_class ssl_vconn_class = {
640 .connect = ssl_connect,
654 static struct pssl_vconn *
655 pssl_vconn_cast(struct vconn *vconn)
657 assert(vconn->class == &pssl_vconn_class);
658 return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
662 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
664 struct sockaddr_in sin;
665 struct pssl_vconn *pssl;
668 unsigned int yes = 1;
676 fd = socket(AF_INET, SOCK_STREAM, 0);
679 VLOG_ERR("%s: socket: %s", name, strerror(error));
683 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
685 VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
689 memset(&sin, 0, sizeof sin);
690 sin.sin_family = AF_INET;
691 sin.sin_addr.s_addr = htonl(INADDR_ANY);
692 sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
693 retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
696 VLOG_ERR("%s: bind: %s", name, strerror(error));
701 retval = listen(fd, 10);
704 VLOG_ERR("%s: listen: %s", name, strerror(error));
709 retval = set_nonblocking(fd);
715 pssl = xmalloc(sizeof *pssl);
716 pssl->vconn.class = &pssl_vconn_class;
717 pssl->vconn.connect_status = 0;
719 *vconnp = &pssl->vconn;
724 pssl_close(struct vconn *vconn)
726 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
732 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
734 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
738 new_fd = accept(pssl->fd, NULL, NULL);
741 if (error != EAGAIN) {
742 VLOG_DBG("accept: %s", strerror(error));
747 error = set_nonblocking(new_fd);
753 return new_ssl_vconn("ssl" /* FIXME */, new_fd,
754 SERVER, STATE_SSL_CONNECTING, new_vconnp);
758 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
760 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
761 assert(wait == WAIT_ACCEPT);
762 poll_fd_wait(pssl->fd, POLLIN);
765 struct vconn_class pssl_vconn_class = {
769 .accept = pssl_accept,
774 * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
775 * OpenSSL is requesting that we call it back when the socket is ready for read
776 * or writing, respectively.
779 ssl_wants_io(int ssl_error)
781 return (ssl_error == SSL_ERROR_WANT_WRITE
782 || ssl_error == SSL_ERROR_WANT_READ);
788 static int init_status = -1;
789 if (init_status < 0) {
790 init_status = do_ssl_init();
791 assert(init_status >= 0);
802 SSL_load_error_strings();
804 method = TLSv1_method();
805 if (method == NULL) {
806 VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
810 ctx = SSL_CTX_new(method);
812 VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
815 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
816 SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
817 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
818 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
819 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
826 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
831 DH *(*constructor)(void);
834 static struct dh dh_table[] = {
835 {1024, NULL, get_dh1024},
836 {2048, NULL, get_dh2048},
837 {4096, NULL, get_dh4096},
842 for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
843 if (dh->keylength == keylength) {
845 dh->dh = dh->constructor();
847 fatal(ENOMEM, "out of memory constructing "
848 "Diffie-Hellman parameters");
854 VLOG_ERR("no Diffie-Hellman parameters for key length %d", keylength);
859 vconn_ssl_set_private_key_file(const char *file_name)
864 if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
865 VLOG_ERR("SSL_use_PrivateKey_file: %s",
866 ERR_error_string(ERR_get_error(), NULL));
869 has_private_key = true;
873 vconn_ssl_set_certificate_file(const char *file_name)
878 if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
879 VLOG_ERR("SSL_use_certificate_file: %s",
880 ERR_error_string(ERR_get_error(), NULL));
883 has_certificate = true;
887 vconn_ssl_set_ca_cert_file(const char *file_name)
889 STACK_OF(X509_NAME) *ca_list;
895 /* Set up list of CAs that the server will accept from the client. */
896 ca_list = SSL_load_client_CA_file(file_name);
897 if (ca_list == NULL) {
898 VLOG_ERR("SSL_load_client_CA_file: %s",
899 ERR_error_string(ERR_get_error(), NULL));
902 SSL_CTX_set_client_CA_list(ctx, ca_list);
904 /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
905 if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
906 VLOG_ERR("SSL_CTX_load_verify_locations: %s",
907 ERR_error_string(ERR_get_error(), NULL));