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