vconn: Convert vconn code to modern OVS structure.
[sliver-openvswitch.git] / lib / vconn-ssl.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "vconn-ssl.h"
19 #include "dhparams.h"
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <string.h>
25 #include <netinet/tcp.h>
26 #include <openssl/err.h>
27 #include <openssl/ssl.h>
28 #include <openssl/x509v3.h>
29 #include <poll.h>
30 #include <sys/fcntl.h>
31 #include <sys/stat.h>
32 #include <unistd.h>
33 #include "dynamic-string.h"
34 #include "leak-checker.h"
35 #include "ofpbuf.h"
36 #include "openflow/openflow.h"
37 #include "packets.h"
38 #include "poll-loop.h"
39 #include "socket-util.h"
40 #include "socket-util.h"
41 #include "util.h"
42 #include "vconn-provider.h"
43 #include "vconn.h"
44
45 #include "vlog.h"
46 #define THIS_MODULE VLM_vconn_ssl
47
48 /* Active SSL. */
49
50 enum ssl_state {
51     STATE_TCP_CONNECTING,
52     STATE_SSL_CONNECTING
53 };
54
55 enum session_type {
56     CLIENT,
57     SERVER
58 };
59
60 struct ssl_vconn
61 {
62     struct vconn vconn;
63     enum ssl_state state;
64     int connect_error;
65     enum session_type type;
66     int fd;
67     SSL *ssl;
68     struct ofpbuf *rxbuf;
69     struct ofpbuf *txbuf;
70
71     /* rx_want and tx_want record the result of the last call to SSL_read()
72      * and SSL_write(), respectively:
73      *
74      *    - If the call reported that data needed to be read from the file
75      *      descriptor, the corresponding member is set to SSL_READING.
76      *
77      *    - If the call reported that data needed to be written to the file
78      *      descriptor, the corresponding member is set to SSL_WRITING.
79      *
80      *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
81      *      call completed successfully (or with an error) and that there is no
82      *      need to block.
83      *
84      * These are needed because there is no way to ask OpenSSL what a data read
85      * or write would require without giving it a buffer to receive into or
86      * data to send, respectively.  (Note that the SSL_want() status is
87      * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
88      * its value.)
89      *
90      * A single call to SSL_read() or SSL_write() can perform both reading
91      * and writing and thus invalidate not one of these values but actually
92      * both.  Consider this situation, for example:
93      *
94      *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
95      *
96      *    - SSL_read() laters succeeds reading from 'fd' and clears out the
97      *      whole receive buffer, so rx_want gets SSL_READING.
98      *
99      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
100      *      blocks.
101      *
102      *    - Now we're stuck blocking until the peer sends us data, even though
103      *      SSL_write() could now succeed, which could easily be a deadlock
104      *      condition.
105      *
106      * On the other hand, we can't reset both tx_want and rx_want on every call
107      * to SSL_read() or SSL_write(), because that would produce livelock,
108      * e.g. in this situation:
109      *
110      *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
111      *
112      *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
113      *      but tx_want gets reset to SSL_NOTHING.
114      *
115      *    - Client calls vconn_wait(WAIT_RECV) and vconn_wait(WAIT_SEND) and
116      *      blocks.
117      *
118      *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
119      *      that no blocking is necessary.
120      *
121      * The solution we adopt here is to set tx_want to SSL_NOTHING after
122      * calling SSL_read() only if the SSL state of the connection changed,
123      * which indicates that an SSL-level renegotiation made some progress, and
124      * similarly for rx_want and SSL_write().  This prevents both the
125      * deadlock and livelock situations above.
126      */
127     int rx_want, tx_want;
128 };
129
130 /* SSL context created by ssl_init(). */
131 static SSL_CTX *ctx;
132
133 /* Required configuration. */
134 static bool has_private_key, has_certificate, has_ca_cert;
135
136 /* Ordinarily, we require a CA certificate for the peer to be locally
137  * available.  'has_ca_cert' is true when this is the case, and neither of the
138  * following variables matter.
139  *
140  * We can, however, bootstrap the CA certificate from the peer at the beginning
141  * of our first connection then use that certificate on all subsequent
142  * connections, saving it to a file for use in future runs also.  In this case,
143  * 'has_ca_cert' is false, 'bootstrap_ca_cert' is true, and 'ca_cert_file'
144  * names the file to be saved. */
145 static bool bootstrap_ca_cert;
146 static char *ca_cert_file;
147
148 /* Who knows what can trigger various SSL errors, so let's throttle them down
149  * quite a bit. */
150 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
151
152 static int ssl_init(void);
153 static int do_ssl_init(void);
154 static bool ssl_wants_io(int ssl_error);
155 static void ssl_close(struct vconn *);
156 static void ssl_clear_txbuf(struct ssl_vconn *);
157 static int interpret_ssl_error(const char *function, int ret, int error,
158                                int *want);
159 static DH *tmp_dh_callback(SSL *ssl, int is_export UNUSED, int keylength);
160 static void log_ca_cert(const char *file_name, X509 *cert);
161
162 static 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 *remote,
183               struct vconn **vconnp)
184 {
185     struct sockaddr_in local;
186     socklen_t local_len = sizeof local;
187     struct ssl_vconn *sslv;
188     SSL *ssl = NULL;
189     int on = 1;
190     int retval;
191
192     /* Check for all the needful configuration. */
193     retval = 0;
194     if (!has_private_key) {
195         VLOG_ERR("Private key must be configured to use SSL");
196         retval = ENOPROTOOPT;
197     }
198     if (!has_certificate) {
199         VLOG_ERR("Certificate must be configured to use SSL");
200         retval = ENOPROTOOPT;
201     }
202     if (!has_ca_cert && !bootstrap_ca_cert) {
203         VLOG_ERR("CA certificate must be configured to use SSL");
204         retval = ENOPROTOOPT;
205     }
206     if (!SSL_CTX_check_private_key(ctx)) {
207         VLOG_ERR("Private key does not match certificate public key: %s",
208                  ERR_error_string(ERR_get_error(), NULL));
209         retval = ENOPROTOOPT;
210     }
211     if (retval) {
212         goto error;
213     }
214
215     /* Get the local IP and port information */
216     retval = getsockname(fd, (struct sockaddr *) &local, &local_len);
217     if (retval) {
218         memset(&local, 0, sizeof local);
219     }
220
221     /* Disable Nagle. */
222     retval = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
223     if (retval) {
224         VLOG_ERR("%s: setsockopt(TCP_NODELAY): %s", name, strerror(errno));
225         retval = errno;
226         goto error;
227     }
228
229     /* Create and configure OpenSSL stream. */
230     ssl = SSL_new(ctx);
231     if (ssl == NULL) {
232         VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
233         retval = ENOPROTOOPT;
234         goto error;
235     }
236     if (SSL_set_fd(ssl, fd) == 0) {
237         VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
238         retval = ENOPROTOOPT;
239         goto error;
240     }
241     if (bootstrap_ca_cert && type == CLIENT) {
242         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
243     }
244
245     /* Create and return the ssl_vconn. */
246     sslv = xmalloc(sizeof *sslv);
247     vconn_init(&sslv->vconn, &ssl_vconn_class, EAGAIN, name);
248     vconn_set_remote_ip(&sslv->vconn, remote->sin_addr.s_addr);
249     vconn_set_remote_port(&sslv->vconn, remote->sin_port);
250     vconn_set_local_ip(&sslv->vconn, local.sin_addr.s_addr);
251     vconn_set_local_port(&sslv->vconn, local.sin_port);
252     sslv->state = state;
253     sslv->type = type;
254     sslv->fd = fd;
255     sslv->ssl = ssl;
256     sslv->rxbuf = NULL;
257     sslv->txbuf = NULL;
258     sslv->rx_want = sslv->tx_want = SSL_NOTHING;
259     *vconnp = &sslv->vconn;
260     return 0;
261
262 error:
263     if (ssl) {
264         SSL_free(ssl);
265     }
266     close(fd);
267     return retval;
268 }
269
270 static struct ssl_vconn *
271 ssl_vconn_cast(struct vconn *vconn)
272 {
273     vconn_assert_class(vconn, &ssl_vconn_class);
274     return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
275 }
276
277 static int
278 ssl_open(const char *name, char *suffix, struct vconn **vconnp)
279 {
280     struct sockaddr_in sin;
281     int error, fd;
282
283     error = ssl_init();
284     if (error) {
285         return error;
286     }
287
288     error = inet_open_active(SOCK_STREAM, suffix, OFP_SSL_PORT, &sin, &fd);
289     if (fd >= 0) {
290         int state = error ? STATE_TCP_CONNECTING : STATE_SSL_CONNECTING;
291         return new_ssl_vconn(name, fd, CLIENT, state, &sin, vconnp);
292     } else {
293         VLOG_ERR("%s: connect: %s", name, strerror(error));
294         return error;
295     }
296 }
297
298 static int
299 do_ca_cert_bootstrap(struct vconn *vconn)
300 {
301     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
302     STACK_OF(X509) *chain;
303     X509 *ca_cert;
304     FILE *file;
305     int error;
306     int fd;
307
308     chain = SSL_get_peer_cert_chain(sslv->ssl);
309     if (!chain || !sk_X509_num(chain)) {
310         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
311                  "peer");
312         return EPROTO;
313     }
314     ca_cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
315
316     /* Check that 'ca_cert' is self-signed.  Otherwise it is not a CA
317      * certificate and we should not attempt to use it as one. */
318     error = X509_check_issued(ca_cert, ca_cert);
319     if (error) {
320         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
321                  "not self-signed (%s)",
322                  X509_verify_cert_error_string(error));
323         if (sk_X509_num(chain) < 2) {
324             VLOG_ERR("only one certificate was received, so probably the peer "
325                      "is not configured to send its CA certificate");
326         }
327         return EPROTO;
328     }
329
330     fd = open(ca_cert_file, O_CREAT | O_EXCL | O_WRONLY, 0444);
331     if (fd < 0) {
332         VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
333                  ca_cert_file, strerror(errno));
334         return errno;
335     }
336
337     file = fdopen(fd, "w");
338     if (!file) {
339         int error = errno;
340         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
341                  strerror(error));
342         unlink(ca_cert_file);
343         return error;
344     }
345
346     if (!PEM_write_X509(file, ca_cert)) {
347         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
348                  "%s", ca_cert_file, ERR_error_string(ERR_get_error(), NULL));
349         fclose(file);
350         unlink(ca_cert_file);
351         return EIO;
352     }
353
354     if (fclose(file)) {
355         int error = errno;
356         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
357                  ca_cert_file, strerror(error));
358         unlink(ca_cert_file);
359         return error;
360     }
361
362     VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert_file);
363     log_ca_cert(ca_cert_file, ca_cert);
364     bootstrap_ca_cert = false;
365     has_ca_cert = true;
366
367     /* SSL_CTX_add_client_CA makes a copy of ca_cert's relevant data. */
368     SSL_CTX_add_client_CA(ctx, ca_cert);
369
370     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
371      * 'ca_cert' is owned by sslv->ssl, so we need to duplicate it. */
372     ca_cert = X509_dup(ca_cert);
373     if (!ca_cert) {
374         out_of_memory();
375     }
376     if (SSL_CTX_load_verify_locations(ctx, ca_cert_file, NULL) != 1) {
377         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
378                  ERR_error_string(ERR_get_error(), NULL));
379         return EPROTO;
380     }
381     VLOG_INFO("killing successful connection to retry using CA cert");
382     return EPROTO;
383 }
384
385 static int
386 ssl_connect(struct vconn *vconn)
387 {
388     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
389     int retval;
390
391     switch (sslv->state) {
392     case STATE_TCP_CONNECTING:
393         retval = check_connection_completion(sslv->fd);
394         if (retval) {
395             return retval;
396         }
397         sslv->state = STATE_SSL_CONNECTING;
398         /* Fall through. */
399
400     case STATE_SSL_CONNECTING:
401         retval = (sslv->type == CLIENT
402                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
403         if (retval != 1) {
404             int error = SSL_get_error(sslv->ssl, retval);
405             if (retval < 0 && ssl_wants_io(error)) {
406                 return EAGAIN;
407             } else {
408                 int unused;
409                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
410                                      : "SSL_accept"), retval, error, &unused);
411                 shutdown(sslv->fd, SHUT_RDWR);
412                 return EPROTO;
413             }
414         } else if (bootstrap_ca_cert) {
415             return do_ca_cert_bootstrap(vconn);
416         } else if ((SSL_get_verify_mode(sslv->ssl)
417                     & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
418                    != SSL_VERIFY_PEER) {
419             /* Two or more SSL connections completed at the same time while we
420              * were in bootstrap mode.  Only one of these can finish the
421              * bootstrap successfully.  The other one(s) must be rejected
422              * because they were not verified against the bootstrapped CA
423              * certificate.  (Alternatively we could verify them against the CA
424              * certificate, but that's more trouble than it's worth.  These
425              * connections will succeed the next time they retry, assuming that
426              * they have a certificate against the correct CA.) */
427             VLOG_ERR("rejecting SSL connection during bootstrap race window");
428             return EPROTO;
429         } else {
430             return 0;
431         }
432     }
433
434     NOT_REACHED();
435 }
436
437 static void
438 ssl_close(struct vconn *vconn)
439 {
440     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
441     ssl_clear_txbuf(sslv);
442     ofpbuf_delete(sslv->rxbuf);
443     SSL_free(sslv->ssl);
444     close(sslv->fd);
445     free(sslv);
446 }
447
448 static int
449 interpret_ssl_error(const char *function, int ret, int error,
450                     int *want)
451 {
452     *want = SSL_NOTHING;
453
454     switch (error) {
455     case SSL_ERROR_NONE:
456         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
457         break;
458
459     case SSL_ERROR_ZERO_RETURN:
460         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
461         break;
462
463     case SSL_ERROR_WANT_READ:
464         *want = SSL_READING;
465         return EAGAIN;
466
467     case SSL_ERROR_WANT_WRITE:
468         *want = SSL_WRITING;
469         return EAGAIN;
470
471     case SSL_ERROR_WANT_CONNECT:
472         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
473         break;
474
475     case SSL_ERROR_WANT_ACCEPT:
476         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
477         break;
478
479     case SSL_ERROR_WANT_X509_LOOKUP:
480         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
481                     function);
482         break;
483
484     case SSL_ERROR_SYSCALL: {
485         int queued_error = ERR_get_error();
486         if (queued_error == 0) {
487             if (ret < 0) {
488                 int status = errno;
489                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
490                              function, strerror(status));
491                 return status;
492             } else {
493                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
494                              function);
495                 return EPROTO;
496             }
497         } else {
498             VLOG_WARN_RL(&rl, "%s: %s",
499                          function, ERR_error_string(queued_error, NULL));
500             break;
501         }
502     }
503
504     case SSL_ERROR_SSL: {
505         int queued_error = ERR_get_error();
506         if (queued_error != 0) {
507             VLOG_WARN_RL(&rl, "%s: %s",
508                          function, ERR_error_string(queued_error, NULL));
509         } else {
510             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
511                         function);
512         }
513         break;
514     }
515
516     default:
517         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
518         break;
519     }
520     return EIO;
521 }
522
523 static int
524 ssl_recv(struct vconn *vconn, struct ofpbuf **bufferp)
525 {
526     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
527     struct ofpbuf *rx;
528     size_t want_bytes;
529     int old_state;
530     ssize_t ret;
531
532     if (sslv->rxbuf == NULL) {
533         sslv->rxbuf = ofpbuf_new(1564);
534     }
535     rx = sslv->rxbuf;
536
537 again:
538     if (sizeof(struct ofp_header) > rx->size) {
539         want_bytes = sizeof(struct ofp_header) - rx->size;
540     } else {
541         struct ofp_header *oh = rx->data;
542         size_t length = ntohs(oh->length);
543         if (length < sizeof(struct ofp_header)) {
544             VLOG_ERR_RL(&rl, "received too-short ofp_header (%zu bytes)",
545                         length);
546             return EPROTO;
547         }
548         want_bytes = length - rx->size;
549         if (!want_bytes) {
550             *bufferp = rx;
551             sslv->rxbuf = NULL;
552             return 0;
553         }
554     }
555     ofpbuf_prealloc_tailroom(rx, want_bytes);
556
557     /* Behavior of zero-byte SSL_read is poorly defined. */
558     assert(want_bytes > 0);
559
560     old_state = SSL_get_state(sslv->ssl);
561     ret = SSL_read(sslv->ssl, ofpbuf_tail(rx), want_bytes);
562     if (old_state != SSL_get_state(sslv->ssl)) {
563         sslv->tx_want = SSL_NOTHING;
564     }
565     sslv->rx_want = SSL_NOTHING;
566
567     if (ret > 0) {
568         rx->size += ret;
569         if (ret == want_bytes) {
570             if (rx->size > sizeof(struct ofp_header)) {
571                 *bufferp = rx;
572                 sslv->rxbuf = NULL;
573                 return 0;
574             } else {
575                 goto again;
576             }
577         }
578         return EAGAIN;
579     } else {
580         int error = SSL_get_error(sslv->ssl, ret);
581         if (error == SSL_ERROR_ZERO_RETURN) {
582             /* Connection closed (EOF). */
583             if (rx->size) {
584                 VLOG_WARN_RL(&rl, "SSL_read: unexpected connection close");
585                 return EPROTO;
586             } else {
587                 return EOF;
588             }
589         } else {
590             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
591         }
592     }
593 }
594
595 static void
596 ssl_clear_txbuf(struct ssl_vconn *sslv)
597 {
598     ofpbuf_delete(sslv->txbuf);
599     sslv->txbuf = NULL;
600 }
601
602 static int
603 ssl_do_tx(struct vconn *vconn)
604 {
605     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
606
607     for (;;) {
608         int old_state = SSL_get_state(sslv->ssl);
609         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
610         if (old_state != SSL_get_state(sslv->ssl)) {
611             sslv->rx_want = SSL_NOTHING;
612         }
613         sslv->tx_want = SSL_NOTHING;
614         if (ret > 0) {
615             ofpbuf_pull(sslv->txbuf, ret);
616             if (sslv->txbuf->size == 0) {
617                 return 0;
618             }
619         } else {
620             int ssl_error = SSL_get_error(sslv->ssl, ret);
621             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
622                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
623                 return EPIPE;
624             } else {
625                 return interpret_ssl_error("SSL_write", ret, ssl_error,
626                                            &sslv->tx_want);
627             }
628         }
629     }
630 }
631
632 static int
633 ssl_send(struct vconn *vconn, struct ofpbuf *buffer)
634 {
635     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
636
637     if (sslv->txbuf) {
638         return EAGAIN;
639     } else {
640         int error;
641
642         sslv->txbuf = buffer;
643         error = ssl_do_tx(vconn);
644         switch (error) {
645         case 0:
646             ssl_clear_txbuf(sslv);
647             return 0;
648         case EAGAIN:
649             leak_checker_claim(buffer);
650             return 0;
651         default:
652             sslv->txbuf = NULL;
653             return error;
654         }
655     }
656 }
657
658 static void
659 ssl_run(struct vconn *vconn)
660 {
661     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
662
663     if (sslv->txbuf && ssl_do_tx(vconn) != EAGAIN) {
664         ssl_clear_txbuf(sslv);
665     }
666 }
667
668 static void
669 ssl_run_wait(struct vconn *vconn)
670 {
671     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
672
673     if (sslv->tx_want != SSL_NOTHING) {
674         poll_fd_wait(sslv->fd, want_to_poll_events(sslv->tx_want));
675     }
676 }
677
678 static void
679 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
680 {
681     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
682
683     switch (wait) {
684     case WAIT_CONNECT:
685         if (vconn_connect(vconn) != EAGAIN) {
686             poll_immediate_wake();
687         } else {
688             switch (sslv->state) {
689             case STATE_TCP_CONNECTING:
690                 poll_fd_wait(sslv->fd, POLLOUT);
691                 break;
692
693             case STATE_SSL_CONNECTING:
694                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
695                  * set up the status that we test here. */
696                 poll_fd_wait(sslv->fd,
697                              want_to_poll_events(SSL_want(sslv->ssl)));
698                 break;
699
700             default:
701                 NOT_REACHED();
702             }
703         }
704         break;
705
706     case WAIT_RECV:
707         if (sslv->rx_want != SSL_NOTHING) {
708             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
709         } else {
710             poll_immediate_wake();
711         }
712         break;
713
714     case WAIT_SEND:
715         if (!sslv->txbuf) {
716             /* We have room in our tx queue. */
717             poll_immediate_wake();
718         } else {
719             /* vconn_run_wait() will do the right thing; don't bother with
720              * redundancy. */
721         }
722         break;
723
724     default:
725         NOT_REACHED();
726     }
727 }
728
729 struct vconn_class ssl_vconn_class = {
730     "ssl",                      /* name */
731     ssl_open,                   /* open */
732     ssl_close,                  /* close */
733     ssl_connect,                /* connect */
734     ssl_recv,                   /* recv */
735     ssl_send,                   /* send */
736     ssl_run,                    /* run */
737     ssl_run_wait,               /* run_wait */
738     ssl_wait,                   /* wait */
739 };
740 \f
741 /* Passive SSL. */
742
743 struct pssl_pvconn
744 {
745     struct pvconn pvconn;
746     int fd;
747 };
748
749 struct pvconn_class pssl_pvconn_class;
750
751 static struct pssl_pvconn *
752 pssl_pvconn_cast(struct pvconn *pvconn)
753 {
754     pvconn_assert_class(pvconn, &pssl_pvconn_class);
755     return CONTAINER_OF(pvconn, struct pssl_pvconn, pvconn);
756 }
757
758 static int
759 pssl_open(const char *name, char *suffix, struct pvconn **pvconnp)
760 {
761     struct pssl_pvconn *pssl;
762     int retval;
763     int fd;
764
765     retval = ssl_init();
766     if (retval) {
767         return retval;
768     }
769
770     fd = inet_open_passive(SOCK_STREAM, suffix, OFP_SSL_PORT);
771     if (fd < 0) {
772         return -fd;
773     }
774
775     pssl = xmalloc(sizeof *pssl);
776     pvconn_init(&pssl->pvconn, &pssl_pvconn_class, name);
777     pssl->fd = fd;
778     *pvconnp = &pssl->pvconn;
779     return 0;
780 }
781
782 static void
783 pssl_close(struct pvconn *pvconn)
784 {
785     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
786     close(pssl->fd);
787     free(pssl);
788 }
789
790 static int
791 pssl_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
792 {
793     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
794     struct sockaddr_in sin;
795     socklen_t sin_len = sizeof sin;
796     char name[128];
797     int new_fd;
798     int error;
799
800     new_fd = accept(pssl->fd, &sin, &sin_len);
801     if (new_fd < 0) {
802         int error = errno;
803         if (error != EAGAIN) {
804             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
805         }
806         return error;
807     }
808
809     error = set_nonblocking(new_fd);
810     if (error) {
811         close(new_fd);
812         return error;
813     }
814
815     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
816     if (sin.sin_port != htons(OFP_SSL_PORT)) {
817         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
818     }
819     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
820                          new_vconnp);
821 }
822
823 static void
824 pssl_wait(struct pvconn *pvconn)
825 {
826     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
827     poll_fd_wait(pssl->fd, POLLIN);
828 }
829
830 struct pvconn_class pssl_pvconn_class = {
831     "pssl",
832     pssl_open,
833     pssl_close,
834     pssl_accept,
835     pssl_wait,
836 };
837 \f
838 /*
839  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
840  * OpenSSL is requesting that we call it back when the socket is ready for read
841  * or writing, respectively.
842  */
843 static bool
844 ssl_wants_io(int ssl_error)
845 {
846     return (ssl_error == SSL_ERROR_WANT_WRITE
847             || ssl_error == SSL_ERROR_WANT_READ);
848 }
849
850 static int
851 ssl_init(void)
852 {
853     static int init_status = -1;
854     if (init_status < 0) {
855         init_status = do_ssl_init();
856         assert(init_status >= 0);
857     }
858     return init_status;
859 }
860
861 static int
862 do_ssl_init(void)
863 {
864     SSL_METHOD *method;
865
866     SSL_library_init();
867     SSL_load_error_strings();
868
869     method = TLSv1_method();
870     if (method == NULL) {
871         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
872         return ENOPROTOOPT;
873     }
874
875     ctx = SSL_CTX_new(method);
876     if (ctx == NULL) {
877         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
878         return ENOPROTOOPT;
879     }
880     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
881     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
882     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
883     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
884     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
885                        NULL);
886
887     return 0;
888 }
889
890 static DH *
891 tmp_dh_callback(SSL *ssl UNUSED, int is_export UNUSED, int keylength)
892 {
893     struct dh {
894         int keylength;
895         DH *dh;
896         DH *(*constructor)(void);
897     };
898
899     static struct dh dh_table[] = {
900         {1024, NULL, get_dh1024},
901         {2048, NULL, get_dh2048},
902         {4096, NULL, get_dh4096},
903     };
904
905     struct dh *dh;
906
907     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
908         if (dh->keylength == keylength) {
909             if (!dh->dh) {
910                 dh->dh = dh->constructor();
911                 if (!dh->dh) {
912                     ovs_fatal(ENOMEM, "out of memory constructing "
913                               "Diffie-Hellman parameters");
914                 }
915             }
916             return dh->dh;
917         }
918     }
919     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
920                 keylength);
921     return NULL;
922 }
923
924 /* Returns true if SSL is at least partially configured. */
925 bool
926 vconn_ssl_is_configured(void) 
927 {
928     return has_private_key || has_certificate || has_ca_cert;
929 }
930
931 void
932 vconn_ssl_set_private_key_file(const char *file_name)
933 {
934     if (ssl_init()) {
935         return;
936     }
937     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
938         VLOG_ERR("SSL_use_PrivateKey_file: %s",
939                  ERR_error_string(ERR_get_error(), NULL));
940         return;
941     }
942     has_private_key = true;
943 }
944
945 void
946 vconn_ssl_set_certificate_file(const char *file_name)
947 {
948     if (ssl_init()) {
949         return;
950     }
951     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
952         VLOG_ERR("SSL_use_certificate_file: %s",
953                  ERR_error_string(ERR_get_error(), NULL));
954         return;
955     }
956     has_certificate = true;
957 }
958
959 /* Reads the X509 certificate or certificates in file 'file_name'.  On success,
960  * stores the address of the first element in an array of pointers to
961  * certificates in '*certs' and the number of certificates in the array in
962  * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
963  * in '*n_certs', and returns a positive errno value.
964  *
965  * The caller is responsible for freeing '*certs'. */
966 static int
967 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
968 {
969     FILE *file;
970     size_t allocated_certs = 0;
971
972     *certs = NULL;
973     *n_certs = 0;
974
975     file = fopen(file_name, "r");
976     if (!file) {
977         VLOG_ERR("failed to open %s for reading: %s",
978                  file_name, strerror(errno));
979         return errno;
980     }
981
982     for (;;) {
983         X509 *certificate;
984         int c;
985
986         /* Read certificate from file. */
987         certificate = PEM_read_X509(file, NULL, NULL, NULL);
988         if (!certificate) {
989             size_t i;
990
991             VLOG_ERR("PEM_read_X509 failed reading %s: %s",
992                      file_name, ERR_error_string(ERR_get_error(), NULL));
993             for (i = 0; i < *n_certs; i++) {
994                 X509_free((*certs)[i]);
995             }
996             free(*certs);
997             *certs = NULL;
998             *n_certs = 0;
999             return EIO;
1000         }
1001
1002         /* Add certificate to array. */
1003         if (*n_certs >= allocated_certs) {
1004             *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1005         }
1006         (*certs)[(*n_certs)++] = certificate;
1007
1008         /* Are there additional certificates in the file? */
1009         do {
1010             c = getc(file);
1011         } while (isspace(c));
1012         if (c == EOF) {
1013             break;
1014         }
1015         ungetc(c, file);
1016     }
1017     fclose(file);
1018     return 0;
1019 }
1020
1021
1022 /* Sets 'file_name' as the name of a file containing one or more X509
1023  * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1024  * certificate to the peer, which enables a switch to pick up the controller's
1025  * CA certificate on its first connection. */
1026 void
1027 vconn_ssl_set_peer_ca_cert_file(const char *file_name)
1028 {
1029     X509 **certs;
1030     size_t n_certs;
1031     size_t i;
1032
1033     if (ssl_init()) {
1034         return;
1035     }
1036
1037     if (!read_cert_file(file_name, &certs, &n_certs)) {
1038         for (i = 0; i < n_certs; i++) {
1039             if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1040                 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1041                          ERR_error_string(ERR_get_error(), NULL));
1042             }
1043         }
1044         free(certs);
1045     }
1046 }
1047
1048 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1049 static void
1050 log_ca_cert(const char *file_name, X509 *cert)
1051 {
1052     unsigned char digest[EVP_MAX_MD_SIZE];
1053     unsigned int n_bytes;
1054     struct ds fp;
1055     char *subject;
1056
1057     ds_init(&fp);
1058     if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1059         ds_put_cstr(&fp, "<out of memory>");
1060     } else {
1061         unsigned int i;
1062         for (i = 0; i < n_bytes; i++) {
1063             if (i) {
1064                 ds_put_char(&fp, ':');
1065             }
1066             ds_put_format(&fp, "%02hhx", digest[i]);
1067         }
1068     }
1069     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1070     VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1071               subject ? subject : "<out of memory>", ds_cstr(&fp));
1072     free(subject);
1073     ds_destroy(&fp);
1074 }
1075
1076 /* Sets 'file_name' as the name of the file from which to read the CA
1077  * certificate used to verify the peer within SSL connections.  If 'bootstrap'
1078  * is false, the file must exist.  If 'bootstrap' is false, then the file is
1079  * read if it is exists; if it does not, then it will be created from the CA
1080  * certificate received from the peer on the first SSL connection. */
1081 void
1082 vconn_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1083 {
1084     X509 **certs;
1085     size_t n_certs;
1086     struct stat s;
1087
1088     if (ssl_init()) {
1089         return;
1090     }
1091
1092     if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1093         bootstrap_ca_cert = true;
1094         ca_cert_file = xstrdup(file_name);
1095     } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1096         size_t i;
1097
1098         /* Set up list of CAs that the server will accept from the client. */
1099         for (i = 0; i < n_certs; i++) {
1100             /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1101             if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1102                 VLOG_ERR("failed to add client certificate %d from %s: %s",
1103                          i, file_name,
1104                          ERR_error_string(ERR_get_error(), NULL));
1105             } else {
1106                 log_ca_cert(file_name, certs[i]);
1107             }
1108             X509_free(certs[i]);
1109         }
1110
1111         /* Set up CAs for OpenSSL to trust in verifying the peer's
1112          * certificate. */
1113         if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1114             VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1115                      ERR_error_string(ERR_get_error(), NULL));
1116             return;
1117         }
1118
1119         has_ca_cert = true;
1120     }
1121 }