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"
40 #include <netinet/tcp.h>
41 #include <openssl/err.h>
42 #include <openssl/ssl.h>
46 #include "socket-util.h"
50 #include "poll-loop.h"
51 #include "ofp-print.h"
52 #include "socket-util.h"
56 #define THIS_MODULE VLM_vconn_ssl
75 enum session_type type;
80 struct poll_waiter *tx_waiter;
82 /* rx_want and tx_want record the result of the last call to SSL_read()
83 * and SSL_write(), respectively:
85 * - If the call reported that data needed to be read from the file
86 * descriptor, the corresponding member is set to SSL_READING.
88 * - If the call reported that data needed to be written to the file
89 * descriptor, the corresponding member is set to SSL_WRITING.
91 * - Otherwise, the member is set to SSL_NOTHING, indicating that the
92 * call completed successfully (or with an error) and that there is no
95 * These are needed because there is no way to ask OpenSSL what a data read
96 * or write would require without giving it a buffer to receive into or
97 * data to send, respectively. (Note that the SSL_want() status is
98 * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
101 * A single call to SSL_read() or SSL_write() can perform both reading
102 * and writing and thus invalidate not one of these values but actually
103 * both. Consider this situation, for example:
105 * - SSL_write() blocks on a read, so tx_want gets SSL_READING.
107 * - SSL_read() laters succeeds reading from 'fd' and clears out the
108 * whole receive buffer, so rx_want gets SSL_READING.
110 * - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
113 * - Now we're stuck blocking until the peer sends us data, even though
114 * SSL_write() could now succeed, which could easily be a deadlock
117 * On the other hand, we can't reset both tx_want and rx_want on every call
118 * to SSL_read() or SSL_write(), because that would produce livelock,
119 * e.g. in this situation:
121 * - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
123 * - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
124 * but tx_want gets reset to SSL_NOTHING.
126 * - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
129 * - Client wakes up immediately since SSL_NOTHING in tx_want indicates
130 * that no blocking is necessary.
132 * The solution we adopt here is to set tx_want to SSL_NOTHING after
133 * calling SSL_read() only if the SSL state of the connection changed,
134 * which indicates that an SSL-level renegotiation made some progress, and
135 * similarly for rx_want and SSL_write(). This prevents both the
136 * deadlock and livelock situations above.
138 int rx_want, tx_want;
141 /* SSL context created by ssl_init(). */
144 /* Required configuration. */
145 static bool has_private_key, has_certificate, has_ca_cert;
147 static int ssl_init(void);
148 static int do_ssl_init(void);
149 static bool ssl_wants_io(int ssl_error);
150 static void ssl_close(struct vconn *);
151 static int interpret_ssl_error(const char *function, int ret, int error,
153 static void ssl_tx_poll_callback(int fd, short int revents, void *vconn_);
154 static DH *tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength);
157 want_to_poll_events(int want)
175 new_ssl_vconn(const char *name, int fd, enum session_type type,
176 enum ssl_state state, const struct sockaddr_in *sin,
177 struct vconn **vconnp)
179 struct ssl_vconn *sslv;
184 /* Check for all the needful configuration. */
185 if (!has_private_key) {
186 VLOG_ERR("Private key must be configured to use SSL");
189 if (!has_certificate) {
190 VLOG_ERR("Certificate must be configured to use SSL");
194 VLOG_ERR("CA certificate must be configured to use SSL");
197 if (!SSL_CTX_check_private_key(ctx)) {
198 VLOG_ERR("Private key does not match certificate public key");
203 retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
205 VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
210 /* Create and configure OpenSSL stream. */
213 VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
217 if (SSL_set_fd(ssl, fd) == 0) {
218 VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
222 /* Create and return the ssl_vconn. */
223 sslv = xmalloc(sizeof *sslv);
224 sslv->vconn.class = &ssl_vconn_class;
225 sslv->vconn.connect_status = EAGAIN;
226 sslv->vconn.ip = sin->sin_addr.s_addr;
233 sslv->tx_waiter = NULL;
234 sslv->rx_want = sslv->tx_want = SSL_NOTHING;
235 *vconnp = &sslv->vconn;
246 static struct ssl_vconn *
247 ssl_vconn_cast(struct vconn *vconn)
249 assert(vconn->class == &ssl_vconn_class);
250 return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
254 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
256 char *save_ptr, *host_name, *port_string;
257 struct sockaddr_in sin;
266 /* Glibc 2.7 has a bug in strtok_r when compiling with optimization that
267 * can cause segfaults here:
268 * http://sources.redhat.com/bugzilla/show_bug.cgi?id=5614.
269 * Using "::" instead of the obvious ":" works around it. */
270 host_name = strtok_r(suffix, "::", &save_ptr);
271 port_string = strtok_r(NULL, "::", &save_ptr);
273 fatal(0, "%s: bad peer name format", name);
276 memset(&sin, 0, sizeof sin);
277 sin.sin_family = AF_INET;
278 if (lookup_ip(host_name, &sin.sin_addr)) {
281 sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
285 fd = socket(AF_INET, SOCK_STREAM, 0);
287 VLOG_ERR("%s: socket: %s", name, strerror(errno));
290 retval = set_nonblocking(fd);
296 /* Connect socket. */
297 retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
299 if (errno == EINPROGRESS) {
300 return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
304 VLOG_ERR("%s: connect: %s", name, strerror(error));
309 return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
315 ssl_connect(struct vconn *vconn)
317 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
320 switch (sslv->state) {
321 case STATE_TCP_CONNECTING:
322 retval = check_connection_completion(sslv->fd);
326 sslv->state = STATE_SSL_CONNECTING;
329 case STATE_SSL_CONNECTING:
330 retval = (sslv->type == CLIENT
331 ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
333 int error = SSL_get_error(sslv->ssl, retval);
334 if (retval < 0 && ssl_wants_io(error)) {
338 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
339 : "SSL_accept"), retval, error, &unused);
340 shutdown(sslv->fd, SHUT_RDWR);
352 ssl_close(struct vconn *vconn)
354 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
355 poll_cancel(sslv->tx_waiter);
362 interpret_ssl_error(const char *function, int ret, int error,
369 VLOG_ERR("%s: unexpected SSL_ERROR_NONE", function);
372 case SSL_ERROR_ZERO_RETURN:
373 VLOG_ERR("%s: unexpected SSL_ERROR_ZERO_RETURN", function);
376 case SSL_ERROR_WANT_READ:
380 case SSL_ERROR_WANT_WRITE:
384 case SSL_ERROR_WANT_CONNECT:
385 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_CONNECT", function);
388 case SSL_ERROR_WANT_ACCEPT:
389 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
392 case SSL_ERROR_WANT_X509_LOOKUP:
393 VLOG_ERR("%s: unexpected SSL_ERROR_WANT_X509_LOOKUP", function);
396 case SSL_ERROR_SYSCALL: {
397 int queued_error = ERR_get_error();
398 if (queued_error == 0) {
401 VLOG_WARN("%s: system error (%s)", function, strerror(status));
404 VLOG_WARN("%s: unexpected SSL connection close", function);
408 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
413 case SSL_ERROR_SSL: {
414 int queued_error = ERR_get_error();
415 if (queued_error != 0) {
416 VLOG_DBG("%s: %s", function, ERR_error_string(queued_error, NULL));
418 VLOG_ERR("%s: SSL_ERROR_SSL without queued error", function);
424 VLOG_ERR("%s: bad SSL error code %d", function, error);
431 ssl_recv(struct vconn *vconn, struct buffer **bufferp)
433 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
439 if (sslv->rxbuf == NULL) {
440 sslv->rxbuf = buffer_new(1564);
445 if (sizeof(struct ofp_header) > rx->size) {
446 want_bytes = sizeof(struct ofp_header) - rx->size;
448 struct ofp_header *oh = rx->data;
449 size_t length = ntohs(oh->length);
450 if (length < sizeof(struct ofp_header)) {
451 VLOG_ERR("received too-short ofp_header (%zu bytes)", length);
454 want_bytes = length - rx->size;
461 buffer_reserve_tailroom(rx, want_bytes);
463 /* Behavior of zero-byte SSL_read is poorly defined. */
464 assert(want_bytes > 0);
466 old_state = SSL_get_state(sslv->ssl);
467 ret = SSL_read(sslv->ssl, buffer_tail(rx), want_bytes);
468 if (old_state != SSL_get_state(sslv->ssl)) {
469 sslv->tx_want = SSL_NOTHING;
470 if (sslv->tx_waiter) {
471 poll_cancel(sslv->tx_waiter);
472 ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
475 sslv->rx_want = SSL_NOTHING;
479 if (ret == want_bytes) {
480 if (rx->size > sizeof(struct ofp_header)) {
490 int error = SSL_get_error(sslv->ssl, ret);
491 if (error == SSL_ERROR_ZERO_RETURN) {
492 /* Connection closed (EOF). */
494 VLOG_WARN("SSL_read: unexpected connection close");
500 return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
506 ssl_clear_txbuf(struct ssl_vconn *sslv)
508 buffer_delete(sslv->txbuf);
510 sslv->tx_waiter = NULL;
514 ssl_register_tx_waiter(struct vconn *vconn)
516 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
517 sslv->tx_waiter = poll_fd_callback(sslv->fd,
518 want_to_poll_events(sslv->tx_want),
519 ssl_tx_poll_callback, vconn);
523 ssl_do_tx(struct vconn *vconn)
525 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
528 int old_state = SSL_get_state(sslv->ssl);
529 int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
530 if (old_state != SSL_get_state(sslv->ssl)) {
531 sslv->rx_want = SSL_NOTHING;
533 sslv->tx_want = SSL_NOTHING;
535 buffer_pull(sslv->txbuf, ret);
536 if (sslv->txbuf->size == 0) {
540 int ssl_error = SSL_get_error(sslv->ssl, ret);
541 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
542 VLOG_WARN("SSL_write: connection closed");
545 return interpret_ssl_error("SSL_write", ret, ssl_error,
553 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
555 struct vconn *vconn = vconn_;
556 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
557 int error = ssl_do_tx(vconn);
558 if (error != EAGAIN) {
559 ssl_clear_txbuf(sslv);
561 ssl_register_tx_waiter(vconn);
566 ssl_send(struct vconn *vconn, struct buffer *buffer)
568 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
575 sslv->txbuf = buffer;
576 error = ssl_do_tx(vconn);
579 ssl_clear_txbuf(sslv);
582 ssl_register_tx_waiter(vconn);
592 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
594 struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
598 if (vconn_connect(vconn) != EAGAIN) {
599 poll_immediate_wake();
601 switch (sslv->state) {
602 case STATE_TCP_CONNECTING:
603 poll_fd_wait(sslv->fd, POLLOUT);
606 case STATE_SSL_CONNECTING:
607 /* ssl_connect() called SSL_accept() or SSL_connect(), which
608 * set up the status that we test here. */
609 poll_fd_wait(sslv->fd,
610 want_to_poll_events(SSL_want(sslv->ssl)));
620 if (sslv->rx_want != SSL_NOTHING) {
621 poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
623 poll_immediate_wake();
629 /* We have room in our tx queue. */
630 poll_immediate_wake();
632 /* The call to ssl_tx_poll_callback() will wake us up. */
641 struct vconn_class ssl_vconn_class = {
645 .connect = ssl_connect,
659 static struct pssl_vconn *
660 pssl_vconn_cast(struct vconn *vconn)
662 assert(vconn->class == &pssl_vconn_class);
663 return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
667 pssl_open(const char *name, char *suffix, struct vconn **vconnp)
669 struct sockaddr_in sin;
670 struct pssl_vconn *pssl;
673 unsigned int yes = 1;
681 fd = socket(AF_INET, SOCK_STREAM, 0);
684 VLOG_ERR("%s: socket: %s", name, strerror(error));
688 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
690 VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
694 memset(&sin, 0, sizeof sin);
695 sin.sin_family = AF_INET;
696 sin.sin_addr.s_addr = htonl(INADDR_ANY);
697 sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
698 retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
701 VLOG_ERR("%s: bind: %s", name, strerror(error));
706 retval = listen(fd, 10);
709 VLOG_ERR("%s: listen: %s", name, strerror(error));
714 retval = set_nonblocking(fd);
720 pssl = xmalloc(sizeof *pssl);
721 pssl->vconn.class = &pssl_vconn_class;
722 pssl->vconn.connect_status = 0;
724 *vconnp = &pssl->vconn;
729 pssl_close(struct vconn *vconn)
731 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
737 pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
739 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
740 struct sockaddr_in sin;
741 socklen_t sin_len = sizeof sin;
746 new_fd = accept(pssl->fd, &sin, &sin_len);
749 if (error != EAGAIN) {
750 VLOG_DBG("accept: %s", strerror(error));
755 error = set_nonblocking(new_fd);
761 sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
762 if (sin.sin_port != htons(OFP_SSL_PORT)) {
763 sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
765 return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
770 pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
772 struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
773 assert(wait == WAIT_ACCEPT);
774 poll_fd_wait(pssl->fd, POLLIN);
777 struct vconn_class pssl_vconn_class = {
781 .accept = pssl_accept,
786 * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
787 * OpenSSL is requesting that we call it back when the socket is ready for read
788 * or writing, respectively.
791 ssl_wants_io(int ssl_error)
793 return (ssl_error == SSL_ERROR_WANT_WRITE
794 || ssl_error == SSL_ERROR_WANT_READ);
800 static int init_status = -1;
801 if (init_status < 0) {
802 init_status = do_ssl_init();
803 assert(init_status >= 0);
814 SSL_load_error_strings();
816 method = TLSv1_method();
817 if (method == NULL) {
818 VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
822 ctx = SSL_CTX_new(method);
824 VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
827 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
828 SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
829 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
830 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
831 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
838 tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength)
843 DH *(*constructor)(void);
846 static struct dh dh_table[] = {
847 {1024, NULL, get_dh1024},
848 {2048, NULL, get_dh2048},
849 {4096, NULL, get_dh4096},
854 for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
855 if (dh->keylength == keylength) {
857 dh->dh = dh->constructor();
859 fatal(ENOMEM, "out of memory constructing "
860 "Diffie-Hellman parameters");
866 VLOG_ERR("no Diffie-Hellman parameters for key length %d", keylength);
871 vconn_ssl_set_private_key_file(const char *file_name)
876 if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
877 VLOG_ERR("SSL_use_PrivateKey_file: %s",
878 ERR_error_string(ERR_get_error(), NULL));
881 has_private_key = true;
885 vconn_ssl_set_certificate_file(const char *file_name)
890 if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
891 VLOG_ERR("SSL_use_certificate_file: %s",
892 ERR_error_string(ERR_get_error(), NULL));
895 has_certificate = true;
899 vconn_ssl_set_ca_cert_file(const char *file_name)
901 STACK_OF(X509_NAME) *ca_list;
907 /* Set up list of CAs that the server will accept from the client. */
908 ca_list = SSL_load_client_CA_file(file_name);
909 if (ca_list == NULL) {
910 VLOG_ERR("SSL_load_client_CA_file: %s",
911 ERR_error_string(ERR_get_error(), NULL));
914 SSL_CTX_set_client_CA_list(ctx, ca_list);
916 /* Set up CAs for OpenSSL to trust in verifying the peer's certificate. */
917 if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
918 VLOG_ERR("SSL_CTX_load_verify_locations: %s",
919 ERR_error_string(ERR_get_error(), NULL));