2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "stream-ssl.h"
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/ssl.h>
28 #include <openssl/x509v3.h>
30 #include <sys/fcntl.h>
34 #include "dynamic-string.h"
35 #include "leak-checker.h"
37 #include "openflow/openflow.h"
39 #include "poll-loop.h"
41 #include "socket-util.h"
43 #include "stream-provider.h"
48 VLOG_DEFINE_THIS_MODULE(stream_ssl)
66 enum session_type type;
70 unsigned int session_nr;
72 /* rx_want and tx_want record the result of the last call to SSL_read()
73 * and SSL_write(), respectively:
75 * - If the call reported that data needed to be read from the file
76 * descriptor, the corresponding member is set to SSL_READING.
78 * - If the call reported that data needed to be written to the file
79 * descriptor, the corresponding member is set to SSL_WRITING.
81 * - Otherwise, the member is set to SSL_NOTHING, indicating that the
82 * call completed successfully (or with an error) and that there is no
85 * These are needed because there is no way to ask OpenSSL what a data read
86 * or write would require without giving it a buffer to receive into or
87 * data to send, respectively. (Note that the SSL_want() status is
88 * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
91 * A single call to SSL_read() or SSL_write() can perform both reading
92 * and writing and thus invalidate not one of these values but actually
93 * both. Consider this situation, for example:
95 * - SSL_write() blocks on a read, so tx_want gets SSL_READING.
97 * - SSL_read() laters succeeds reading from 'fd' and clears out the
98 * whole receive buffer, so rx_want gets SSL_READING.
100 * - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
103 * - Now we're stuck blocking until the peer sends us data, even though
104 * SSL_write() could now succeed, which could easily be a deadlock
107 * On the other hand, we can't reset both tx_want and rx_want on every call
108 * to SSL_read() or SSL_write(), because that would produce livelock,
109 * e.g. in this situation:
111 * - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
113 * - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
114 * but tx_want gets reset to SSL_NOTHING.
116 * - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
119 * - Client wakes up immediately since SSL_NOTHING in tx_want indicates
120 * that no blocking is necessary.
122 * The solution we adopt here is to set tx_want to SSL_NOTHING after
123 * calling SSL_read() only if the SSL state of the connection changed,
124 * which indicates that an SSL-level renegotiation made some progress, and
125 * similarly for rx_want and SSL_write(). This prevents both the
126 * deadlock and livelock situations above.
128 int rx_want, tx_want;
130 /* A few bytes of header data in case SSL negotiation fails. */
135 /* SSL context created by ssl_init(). */
138 /* Maps from stream target (e.g. "127.0.0.1:1234") to SSL_SESSION *. The
139 * sessions are those from the last SSL connection to the given target.
140 * OpenSSL caches server-side sessions internally, so this cache is only used
141 * for client connections.
143 * The stream_ssl module owns a reference to each of the sessions in this
144 * table, so they must be freed with SSL_SESSION_free() when they are no
146 static struct shash client_sessions = SHASH_INITIALIZER(&client_sessions);
148 /* Maximum number of client sessions to cache. Ordinarily I'd expect that one
149 * session would be sufficient but this should cover it. */
150 #define MAX_CLIENT_SESSION_CACHE 16
152 struct ssl_config_file {
153 bool read; /* Whether the file was successfully read. */
154 char *file_name; /* Configured file name, if any. */
155 struct timespec mtime; /* File mtime as of last time we read it. */
158 /* SSL configuration files. */
159 static struct ssl_config_file private_key;
160 static struct ssl_config_file certificate;
161 static struct ssl_config_file ca_cert;
163 /* Ordinarily, the SSL client and server verify each other's certificates using
164 * a CA certificate. Setting this to false disables this behavior. (This is a
166 static bool verify_peer_cert = true;
168 /* Ordinarily, we require a CA certificate for the peer to be locally
169 * available. We can, however, bootstrap the CA certificate from the peer at
170 * the beginning of our first connection then use that certificate on all
171 * subsequent connections, saving it to a file for use in future runs also. In
172 * this case, 'bootstrap_ca_cert' is true. */
173 static bool bootstrap_ca_cert;
175 /* Session number. Used in debug logging messages to uniquely identify a
177 static unsigned int next_session_nr;
179 /* Who knows what can trigger various SSL errors, so let's throttle them down
181 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
183 static int ssl_init(void);
184 static int do_ssl_init(void);
185 static bool ssl_wants_io(int ssl_error);
186 static void ssl_close(struct stream *);
187 static void ssl_clear_txbuf(struct ssl_stream *);
188 static int interpret_ssl_error(const char *function, int ret, int error,
190 static DH *tmp_dh_callback(SSL *ssl, int is_export OVS_UNUSED, int keylength);
191 static void log_ca_cert(const char *file_name, X509 *cert);
192 static void stream_ssl_set_ca_cert_file__(const char *file_name,
194 static void ssl_protocol_cb(int write_p, int version, int content_type,
195 const void *, size_t, SSL *, void *sslv_);
198 want_to_poll_events(int want)
216 new_ssl_stream(const char *name, int fd, enum session_type type,
217 enum ssl_state state, const struct sockaddr_in *remote,
218 struct stream **streamp)
220 struct sockaddr_in local;
221 socklen_t local_len = sizeof local;
222 struct ssl_stream *sslv;
227 /* Check for all the needful configuration. */
229 if (!private_key.read) {
230 VLOG_ERR("Private key must be configured to use SSL");
231 retval = ENOPROTOOPT;
233 if (!certificate.read) {
234 VLOG_ERR("Certificate must be configured to use SSL");
235 retval = ENOPROTOOPT;
237 if (!ca_cert.read && verify_peer_cert && !bootstrap_ca_cert) {
238 VLOG_ERR("CA certificate must be configured to use SSL");
239 retval = ENOPROTOOPT;
241 if (!SSL_CTX_check_private_key(ctx)) {
242 VLOG_ERR("Private key does not match certificate public key: %s",
243 ERR_error_string(ERR_get_error(), NULL));
244 retval = ENOPROTOOPT;
250 /* Get the local IP and port information */
251 retval = getsockname(fd, (struct sockaddr *) &local, &local_len);
253 memset(&local, 0, sizeof local);
257 retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
259 VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
264 /* Create and configure OpenSSL stream. */
267 VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
268 retval = ENOPROTOOPT;
271 if (SSL_set_fd(ssl, fd) == 0) {
272 VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
273 retval = ENOPROTOOPT;
276 if (!verify_peer_cert || (bootstrap_ca_cert && type == CLIENT)) {
277 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
280 /* Create and return the ssl_stream. */
281 sslv = xmalloc(sizeof *sslv);
282 stream_init(&sslv->stream, &ssl_stream_class, EAGAIN, name);
283 stream_set_remote_ip(&sslv->stream, remote->sin_addr.s_addr);
284 stream_set_remote_port(&sslv->stream, remote->sin_port);
285 stream_set_local_ip(&sslv->stream, local.sin_addr.s_addr);
286 stream_set_local_port(&sslv->stream, local.sin_port);
292 sslv->rx_want = sslv->tx_want = SSL_NOTHING;
293 sslv->session_nr = next_session_nr++;
296 if (VLOG_IS_DBG_ENABLED()) {
297 SSL_set_msg_callback(ssl, ssl_protocol_cb);
298 SSL_set_msg_callback_arg(ssl, sslv);
301 *streamp = &sslv->stream;
312 static struct ssl_stream *
313 ssl_stream_cast(struct stream *stream)
315 stream_assert_class(stream, &ssl_stream_class);
316 return CONTAINER_OF(stream, struct ssl_stream, stream);
320 ssl_open(const char *name, char *suffix, struct stream **streamp)
322 struct sockaddr_in sin;
330 error = inet_open_active(SOCK_STREAM, suffix, OFP_SSL_PORT, &sin, &fd);
332 int state = error ? STATE_TCP_CONNECTING : STATE_SSL_CONNECTING;
333 return new_ssl_stream(name, fd, CLIENT, state, &sin, streamp);
335 VLOG_ERR("%s: connect: %s", name, strerror(error));
341 do_ca_cert_bootstrap(struct stream *stream)
343 struct ssl_stream *sslv = ssl_stream_cast(stream);
344 STACK_OF(X509) *chain;
350 chain = SSL_get_peer_cert_chain(sslv->ssl);
351 if (!chain || !sk_X509_num(chain)) {
352 VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
356 cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
358 /* Check that 'cert' is self-signed. Otherwise it is not a CA
359 * certificate and we should not attempt to use it as one. */
360 error = X509_check_issued(cert, cert);
362 VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
363 "not self-signed (%s)",
364 X509_verify_cert_error_string(error));
365 if (sk_X509_num(chain) < 2) {
366 VLOG_ERR("only one certificate was received, so probably the peer "
367 "is not configured to send its CA certificate");
372 fd = open(ca_cert.file_name, O_CREAT | O_EXCL | O_WRONLY, 0444);
374 if (errno == EEXIST) {
375 VLOG_INFO("reading CA cert %s created by another process",
377 stream_ssl_set_ca_cert_file(ca_cert.file_name, true);
380 VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
381 ca_cert.file_name, strerror(errno));
386 file = fdopen(fd, "w");
389 VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
391 unlink(ca_cert.file_name);
395 if (!PEM_write_X509(file, cert)) {
396 VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
397 "%s", ca_cert.file_name,
398 ERR_error_string(ERR_get_error(), NULL));
400 unlink(ca_cert.file_name);
406 VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
407 ca_cert.file_name, strerror(error));
408 unlink(ca_cert.file_name);
412 VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert.file_name);
413 log_ca_cert(ca_cert.file_name, cert);
414 bootstrap_ca_cert = false;
417 /* SSL_CTX_add_client_CA makes a copy of cert's relevant data. */
418 SSL_CTX_add_client_CA(ctx, cert);
420 /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
421 * 'cert' is owned by sslv->ssl, so we need to duplicate it. */
422 cert = X509_dup(cert);
426 if (SSL_CTX_load_verify_locations(ctx, ca_cert.file_name, NULL) != 1) {
427 VLOG_ERR("SSL_CTX_load_verify_locations: %s",
428 ERR_error_string(ERR_get_error(), NULL));
431 VLOG_INFO("killing successful connection to retry using CA cert");
436 ssl_delete_session(struct shash_node *node)
438 SSL_SESSION *session = node->data;
439 SSL_SESSION_free(session);
440 shash_delete(&client_sessions, node);
443 /* Find and free any previously cached session for 'stream''s target. */
445 ssl_flush_session(struct stream *stream)
447 struct shash_node *node;
449 node = shash_find(&client_sessions, stream_get_name(stream));
451 ssl_delete_session(node);
455 /* Add 'stream''s session to the cache for its target, so that it will be
456 * reused for future SSL connections to the same target. */
458 ssl_cache_session(struct stream *stream)
460 struct ssl_stream *sslv = ssl_stream_cast(stream);
461 SSL_SESSION *session;
464 COVERAGE_INC(ssl_session);
465 if (SSL_session_reused(sslv->ssl)) {
466 COVERAGE_INC(ssl_session_reused);
469 /* Get session from stream. */
470 session = SSL_get1_session(sslv->ssl);
472 SSL_SESSION *old_session;
474 old_session = shash_replace(&client_sessions, stream_get_name(stream),
477 /* Free the session that we replaced. (We might actually have
478 * session == old_session, but either way we have to free it to
479 * avoid leaking a reference.) */
480 SSL_SESSION_free(old_session);
481 } else if (shash_count(&client_sessions) > MAX_CLIENT_SESSION_CACHE) {
483 struct shash_node *node = shash_random_node(&client_sessions);
484 if (node->data != session) {
485 ssl_delete_session(node);
491 /* There is no new session. This doesn't really make sense because
492 * this function is only called upon successful connection and there
493 * should always be a new session in that case. But I don't trust
494 * OpenSSL so I'd rather handle this case anyway. */
495 ssl_flush_session(stream);
500 ssl_connect(struct stream *stream)
502 struct ssl_stream *sslv = ssl_stream_cast(stream);
505 switch (sslv->state) {
506 case STATE_TCP_CONNECTING:
507 retval = check_connection_completion(sslv->fd);
511 sslv->state = STATE_SSL_CONNECTING;
514 case STATE_SSL_CONNECTING:
515 /* Capture the first few bytes of received data so that we can guess
516 * what kind of funny data we've been sent if SSL negotation fails. */
517 if (sslv->n_head <= 0) {
518 sslv->n_head = recv(sslv->fd, sslv->head, sizeof sslv->head,
522 /* Grab SSL session information from the cache. */
523 if (sslv->type == CLIENT) {
524 SSL_SESSION *session = shash_find_data(&client_sessions,
525 stream_get_name(stream));
527 SSL_set_session(sslv->ssl, session);
531 retval = (sslv->type == CLIENT
532 ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
534 int error = SSL_get_error(sslv->ssl, retval);
535 if (retval < 0 && ssl_wants_io(error)) {
540 if (sslv->type == CLIENT) {
541 /* Delete any cached session for this stream's target.
542 * Otherwise a single error causes recurring errors that
543 * don't resolve until the SSL client or server is
544 * restarted. (It can take dozens of reused connections to
545 * see this behavior, so this is difficult to test.) If we
546 * delete the session on the first error, though, the error
547 * only occurs once and then resolves itself. */
548 ssl_flush_session(stream);
551 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
552 : "SSL_accept"), retval, error, &unused);
553 shutdown(sslv->fd, SHUT_RDWR);
554 stream_report_content(sslv->head, sslv->n_head, STREAM_SSL,
555 THIS_MODULE, stream_get_name(stream));
558 } else if (bootstrap_ca_cert) {
559 return do_ca_cert_bootstrap(stream);
560 } else if (verify_peer_cert
561 && ((SSL_get_verify_mode(sslv->ssl)
562 & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
563 != SSL_VERIFY_PEER)) {
564 /* Two or more SSL connections completed at the same time while we
565 * were in bootstrap mode. Only one of these can finish the
566 * bootstrap successfully. The other one(s) must be rejected
567 * because they were not verified against the bootstrapped CA
568 * certificate. (Alternatively we could verify them against the CA
569 * certificate, but that's more trouble than it's worth. These
570 * connections will succeed the next time they retry, assuming that
571 * they have a certificate against the correct CA.) */
572 VLOG_ERR("rejecting SSL connection during bootstrap race window");
575 if (sslv->type == CLIENT) {
576 ssl_cache_session(stream);
586 ssl_close(struct stream *stream)
588 struct ssl_stream *sslv = ssl_stream_cast(stream);
589 ssl_clear_txbuf(sslv);
591 /* Attempt clean shutdown of the SSL connection. This will work most of
592 * the time, as long as the kernel send buffer has some free space and the
593 * SSL connection isn't renegotiating, etc. That has to be good enough,
594 * since we don't have any way to continue the close operation in the
596 SSL_shutdown(sslv->ssl);
598 /* SSL_shutdown() might have signaled an error, in which case we need to
599 * flush it out of the OpenSSL error queue or the next OpenSSL operation
600 * will falsely signal an error. */
609 interpret_ssl_error(const char *function, int ret, int error,
616 VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
619 case SSL_ERROR_ZERO_RETURN:
620 VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
623 case SSL_ERROR_WANT_READ:
627 case SSL_ERROR_WANT_WRITE:
631 case SSL_ERROR_WANT_CONNECT:
632 VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
635 case SSL_ERROR_WANT_ACCEPT:
636 VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
639 case SSL_ERROR_WANT_X509_LOOKUP:
640 VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
644 case SSL_ERROR_SYSCALL: {
645 int queued_error = ERR_get_error();
646 if (queued_error == 0) {
649 VLOG_WARN_RL(&rl, "%s: system error (%s)",
650 function, strerror(status));
653 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
658 VLOG_WARN_RL(&rl, "%s: %s",
659 function, ERR_error_string(queued_error, NULL));
664 case SSL_ERROR_SSL: {
665 int queued_error = ERR_get_error();
666 if (queued_error != 0) {
667 VLOG_WARN_RL(&rl, "%s: %s",
668 function, ERR_error_string(queued_error, NULL));
670 VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
677 VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
684 ssl_recv(struct stream *stream, void *buffer, size_t n)
686 struct ssl_stream *sslv = ssl_stream_cast(stream);
690 /* Behavior of zero-byte SSL_read is poorly defined. */
693 old_state = SSL_get_state(sslv->ssl);
694 ret = SSL_read(sslv->ssl, buffer, n);
695 if (old_state != SSL_get_state(sslv->ssl)) {
696 sslv->tx_want = SSL_NOTHING;
698 sslv->rx_want = SSL_NOTHING;
703 int error = SSL_get_error(sslv->ssl, ret);
704 if (error == SSL_ERROR_ZERO_RETURN) {
707 return -interpret_ssl_error("SSL_read", ret, error,
714 ssl_clear_txbuf(struct ssl_stream *sslv)
716 ofpbuf_delete(sslv->txbuf);
721 ssl_do_tx(struct stream *stream)
723 struct ssl_stream *sslv = ssl_stream_cast(stream);
726 int old_state = SSL_get_state(sslv->ssl);
727 int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
728 if (old_state != SSL_get_state(sslv->ssl)) {
729 sslv->rx_want = SSL_NOTHING;
731 sslv->tx_want = SSL_NOTHING;
733 ofpbuf_pull(sslv->txbuf, ret);
734 if (sslv->txbuf->size == 0) {
738 int ssl_error = SSL_get_error(sslv->ssl, ret);
739 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
740 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
743 return interpret_ssl_error("SSL_write", ret, ssl_error,
751 ssl_send(struct stream *stream, const void *buffer, size_t n)
753 struct ssl_stream *sslv = ssl_stream_cast(stream);
760 sslv->txbuf = ofpbuf_clone_data(buffer, n);
761 error = ssl_do_tx(stream);
764 ssl_clear_txbuf(sslv);
767 leak_checker_claim(buffer);
777 ssl_run(struct stream *stream)
779 struct ssl_stream *sslv = ssl_stream_cast(stream);
781 if (sslv->txbuf && ssl_do_tx(stream) != EAGAIN) {
782 ssl_clear_txbuf(sslv);
787 ssl_run_wait(struct stream *stream)
789 struct ssl_stream *sslv = ssl_stream_cast(stream);
791 if (sslv->tx_want != SSL_NOTHING) {
792 poll_fd_wait(sslv->fd, want_to_poll_events(sslv->tx_want));
797 ssl_wait(struct stream *stream, enum stream_wait_type wait)
799 struct ssl_stream *sslv = ssl_stream_cast(stream);
803 if (stream_connect(stream) != EAGAIN) {
804 poll_immediate_wake();
806 switch (sslv->state) {
807 case STATE_TCP_CONNECTING:
808 poll_fd_wait(sslv->fd, POLLOUT);
811 case STATE_SSL_CONNECTING:
812 /* ssl_connect() called SSL_accept() or SSL_connect(), which
813 * set up the status that we test here. */
814 poll_fd_wait(sslv->fd,
815 want_to_poll_events(SSL_want(sslv->ssl)));
825 if (sslv->rx_want != SSL_NOTHING) {
826 poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
828 poll_immediate_wake();
834 /* We have room in our tx queue. */
835 poll_immediate_wake();
837 /* stream_run_wait() will do the right thing; don't bother with
847 struct stream_class ssl_stream_class = {
850 ssl_close, /* close */
851 ssl_connect, /* connect */
855 ssl_run_wait, /* run_wait */
863 struct pstream pstream;
867 struct pstream_class pssl_pstream_class;
869 static struct pssl_pstream *
870 pssl_pstream_cast(struct pstream *pstream)
872 pstream_assert_class(pstream, &pssl_pstream_class);
873 return CONTAINER_OF(pstream, struct pssl_pstream, pstream);
877 pssl_open(const char *name OVS_UNUSED, char *suffix, struct pstream **pstreamp)
879 struct pssl_pstream *pssl;
880 struct sockaddr_in sin;
881 char bound_name[128];
890 fd = inet_open_passive(SOCK_STREAM, suffix, OFP_SSL_PORT, &sin);
894 sprintf(bound_name, "pssl:%"PRIu16":"IP_FMT,
895 ntohs(sin.sin_port), IP_ARGS(&sin.sin_addr.s_addr));
897 pssl = xmalloc(sizeof *pssl);
898 pstream_init(&pssl->pstream, &pssl_pstream_class, bound_name);
900 *pstreamp = &pssl->pstream;
905 pssl_close(struct pstream *pstream)
907 struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
913 pssl_accept(struct pstream *pstream, struct stream **new_streamp)
915 struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
916 struct sockaddr_in sin;
917 socklen_t sin_len = sizeof sin;
922 new_fd = accept(pssl->fd, &sin, &sin_len);
925 if (error != EAGAIN) {
926 VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
931 error = set_nonblocking(new_fd);
937 sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
938 if (sin.sin_port != htons(OFP_SSL_PORT)) {
939 sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
941 return new_ssl_stream(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
946 pssl_wait(struct pstream *pstream)
948 struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
949 poll_fd_wait(pssl->fd, POLLIN);
952 struct pstream_class pssl_pstream_class = {
961 * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
962 * OpenSSL is requesting that we call it back when the socket is ready for read
963 * or writing, respectively.
966 ssl_wants_io(int ssl_error)
968 return (ssl_error == SSL_ERROR_WANT_WRITE
969 || ssl_error == SSL_ERROR_WANT_READ);
975 static int init_status = -1;
976 if (init_status < 0) {
977 init_status = do_ssl_init();
978 assert(init_status >= 0);
989 SSL_load_error_strings();
991 method = TLSv1_method();
992 if (method == NULL) {
993 VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
997 ctx = SSL_CTX_new(method);
999 VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
1002 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
1003 SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
1004 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
1005 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1006 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1013 tmp_dh_callback(SSL *ssl OVS_UNUSED, int is_export OVS_UNUSED, int keylength)
1018 DH *(*constructor)(void);
1021 static struct dh dh_table[] = {
1022 {1024, NULL, get_dh1024},
1023 {2048, NULL, get_dh2048},
1024 {4096, NULL, get_dh4096},
1029 for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
1030 if (dh->keylength == keylength) {
1032 dh->dh = dh->constructor();
1034 ovs_fatal(ENOMEM, "out of memory constructing "
1035 "Diffie-Hellman parameters");
1041 VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
1046 /* Returns true if SSL is at least partially configured. */
1048 stream_ssl_is_configured(void)
1050 return private_key.file_name || certificate.file_name || ca_cert.file_name;
1054 update_ssl_config(struct ssl_config_file *config, const char *file_name)
1056 struct timespec mtime;
1058 if (ssl_init() || !file_name) {
1062 /* If the file name hasn't changed and neither has the file contents, stop
1064 get_mtime(file_name, &mtime);
1065 if (config->file_name
1066 && !strcmp(config->file_name, file_name)
1067 && mtime.tv_sec == config->mtime.tv_sec
1068 && mtime.tv_nsec == config->mtime.tv_nsec) {
1072 /* Update 'config'. */
1073 config->mtime = mtime;
1074 if (file_name != config->file_name) {
1075 free(config->file_name);
1076 config->file_name = xstrdup(file_name);
1082 stream_ssl_set_private_key_file__(const char *file_name)
1084 if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) == 1) {
1085 private_key.read = true;
1087 VLOG_ERR("SSL_use_PrivateKey_file: %s",
1088 ERR_error_string(ERR_get_error(), NULL));
1093 stream_ssl_set_private_key_file(const char *file_name)
1095 if (update_ssl_config(&private_key, file_name)) {
1096 stream_ssl_set_private_key_file__(file_name);
1101 stream_ssl_set_certificate_file__(const char *file_name)
1103 if (SSL_CTX_use_certificate_chain_file(ctx, file_name) == 1) {
1104 certificate.read = true;
1106 VLOG_ERR("SSL_use_certificate_file: %s",
1107 ERR_error_string(ERR_get_error(), NULL));
1112 stream_ssl_set_certificate_file(const char *file_name)
1114 if (update_ssl_config(&certificate, file_name)) {
1115 stream_ssl_set_certificate_file__(file_name);
1119 /* Sets the private key and certificate files in one operation. Use this
1120 * interface, instead of calling stream_ssl_set_private_key_file() and
1121 * stream_ssl_set_certificate_file() individually, in the main loop of a
1122 * long-running program whose key and certificate might change at runtime.
1124 * This is important because of OpenSSL's behavior. If an OpenSSL context
1125 * already has a certificate, and stream_ssl_set_private_key_file() is called
1126 * to install a new private key, OpenSSL will report an error because the new
1127 * private key does not match the old certificate. The other order, of setting
1128 * a new certificate, then setting a new private key, does work.
1130 * If this were the only problem, calling stream_ssl_set_certificate_file()
1131 * before stream_ssl_set_private_key_file() would fix it. But, if the private
1132 * key is changed before the certificate (e.g. someone "scp"s or "mv"s the new
1133 * private key in place before the certificate), then OpenSSL would reject that
1134 * change, and then the change of certificate would succeed, but there would be
1135 * no associated private key (because it had only changed once and therefore
1136 * there was no point in re-reading it).
1138 * This function avoids both problems by, whenever either the certificate or
1139 * the private key file changes, re-reading both of them, in the correct order.
1142 stream_ssl_set_key_and_cert(const char *private_key_file,
1143 const char *certificate_file)
1145 if (update_ssl_config(&private_key, private_key_file)
1146 || update_ssl_config(&certificate, certificate_file)) {
1147 stream_ssl_set_certificate_file__(certificate_file);
1148 stream_ssl_set_private_key_file__(private_key_file);
1152 /* Reads the X509 certificate or certificates in file 'file_name'. On success,
1153 * stores the address of the first element in an array of pointers to
1154 * certificates in '*certs' and the number of certificates in the array in
1155 * '*n_certs', and returns 0. On failure, stores a null pointer in '*certs', 0
1156 * in '*n_certs', and returns a positive errno value.
1158 * The caller is responsible for freeing '*certs'. */
1160 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
1163 size_t allocated_certs = 0;
1168 file = fopen(file_name, "r");
1170 VLOG_ERR("failed to open %s for reading: %s",
1171 file_name, strerror(errno));
1179 /* Read certificate from file. */
1180 certificate = PEM_read_X509(file, NULL, NULL, NULL);
1184 VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1185 file_name, ERR_error_string(ERR_get_error(), NULL));
1186 for (i = 0; i < *n_certs; i++) {
1187 X509_free((*certs)[i]);
1195 /* Add certificate to array. */
1196 if (*n_certs >= allocated_certs) {
1197 *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1199 (*certs)[(*n_certs)++] = certificate;
1201 /* Are there additional certificates in the file? */
1204 } while (isspace(c));
1215 /* Sets 'file_name' as the name of a file containing one or more X509
1216 * certificates to send to the peer. Typical use in OpenFlow is to send the CA
1217 * certificate to the peer, which enables a switch to pick up the controller's
1218 * CA certificate on its first connection. */
1220 stream_ssl_set_peer_ca_cert_file(const char *file_name)
1230 if (!read_cert_file(file_name, &certs, &n_certs)) {
1231 for (i = 0; i < n_certs; i++) {
1232 if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1233 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1234 ERR_error_string(ERR_get_error(), NULL));
1241 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1243 log_ca_cert(const char *file_name, X509 *cert)
1245 unsigned char digest[EVP_MAX_MD_SIZE];
1246 unsigned int n_bytes;
1251 if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1252 ds_put_cstr(&fp, "<out of memory>");
1255 for (i = 0; i < n_bytes; i++) {
1257 ds_put_char(&fp, ':');
1259 ds_put_format(&fp, "%02hhx", digest[i]);
1262 subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1263 VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1264 subject ? subject : "<out of memory>", ds_cstr(&fp));
1265 OPENSSL_free(subject);
1270 stream_ssl_set_ca_cert_file__(const char *file_name, bool bootstrap)
1276 if (!strcmp(file_name, "none")) {
1277 verify_peer_cert = false;
1278 VLOG_WARN("Peer certificate validation disabled "
1279 "(this is a security risk)");
1280 } else if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1281 bootstrap_ca_cert = true;
1282 } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1285 /* Set up list of CAs that the server will accept from the client. */
1286 for (i = 0; i < n_certs; i++) {
1287 /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1288 if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1289 VLOG_ERR("failed to add client certificate %d from %s: %s",
1291 ERR_error_string(ERR_get_error(), NULL));
1293 log_ca_cert(file_name, certs[i]);
1295 X509_free(certs[i]);
1299 /* Set up CAs for OpenSSL to trust in verifying the peer's
1301 if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1302 VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1303 ERR_error_string(ERR_get_error(), NULL));
1307 bootstrap_ca_cert = false;
1309 ca_cert.read = true;
1312 /* Sets 'file_name' as the name of the file from which to read the CA
1313 * certificate used to verify the peer within SSL connections. If 'bootstrap'
1314 * is false, the file must exist. If 'bootstrap' is false, then the file is
1315 * read if it is exists; if it does not, then it will be created from the CA
1316 * certificate received from the peer on the first SSL connection. */
1318 stream_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1320 if (!update_ssl_config(&ca_cert, file_name)) {
1324 stream_ssl_set_ca_cert_file__(file_name, bootstrap);
1327 /* SSL protocol logging. */
1330 ssl_alert_level_to_string(uint8_t type)
1333 case 1: return "warning";
1334 case 2: return "fatal";
1335 default: return "<unknown>";
1340 ssl_alert_description_to_string(uint8_t type)
1343 case 0: return "close_notify";
1344 case 10: return "unexpected_message";
1345 case 20: return "bad_record_mac";
1346 case 21: return "decryption_failed";
1347 case 22: return "record_overflow";
1348 case 30: return "decompression_failure";
1349 case 40: return "handshake_failure";
1350 case 42: return "bad_certificate";
1351 case 43: return "unsupported_certificate";
1352 case 44: return "certificate_revoked";
1353 case 45: return "certificate_expired";
1354 case 46: return "certificate_unknown";
1355 case 47: return "illegal_parameter";
1356 case 48: return "unknown_ca";
1357 case 49: return "access_denied";
1358 case 50: return "decode_error";
1359 case 51: return "decrypt_error";
1360 case 60: return "export_restriction";
1361 case 70: return "protocol_version";
1362 case 71: return "insufficient_security";
1363 case 80: return "internal_error";
1364 case 90: return "user_canceled";
1365 case 100: return "no_renegotiation";
1366 default: return "<unknown>";
1371 ssl_handshake_type_to_string(uint8_t type)
1374 case 0: return "hello_request";
1375 case 1: return "client_hello";
1376 case 2: return "server_hello";
1377 case 11: return "certificate";
1378 case 12: return "server_key_exchange";
1379 case 13: return "certificate_request";
1380 case 14: return "server_hello_done";
1381 case 15: return "certificate_verify";
1382 case 16: return "client_key_exchange";
1383 case 20: return "finished";
1384 default: return "<unknown>";
1389 ssl_protocol_cb(int write_p, int version OVS_UNUSED, int content_type,
1390 const void *buf_, size_t len, SSL *ssl OVS_UNUSED, void *sslv_)
1392 const struct ssl_stream *sslv = sslv_;
1393 const uint8_t *buf = buf_;
1396 if (!VLOG_IS_DBG_ENABLED()) {
1401 if (content_type == 20) {
1402 ds_put_cstr(&details, "change_cipher_spec");
1403 } else if (content_type == 21) {
1404 ds_put_format(&details, "alert: %s, %s",
1405 ssl_alert_level_to_string(buf[0]),
1406 ssl_alert_description_to_string(buf[1]));
1407 } else if (content_type == 22) {
1408 ds_put_format(&details, "handshake: %s",
1409 ssl_handshake_type_to_string(buf[0]));
1411 ds_put_format(&details, "type %d", content_type);
1414 VLOG_DBG("%s%u%s%s %s (%zu bytes)",
1415 sslv->type == CLIENT ? "client" : "server",
1416 sslv->session_nr, write_p ? "-->" : "<--",
1417 stream_get_name(&sslv->stream), ds_cstr(&details), len);
1419 ds_destroy(&details);