Implement "brctl showmacs" support in brcompat and ovs-brcompatd.
[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     char *save_ptr, *host_name, *port_string;
284     struct sockaddr_in sin;
285     int retval;
286     int fd;
287
288     retval = ssl_init();
289     if (retval) {
290         return retval;
291     }
292
293     host_name = strtok_r(suffix, ":", &save_ptr);
294     port_string = strtok_r(NULL, ":", &save_ptr);
295     if (!host_name) {
296         ovs_error(0, "%s: bad peer name format", name);
297         return EAFNOSUPPORT;
298     }
299
300     memset(&sin, 0, sizeof sin);
301     sin.sin_family = AF_INET;
302     if (lookup_ip(host_name, &sin.sin_addr)) {
303         return ENOENT;
304     }
305     sin.sin_port = htons(port_string && *port_string ? atoi(port_string)
306                          : OFP_SSL_PORT);
307
308     /* Create socket. */
309     fd = socket(AF_INET, SOCK_STREAM, 0);
310     if (fd < 0) {
311         VLOG_ERR("%s: socket: %s", name, strerror(errno));
312         return errno;
313     }
314     retval = set_nonblocking(fd);
315     if (retval) {
316         close(fd);
317         return retval;
318     }
319
320     /* Connect socket. */
321     retval = connect(fd, (struct sockaddr *) &sin, sizeof sin);
322     if (retval < 0) {
323         if (errno == EINPROGRESS) {
324             return new_ssl_vconn(name, fd, CLIENT, STATE_TCP_CONNECTING,
325                                  &sin, vconnp);
326         } else {
327             int error = errno;
328             VLOG_ERR("%s: connect: %s", name, strerror(error));
329             close(fd);
330             return error;
331         }
332     } else {
333         return new_ssl_vconn(name, fd, CLIENT, STATE_SSL_CONNECTING,
334                              &sin, vconnp);
335     }
336 }
337
338 static int
339 do_ca_cert_bootstrap(struct vconn *vconn)
340 {
341     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
342     STACK_OF(X509) *chain;
343     X509 *ca_cert;
344     FILE *file;
345     int error;
346     int fd;
347
348     chain = SSL_get_peer_cert_chain(sslv->ssl);
349     if (!chain || !sk_X509_num(chain)) {
350         VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
351                  "peer");
352         return EPROTO;
353     }
354     ca_cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
355
356     /* Check that 'ca_cert' is self-signed.  Otherwise it is not a CA
357      * certificate and we should not attempt to use it as one. */
358     error = X509_check_issued(ca_cert, ca_cert);
359     if (error) {
360         VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
361                  "not self-signed (%s)",
362                  X509_verify_cert_error_string(error));
363         if (sk_X509_num(chain) < 2) {
364             VLOG_ERR("only one certificate was received, so probably the peer "
365                      "is not configured to send its CA certificate");
366         }
367         return EPROTO;
368     }
369
370     fd = open(ca_cert_file, O_CREAT | O_EXCL | O_WRONLY, 0444);
371     if (fd < 0) {
372         VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
373                  ca_cert_file, strerror(errno));
374         return errno;
375     }
376
377     file = fdopen(fd, "w");
378     if (!file) {
379         int error = errno;
380         VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
381                  strerror(error));
382         unlink(ca_cert_file);
383         return error;
384     }
385
386     if (!PEM_write_X509(file, ca_cert)) {
387         VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
388                  "%s", ca_cert_file, ERR_error_string(ERR_get_error(), NULL));
389         fclose(file);
390         unlink(ca_cert_file);
391         return EIO;
392     }
393
394     if (fclose(file)) {
395         int error = errno;
396         VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
397                  ca_cert_file, strerror(error));
398         unlink(ca_cert_file);
399         return error;
400     }
401
402     VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert_file);
403     log_ca_cert(ca_cert_file, ca_cert);
404     bootstrap_ca_cert = false;
405     has_ca_cert = true;
406
407     /* SSL_CTX_add_client_CA makes a copy of ca_cert's relevant data. */
408     SSL_CTX_add_client_CA(ctx, ca_cert);
409
410     /* SSL_CTX_use_certificate() takes ownership of the certificate passed in.
411      * 'ca_cert' is owned by sslv->ssl, so we need to duplicate it. */
412     ca_cert = X509_dup(ca_cert);
413     if (!ca_cert) {
414         out_of_memory();
415     }
416     if (SSL_CTX_load_verify_locations(ctx, ca_cert_file, NULL) != 1) {
417         VLOG_ERR("SSL_CTX_load_verify_locations: %s",
418                  ERR_error_string(ERR_get_error(), NULL));
419         return EPROTO;
420     }
421     VLOG_INFO("killing successful connection to retry using CA cert");
422     return EPROTO;
423 }
424
425 static int
426 ssl_connect(struct vconn *vconn)
427 {
428     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
429     int retval;
430
431     switch (sslv->state) {
432     case STATE_TCP_CONNECTING:
433         retval = check_connection_completion(sslv->fd);
434         if (retval) {
435             return retval;
436         }
437         sslv->state = STATE_SSL_CONNECTING;
438         /* Fall through. */
439
440     case STATE_SSL_CONNECTING:
441         retval = (sslv->type == CLIENT
442                    ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
443         if (retval != 1) {
444             int error = SSL_get_error(sslv->ssl, retval);
445             if (retval < 0 && ssl_wants_io(error)) {
446                 return EAGAIN;
447             } else {
448                 int unused;
449                 interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
450                                      : "SSL_accept"), retval, error, &unused);
451                 shutdown(sslv->fd, SHUT_RDWR);
452                 return EPROTO;
453             }
454         } else if (bootstrap_ca_cert) {
455             return do_ca_cert_bootstrap(vconn);
456         } else if ((SSL_get_verify_mode(sslv->ssl)
457                     & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
458                    != SSL_VERIFY_PEER) {
459             /* Two or more SSL connections completed at the same time while we
460              * were in bootstrap mode.  Only one of these can finish the
461              * bootstrap successfully.  The other one(s) must be rejected
462              * because they were not verified against the bootstrapped CA
463              * certificate.  (Alternatively we could verify them against the CA
464              * certificate, but that's more trouble than it's worth.  These
465              * connections will succeed the next time they retry, assuming that
466              * they have a certificate against the correct CA.) */
467             VLOG_ERR("rejecting SSL connection during bootstrap race window");
468             return EPROTO;
469         } else {
470             return 0;
471         }
472     }
473
474     NOT_REACHED();
475 }
476
477 static void
478 ssl_close(struct vconn *vconn)
479 {
480     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
481     poll_cancel(sslv->tx_waiter);
482     ssl_clear_txbuf(sslv);
483     ofpbuf_delete(sslv->rxbuf);
484     SSL_free(sslv->ssl);
485     close(sslv->fd);
486     free(sslv);
487 }
488
489 static int
490 interpret_ssl_error(const char *function, int ret, int error,
491                     int *want)
492 {
493     *want = SSL_NOTHING;
494
495     switch (error) {
496     case SSL_ERROR_NONE:
497         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
498         break;
499
500     case SSL_ERROR_ZERO_RETURN:
501         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
502         break;
503
504     case SSL_ERROR_WANT_READ:
505         *want = SSL_READING;
506         return EAGAIN;
507
508     case SSL_ERROR_WANT_WRITE:
509         *want = SSL_WRITING;
510         return EAGAIN;
511
512     case SSL_ERROR_WANT_CONNECT:
513         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
514         break;
515
516     case SSL_ERROR_WANT_ACCEPT:
517         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
518         break;
519
520     case SSL_ERROR_WANT_X509_LOOKUP:
521         VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
522                     function);
523         break;
524
525     case SSL_ERROR_SYSCALL: {
526         int queued_error = ERR_get_error();
527         if (queued_error == 0) {
528             if (ret < 0) {
529                 int status = errno;
530                 VLOG_WARN_RL(&rl, "%s: system error (%s)",
531                              function, strerror(status));
532                 return status;
533             } else {
534                 VLOG_WARN_RL(&rl, "%s: unexpected SSL connection close",
535                              function);
536                 return EPROTO;
537             }
538         } else {
539             VLOG_WARN_RL(&rl, "%s: %s",
540                          function, ERR_error_string(queued_error, NULL));
541             break;
542         }
543     }
544
545     case SSL_ERROR_SSL: {
546         int queued_error = ERR_get_error();
547         if (queued_error != 0) {
548             VLOG_WARN_RL(&rl, "%s: %s",
549                          function, ERR_error_string(queued_error, NULL));
550         } else {
551             VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error",
552                         function);
553         }
554         break;
555     }
556
557     default:
558         VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
559         break;
560     }
561     return EIO;
562 }
563
564 static int
565 ssl_recv(struct vconn *vconn, struct ofpbuf **bufferp)
566 {
567     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
568     struct ofpbuf *rx;
569     size_t want_bytes;
570     int old_state;
571     ssize_t ret;
572
573     if (sslv->rxbuf == NULL) {
574         sslv->rxbuf = ofpbuf_new(1564);
575     }
576     rx = sslv->rxbuf;
577
578 again:
579     if (sizeof(struct ofp_header) > rx->size) {
580         want_bytes = sizeof(struct ofp_header) - rx->size;
581     } else {
582         struct ofp_header *oh = rx->data;
583         size_t length = ntohs(oh->length);
584         if (length < sizeof(struct ofp_header)) {
585             VLOG_ERR_RL(&rl, "received too-short ofp_header (%zu bytes)",
586                         length);
587             return EPROTO;
588         }
589         want_bytes = length - rx->size;
590         if (!want_bytes) {
591             *bufferp = rx;
592             sslv->rxbuf = NULL;
593             return 0;
594         }
595     }
596     ofpbuf_prealloc_tailroom(rx, want_bytes);
597
598     /* Behavior of zero-byte SSL_read is poorly defined. */
599     assert(want_bytes > 0);
600
601     old_state = SSL_get_state(sslv->ssl);
602     ret = SSL_read(sslv->ssl, ofpbuf_tail(rx), want_bytes);
603     if (old_state != SSL_get_state(sslv->ssl)) {
604         sslv->tx_want = SSL_NOTHING;
605         if (sslv->tx_waiter) {
606             poll_cancel(sslv->tx_waiter);
607             ssl_tx_poll_callback(sslv->fd, POLLIN, vconn);
608         }
609     }
610     sslv->rx_want = SSL_NOTHING;
611
612     if (ret > 0) {
613         rx->size += ret;
614         if (ret == want_bytes) {
615             if (rx->size > sizeof(struct ofp_header)) {
616                 *bufferp = rx;
617                 sslv->rxbuf = NULL;
618                 return 0;
619             } else {
620                 goto again;
621             }
622         }
623         return EAGAIN;
624     } else {
625         int error = SSL_get_error(sslv->ssl, ret);
626         if (error == SSL_ERROR_ZERO_RETURN) {
627             /* Connection closed (EOF). */
628             if (rx->size) {
629                 VLOG_WARN_RL(&rl, "SSL_read: unexpected connection close");
630                 return EPROTO;
631             } else {
632                 return EOF;
633             }
634         } else {
635             return interpret_ssl_error("SSL_read", ret, error, &sslv->rx_want);
636         }
637     }
638 }
639
640 static void
641 ssl_clear_txbuf(struct ssl_vconn *sslv)
642 {
643     ofpbuf_delete(sslv->txbuf);
644     sslv->txbuf = NULL;
645     sslv->tx_waiter = NULL;
646 }
647
648 static void
649 ssl_register_tx_waiter(struct vconn *vconn)
650 {
651     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
652     sslv->tx_waiter = poll_fd_callback(sslv->fd,
653                                        want_to_poll_events(sslv->tx_want),
654                                        ssl_tx_poll_callback, vconn);
655 }
656
657 static int
658 ssl_do_tx(struct vconn *vconn)
659 {
660     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
661
662     for (;;) {
663         int old_state = SSL_get_state(sslv->ssl);
664         int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
665         if (old_state != SSL_get_state(sslv->ssl)) {
666             sslv->rx_want = SSL_NOTHING;
667         }
668         sslv->tx_want = SSL_NOTHING;
669         if (ret > 0) {
670             ofpbuf_pull(sslv->txbuf, ret);
671             if (sslv->txbuf->size == 0) {
672                 return 0;
673             }
674         } else {
675             int ssl_error = SSL_get_error(sslv->ssl, ret);
676             if (ssl_error == SSL_ERROR_ZERO_RETURN) {
677                 VLOG_WARN_RL(&rl, "SSL_write: connection closed");
678                 return EPIPE;
679             } else {
680                 return interpret_ssl_error("SSL_write", ret, ssl_error,
681                                            &sslv->tx_want);
682             }
683         }
684     }
685 }
686
687 static void
688 ssl_tx_poll_callback(int fd UNUSED, short int revents UNUSED, void *vconn_)
689 {
690     struct vconn *vconn = vconn_;
691     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
692     int error = ssl_do_tx(vconn);
693     if (error != EAGAIN) {
694         ssl_clear_txbuf(sslv);
695     } else {
696         ssl_register_tx_waiter(vconn);
697     }
698 }
699
700 static int
701 ssl_send(struct vconn *vconn, struct ofpbuf *buffer)
702 {
703     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
704
705     if (sslv->txbuf) {
706         return EAGAIN;
707     } else {
708         int error;
709
710         sslv->txbuf = buffer;
711         error = ssl_do_tx(vconn);
712         switch (error) {
713         case 0:
714             ssl_clear_txbuf(sslv);
715             return 0;
716         case EAGAIN:
717             leak_checker_claim(buffer);
718             ssl_register_tx_waiter(vconn);
719             return 0;
720         default:
721             sslv->txbuf = NULL;
722             return error;
723         }
724     }
725 }
726
727 static void
728 ssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
729 {
730     struct ssl_vconn *sslv = ssl_vconn_cast(vconn);
731
732     switch (wait) {
733     case WAIT_CONNECT:
734         if (vconn_connect(vconn) != EAGAIN) {
735             poll_immediate_wake();
736         } else {
737             switch (sslv->state) {
738             case STATE_TCP_CONNECTING:
739                 poll_fd_wait(sslv->fd, POLLOUT);
740                 break;
741
742             case STATE_SSL_CONNECTING:
743                 /* ssl_connect() called SSL_accept() or SSL_connect(), which
744                  * set up the status that we test here. */
745                 poll_fd_wait(sslv->fd,
746                              want_to_poll_events(SSL_want(sslv->ssl)));
747                 break;
748
749             default:
750                 NOT_REACHED();
751             }
752         }
753         break;
754
755     case WAIT_RECV:
756         if (sslv->rx_want != SSL_NOTHING) {
757             poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
758         } else {
759             poll_immediate_wake();
760         }
761         break;
762
763     case WAIT_SEND:
764         if (!sslv->txbuf) {
765             /* We have room in our tx queue. */
766             poll_immediate_wake();
767         } else {
768             /* The call to ssl_tx_poll_callback() will wake us up. */
769         }
770         break;
771
772     default:
773         NOT_REACHED();
774     }
775 }
776
777 struct vconn_class ssl_vconn_class = {
778     "ssl",                      /* name */
779     ssl_open,                   /* open */
780     ssl_close,                  /* close */
781     ssl_connect,                /* connect */
782     ssl_recv,                   /* recv */
783     ssl_send,                   /* send */
784     ssl_wait,                   /* wait */
785 };
786 \f
787 /* Passive SSL. */
788
789 struct pssl_pvconn
790 {
791     struct pvconn pvconn;
792     int fd;
793 };
794
795 struct pvconn_class pssl_pvconn_class;
796
797 static struct pssl_pvconn *
798 pssl_pvconn_cast(struct pvconn *pvconn)
799 {
800     pvconn_assert_class(pvconn, &pssl_pvconn_class);
801     return CONTAINER_OF(pvconn, struct pssl_pvconn, pvconn);
802 }
803
804 static int
805 pssl_open(const char *name, char *suffix, struct pvconn **pvconnp)
806 {
807     struct sockaddr_in sin;
808     struct pssl_pvconn *pssl;
809     int retval;
810     int fd;
811     unsigned int yes = 1;
812
813     retval = ssl_init();
814     if (retval) {
815         return retval;
816     }
817
818     /* Create socket. */
819     fd = socket(AF_INET, SOCK_STREAM, 0);
820     if (fd < 0) {
821         int error = errno;
822         VLOG_ERR("%s: socket: %s", name, strerror(error));
823         return error;
824     }
825
826     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes) < 0) {
827         int error = errno;
828         VLOG_ERR("%s: setsockopt(SO_REUSEADDR): %s", name, strerror(errno));
829         return error;
830     }
831
832     memset(&sin, 0, sizeof sin);
833     sin.sin_family = AF_INET;
834     sin.sin_addr.s_addr = htonl(INADDR_ANY);
835     sin.sin_port = htons(atoi(suffix) ? atoi(suffix) : OFP_SSL_PORT);
836     retval = bind(fd, (struct sockaddr *) &sin, sizeof sin);
837     if (retval < 0) {
838         int error = errno;
839         VLOG_ERR("%s: bind: %s", name, strerror(error));
840         close(fd);
841         return error;
842     }
843
844     retval = listen(fd, 10);
845     if (retval < 0) {
846         int error = errno;
847         VLOG_ERR("%s: listen: %s", name, strerror(error));
848         close(fd);
849         return error;
850     }
851
852     retval = set_nonblocking(fd);
853     if (retval) {
854         close(fd);
855         return retval;
856     }
857
858     pssl = xmalloc(sizeof *pssl);
859     pvconn_init(&pssl->pvconn, &pssl_pvconn_class, name);
860     pssl->fd = fd;
861     *pvconnp = &pssl->pvconn;
862     return 0;
863 }
864
865 static void
866 pssl_close(struct pvconn *pvconn)
867 {
868     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
869     close(pssl->fd);
870     free(pssl);
871 }
872
873 static int
874 pssl_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
875 {
876     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
877     struct sockaddr_in sin;
878     socklen_t sin_len = sizeof sin;
879     char name[128];
880     int new_fd;
881     int error;
882
883     new_fd = accept(pssl->fd, &sin, &sin_len);
884     if (new_fd < 0) {
885         int error = errno;
886         if (error != EAGAIN) {
887             VLOG_DBG_RL(&rl, "accept: %s", strerror(error));
888         }
889         return error;
890     }
891
892     error = set_nonblocking(new_fd);
893     if (error) {
894         close(new_fd);
895         return error;
896     }
897
898     sprintf(name, "ssl:"IP_FMT, IP_ARGS(&sin.sin_addr));
899     if (sin.sin_port != htons(OFP_SSL_PORT)) {
900         sprintf(strchr(name, '\0'), ":%"PRIu16, ntohs(sin.sin_port));
901     }
902     return new_ssl_vconn(name, new_fd, SERVER, STATE_SSL_CONNECTING, &sin,
903                          new_vconnp);
904 }
905
906 static void
907 pssl_wait(struct pvconn *pvconn)
908 {
909     struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
910     poll_fd_wait(pssl->fd, POLLIN);
911 }
912
913 struct pvconn_class pssl_pvconn_class = {
914     "pssl",
915     pssl_open,
916     pssl_close,
917     pssl_accept,
918     pssl_wait,
919 };
920 \f
921 /*
922  * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
923  * OpenSSL is requesting that we call it back when the socket is ready for read
924  * or writing, respectively.
925  */
926 static bool
927 ssl_wants_io(int ssl_error)
928 {
929     return (ssl_error == SSL_ERROR_WANT_WRITE
930             || ssl_error == SSL_ERROR_WANT_READ);
931 }
932
933 static int
934 ssl_init(void)
935 {
936     static int init_status = -1;
937     if (init_status < 0) {
938         init_status = do_ssl_init();
939         assert(init_status >= 0);
940     }
941     return init_status;
942 }
943
944 static int
945 do_ssl_init(void)
946 {
947     SSL_METHOD *method;
948
949     SSL_library_init();
950     SSL_load_error_strings();
951
952     method = TLSv1_method();
953     if (method == NULL) {
954         VLOG_ERR("TLSv1_method: %s", ERR_error_string(ERR_get_error(), NULL));
955         return ENOPROTOOPT;
956     }
957
958     ctx = SSL_CTX_new(method);
959     if (ctx == NULL) {
960         VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
961         return ENOPROTOOPT;
962     }
963     SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
964     SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
965     SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
966     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
967     SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
968                        NULL);
969
970     return 0;
971 }
972
973 static DH *
974 tmp_dh_callback(SSL *ssl UNUSED, int is_export UNUSED, int keylength)
975 {
976     struct dh {
977         int keylength;
978         DH *dh;
979         DH *(*constructor)(void);
980     };
981
982     static struct dh dh_table[] = {
983         {1024, NULL, get_dh1024},
984         {2048, NULL, get_dh2048},
985         {4096, NULL, get_dh4096},
986     };
987
988     struct dh *dh;
989
990     for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
991         if (dh->keylength == keylength) {
992             if (!dh->dh) {
993                 dh->dh = dh->constructor();
994                 if (!dh->dh) {
995                     ovs_fatal(ENOMEM, "out of memory constructing "
996                               "Diffie-Hellman parameters");
997                 }
998             }
999             return dh->dh;
1000         }
1001     }
1002     VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
1003                 keylength);
1004     return NULL;
1005 }
1006
1007 /* Returns true if SSL is at least partially configured. */
1008 bool
1009 vconn_ssl_is_configured(void) 
1010 {
1011     return has_private_key || has_certificate || has_ca_cert;
1012 }
1013
1014 void
1015 vconn_ssl_set_private_key_file(const char *file_name)
1016 {
1017     if (ssl_init()) {
1018         return;
1019     }
1020     if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) != 1) {
1021         VLOG_ERR("SSL_use_PrivateKey_file: %s",
1022                  ERR_error_string(ERR_get_error(), NULL));
1023         return;
1024     }
1025     has_private_key = true;
1026 }
1027
1028 void
1029 vconn_ssl_set_certificate_file(const char *file_name)
1030 {
1031     if (ssl_init()) {
1032         return;
1033     }
1034     if (SSL_CTX_use_certificate_chain_file(ctx, file_name) != 1) {
1035         VLOG_ERR("SSL_use_certificate_file: %s",
1036                  ERR_error_string(ERR_get_error(), NULL));
1037         return;
1038     }
1039     has_certificate = true;
1040 }
1041
1042 /* Reads the X509 certificate or certificates in file 'file_name'.  On success,
1043  * stores the address of the first element in an array of pointers to
1044  * certificates in '*certs' and the number of certificates in the array in
1045  * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
1046  * in '*n_certs', and returns a positive errno value.
1047  *
1048  * The caller is responsible for freeing '*certs'. */
1049 static int
1050 read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
1051 {
1052     FILE *file;
1053     size_t allocated_certs = 0;
1054
1055     *certs = NULL;
1056     *n_certs = 0;
1057
1058     file = fopen(file_name, "r");
1059     if (!file) {
1060         VLOG_ERR("failed to open %s for reading: %s",
1061                  file_name, strerror(errno));
1062         return errno;
1063     }
1064
1065     for (;;) {
1066         X509 *certificate;
1067         int c;
1068
1069         /* Read certificate from file. */
1070         certificate = PEM_read_X509(file, NULL, NULL, NULL);
1071         if (!certificate) {
1072             size_t i;
1073
1074             VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1075                      file_name, ERR_error_string(ERR_get_error(), NULL));
1076             for (i = 0; i < *n_certs; i++) {
1077                 X509_free((*certs)[i]);
1078             }
1079             free(*certs);
1080             *certs = NULL;
1081             *n_certs = 0;
1082             return EIO;
1083         }
1084
1085         /* Add certificate to array. */
1086         if (*n_certs >= allocated_certs) {
1087             *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1088         }
1089         (*certs)[(*n_certs)++] = certificate;
1090
1091         /* Are there additional certificates in the file? */
1092         do {
1093             c = getc(file);
1094         } while (isspace(c));
1095         if (c == EOF) {
1096             break;
1097         }
1098         ungetc(c, file);
1099     }
1100     fclose(file);
1101     return 0;
1102 }
1103
1104
1105 /* Sets 'file_name' as the name of a file containing one or more X509
1106  * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1107  * certificate to the peer, which enables a switch to pick up the controller's
1108  * CA certificate on its first connection. */
1109 void
1110 vconn_ssl_set_peer_ca_cert_file(const char *file_name)
1111 {
1112     X509 **certs;
1113     size_t n_certs;
1114     size_t i;
1115
1116     if (ssl_init()) {
1117         return;
1118     }
1119
1120     if (!read_cert_file(file_name, &certs, &n_certs)) {
1121         for (i = 0; i < n_certs; i++) {
1122             if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1123                 VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1124                          ERR_error_string(ERR_get_error(), NULL));
1125             }
1126         }
1127         free(certs);
1128     }
1129 }
1130
1131 /* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1132 static void
1133 log_ca_cert(const char *file_name, X509 *cert)
1134 {
1135     unsigned char digest[EVP_MAX_MD_SIZE];
1136     unsigned int n_bytes;
1137     struct ds fp;
1138     char *subject;
1139
1140     ds_init(&fp);
1141     if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1142         ds_put_cstr(&fp, "<out of memory>");
1143     } else {
1144         unsigned int i;
1145         for (i = 0; i < n_bytes; i++) {
1146             if (i) {
1147                 ds_put_char(&fp, ':');
1148             }
1149             ds_put_format(&fp, "%02hhx", digest[i]);
1150         }
1151     }
1152     subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1153     VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1154               subject ? subject : "<out of memory>", ds_cstr(&fp));
1155     free(subject);
1156     ds_destroy(&fp);
1157 }
1158
1159 /* Sets 'file_name' as the name of the file from which to read the CA
1160  * certificate used to verify the peer within SSL connections.  If 'bootstrap'
1161  * is false, the file must exist.  If 'bootstrap' is false, then the file is
1162  * read if it is exists; if it does not, then it will be created from the CA
1163  * certificate received from the peer on the first SSL connection. */
1164 void
1165 vconn_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1166 {
1167     X509 **certs;
1168     size_t n_certs;
1169     struct stat s;
1170
1171     if (ssl_init()) {
1172         return;
1173     }
1174
1175     if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1176         bootstrap_ca_cert = true;
1177         ca_cert_file = xstrdup(file_name);
1178     } else if (!read_cert_file(file_name, &certs, &n_certs)) {
1179         size_t i;
1180
1181         /* Set up list of CAs that the server will accept from the client. */
1182         for (i = 0; i < n_certs; i++) {
1183             /* SSL_CTX_add_client_CA makes a copy of the relevant data. */
1184             if (SSL_CTX_add_client_CA(ctx, certs[i]) != 1) {
1185                 VLOG_ERR("failed to add client certificate %d from %s: %s",
1186                          i, file_name,
1187                          ERR_error_string(ERR_get_error(), NULL));
1188             } else {
1189                 log_ca_cert(file_name, certs[i]);
1190             }
1191             X509_free(certs[i]);
1192         }
1193
1194         /* Set up CAs for OpenSSL to trust in verifying the peer's
1195          * certificate. */
1196         if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1197             VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1198                      ERR_error_string(ERR_get_error(), NULL));
1199             return;
1200         }
1201
1202         has_ca_cert = true;
1203     }
1204 }