shrpx_ssl.cc 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Spdylay - SPDY Library
 *
 * Copyright (c) 2012 Tatsuhiro Tsujikawa
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "shrpx_ssl.h"

#include <sys/socket.h>
#include <netdb.h>
29
#include <netinet/tcp.h>
30 31
#include <pthread.h>

32 33 34
#include <vector>
#include <string>

35
#include <openssl/crypto.h>
36 37
#include <openssl/x509.h>
#include <openssl/x509v3.h>
38 39 40 41

#include <event2/bufferevent.h>
#include <event2/bufferevent_ssl.h>

42 43
#include <spdylay/spdylay.h>

44 45 46
#include "shrpx_log.h"
#include "shrpx_client_handler.h"
#include "shrpx_config.h"
47
#include "shrpx_accesslog.h"
48 49 50
#include "util.h"

using namespace spdylay;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

namespace shrpx {

namespace ssl {

namespace {
std::pair<unsigned char*, size_t> next_proto;
unsigned char proto_list[23];
} // namespace

namespace {
int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len,
                  void *arg)
{
  std::pair<unsigned char*, size_t> *next_proto =
    reinterpret_cast<std::pair<unsigned char*, size_t>* >(arg);
  *data = next_proto->first;
  *len = next_proto->second;
  return SSL_TLSEXT_ERR_OK;
}
} // namespace

namespace {
int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
  // We don't verify the client certificate. Just request it for the
  // testing purpose.
  return 1;
}
} // namespace

82 83 84 85 86 87 88 89 90 91 92 93
namespace {
void set_npn_prefs(unsigned char *out, const char **protos, size_t len)
{
  unsigned char *ptr = out;
  for(size_t i = 0; i < len; ++i) {
    *ptr = strlen(protos[i]);
    memcpy(ptr+1, protos[i], *ptr);
    ptr += *ptr+1;
  }
}
} // namespace

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

static int ssl_pem_passwd_cb(char *buf, int size, int rwflag, void *user_data)
{
  Config *config = (Config *)user_data;
  int len = (int)strlen(config->private_key_passwd);
  if (size < len + 1) {
    LOG(ERROR) << "ssl_pem_passwd_cb: buf is too small " << size;
    return 0;
  }

  strncpy(buf, config->private_key_passwd, len);
  buf[len] = '\0';
  return len;
}


110 111 112 113 114 115 116 117 118
SSL_CTX* create_ssl_context()
{
  SSL_CTX *ssl_ctx;
  ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  if(!ssl_ctx) {
    LOG(FATAL) << ERR_error_string(ERR_get_error(), 0);
    DIE();
  }
  SSL_CTX_set_options(ssl_ctx,
119 120 121
                      SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_COMPRESSION |
                      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);

122 123 124 125
  const unsigned char sid_ctx[] = "shrpx";
  SSL_CTX_set_session_id_context(ssl_ctx, sid_ctx, sizeof(sid_ctx)-1);
  SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);

126 127
  if(get_config()->ciphers) {
    if(SSL_CTX_set_cipher_list(ssl_ctx, get_config()->ciphers) == 0) {
128 129
      LOG(FATAL) << "SSL_CTX_set_cipher_list failed: "
                 << ERR_error_string(ERR_get_error(), NULL);
130 131 132 133
      DIE();
    }
  }

134
  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
135 136
  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
137 138 139 140
  if (get_config()->private_key_passwd) {
    SSL_CTX_set_default_passwd_cb(ssl_ctx, ssl_pem_passwd_cb);
    SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)get_config());
  }
141 142 143
  if(SSL_CTX_use_PrivateKey_file(ssl_ctx,
                                 get_config()->private_key_file,
                                 SSL_FILETYPE_PEM) != 1) {
144 145
    LOG(FATAL) << "SSL_CTX_use_PrivateKey_file failed: "
               << ERR_error_string(ERR_get_error(), NULL);
146 147
    DIE();
  }
148 149
  if(SSL_CTX_use_certificate_chain_file(ssl_ctx,
                                        get_config()->cert_file) != 1) {
150 151
    LOG(FATAL) << "SSL_CTX_use_certificate_file failed: "
               << ERR_error_string(ERR_get_error(), NULL);
152 153 154
    DIE();
  }
  if(SSL_CTX_check_private_key(ssl_ctx) != 1) {
155 156
    LOG(FATAL) << "SSL_CTX_check_private_key failed: "
               << ERR_error_string(ERR_get_error(), NULL);
157 158 159 160 161 162 163 164
    DIE();
  }
  if(get_config()->verify_client) {
    SSL_CTX_set_verify(ssl_ctx,
                       SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE |
                       SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
                       verify_callback);
  }
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
165
  // We speak "http/1.1", "spdy/2" and "spdy/3".
166 167
  const char *protos[] = { "spdy/3", "spdy/2", "http/1.1" };
  set_npn_prefs(proto_list, protos, 3);
168 169 170 171 172 173 174

  next_proto.first = proto_list;
  next_proto.second = sizeof(proto_list);
  SSL_CTX_set_next_protos_advertised_cb(ssl_ctx, next_proto_cb, &next_proto);
  return ssl_ctx;
}

175 176 177 178 179 180 181
namespace {
int select_next_proto_cb(SSL* ssl,
                         unsigned char **out, unsigned char *outlen,
                         const unsigned char *in, unsigned int inlen,
                         void *arg)
{
  if(spdylay_select_next_protocol(out, outlen, in, inlen) <= 0) {
Tatsuhiro Tsujikawa's avatar
Tatsuhiro Tsujikawa committed
182
    *out = (unsigned char*)"spdy/3";
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    *outlen = 6;
  }
  return SSL_TLSEXT_ERR_OK;
}
} // namespace

SSL_CTX* create_ssl_client_context()
{
  SSL_CTX *ssl_ctx;
  ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  if(!ssl_ctx) {
    LOG(FATAL) << ERR_error_string(ERR_get_error(), 0);
    DIE();
  }
  SSL_CTX_set_options(ssl_ctx,
                      SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_COMPRESSION |
                      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);

  if(get_config()->ciphers) {
    if(SSL_CTX_set_cipher_list(ssl_ctx, get_config()->ciphers) == 0) {
      LOG(FATAL) << "SSL_CTX_set_cipher_list failed: "
                 << ERR_error_string(ERR_get_error(), NULL);
      DIE();
    }
  }

  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);

213 214 215 216 217 218 219 220 221 222 223 224 225 226
  if(SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
    LOG(WARNING) << "Could not load system trusted ca certificates: "
                 << ERR_error_string(ERR_get_error(), NULL);
  }

  if(get_config()->cacert) {
    if(SSL_CTX_load_verify_locations(ssl_ctx, get_config()->cacert, 0) != 1) {
      LOG(FATAL) << "Could not load trusted ca certificates from "
                 << get_config()->cacert << ": "
                 << ERR_error_string(ERR_get_error(), NULL);
      DIE();
    }
  }

227 228 229 230
  SSL_CTX_set_next_proto_select_cb(ssl_ctx, select_next_proto_cb, 0);
  return ssl_ctx;
}

231 232 233 234 235 236 237 238
ClientHandler* accept_ssl_connection(event_base *evbase, SSL_CTX *ssl_ctx,
                                     evutil_socket_t fd,
                                     sockaddr *addr, int addrlen)
{
  char host[NI_MAXHOST];
  int rv;
  rv = getnameinfo(addr, addrlen, host, sizeof(host), 0, 0, NI_NUMERICHOST);
  if(rv == 0) {
239 240 241 242
    if(get_config()->accesslog) {
      upstream_connect(host);
    }

243 244 245 246
    int val = 1;
    rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
                    reinterpret_cast<char *>(&val), sizeof(val));
    if(rv == -1) {
247 248
      LOG(WARNING) << "Setting option TCP_NODELAY failed: "
                   << strerror(errno);
249
    }
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    SSL *ssl = 0;
    bufferevent *bev;
    if(get_config()->client_mode) {
      bev = bufferevent_socket_new(evbase, fd, BEV_OPT_DEFER_CALLBACKS);
    } else {
      ssl = SSL_new(ssl_ctx);
      if(!ssl) {
        LOG(ERROR) << "SSL_new() failed: "
                   << ERR_error_string(ERR_get_error(), NULL);
        return 0;
      }
      bev = bufferevent_openssl_socket_new
        (evbase, fd, ssl,
         BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_DEFER_CALLBACKS);
    }
    ClientHandler *client_handler = new ClientHandler(bev, fd, ssl, host);
266 267 268 269 270 271 272
    return client_handler;
  } else {
    LOG(ERROR) << "getnameinfo() failed: " << gai_strerror(rv);
    return 0;
  }
}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
bool numeric_host(const char *hostname)
{
  struct addrinfo hints;
  struct addrinfo* res;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_flags = AI_NUMERICHOST;
  if(getaddrinfo(hostname, 0, &hints, &res)) {
    return false;
  }
  freeaddrinfo(res);
  return true;
}

namespace {
bool tls_hostname_match(const char *pattern, const char *hostname)
{
  const char *ptWildcard = strchr(pattern, '*');
  if(ptWildcard == 0) {
    return util::strieq(pattern, hostname);
  }
  const char *ptLeftLabelEnd = strchr(pattern, '.');
  bool wildcardEnabled = true;
  // Do case-insensitive match. At least 2 dots are required to enable
  // wildcard match. Also wildcard must be in the left-most label.
  // Don't attempt to match a presented identifier where the wildcard
  // character is embedded within an A-label.
  if(ptLeftLabelEnd == 0 || strchr(ptLeftLabelEnd+1, '.') == 0 ||
     ptLeftLabelEnd < ptWildcard || util::istartsWith(pattern, "xn--")) {
    wildcardEnabled = false;
  }
  if(!wildcardEnabled) {
    return util::strieq(pattern, hostname);
  }
  const char *hnLeftLabelEnd = strchr(hostname, '.');
  if(hnLeftLabelEnd == 0 || !util::strieq(ptLeftLabelEnd, hnLeftLabelEnd)) {
    return false;
  }
  // Perform wildcard match. Here '*' must match at least one
  // character.
  if(hnLeftLabelEnd - hostname < ptLeftLabelEnd - pattern) {
    return false;
  }
  return util::istartsWith(hostname, hnLeftLabelEnd, pattern, ptWildcard) &&
    util::iendsWith(hostname, hnLeftLabelEnd, ptWildcard+1, ptLeftLabelEnd);
}
} // namespace

namespace {
int verify_hostname(const char *hostname,
                    const sockaddr_union *su,
                    size_t salen,
                    const std::vector<std::string>& dns_names,
                    const std::vector<std::string>& ip_addrs,
                    const std::string& common_name)
{
  if(numeric_host(hostname)) {
    if(ip_addrs.empty()) {
      return util::strieq(common_name.c_str(), hostname) ? 0 : -1;
    }
    const void *saddr;
    switch(su->storage.ss_family) {
    case AF_INET:
      saddr = &su->in.sin_addr;
      break;
    case AF_INET6:
      saddr = &su->in6.sin6_addr;
      break;
    default:
      return -1;
    }
    for(size_t i = 0; i < ip_addrs.size(); ++i) {
      if(salen == ip_addrs[i].size() &&
         memcmp(saddr, ip_addrs[i].c_str(), salen) == 0) {
        return 0;
      }
    }
  } else {
    if(dns_names.empty()) {
      return tls_hostname_match(common_name.c_str(), hostname) ? 0 : -1;
    }
    for(size_t i = 0; i < dns_names.size(); ++i) {
      if(tls_hostname_match(dns_names[i].c_str(), hostname)) {
        return 0;
      }
    }
  }
  return -1;
}
} // namespace

int check_cert(SSL *ssl)
{
  X509 *cert = SSL_get_peer_certificate(ssl);
  if(!cert) {
    LOG(ERROR) << "No certificate found";
    return -1;
  }
  util::auto_delete<X509*> cert_deleter(cert, X509_free);
  long verify_res = SSL_get_verify_result(ssl);
  if(verify_res != X509_V_OK) {
    LOG(ERROR) << "Certificate verification failed: "
               << X509_verify_cert_error_string(verify_res);
    return -1;
  }
  std::string common_name;
  std::vector<std::string> dns_names;
  std::vector<std::string> ip_addrs;
  GENERAL_NAMES* altnames;
  altnames = reinterpret_cast<GENERAL_NAMES*>
    (X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0));
  if(altnames) {
    util::auto_delete<GENERAL_NAMES*> altnames_deleter(altnames,
                                                       GENERAL_NAMES_free);
    size_t n = sk_GENERAL_NAME_num(altnames);
    for(size_t i = 0; i < n; ++i) {
      const GENERAL_NAME *altname = sk_GENERAL_NAME_value(altnames, i);
      if(altname->type == GEN_DNS) {
        const char *name;
        name = reinterpret_cast<char*>(ASN1_STRING_data(altname->d.ia5));
        if(!name) {
          continue;
        }
        size_t len = ASN1_STRING_length(altname->d.ia5);
        if(std::find(name, name+len, '\0') != name+len) {
          // Embedded NULL is not permitted.
          continue;
        }
        dns_names.push_back(std::string(name, len));
      } else if(altname->type == GEN_IPADD) {
        const unsigned char *ip_addr = altname->d.iPAddress->data;
        if(!ip_addr) {
          continue;
        }
        size_t len = altname->d.iPAddress->length;
        ip_addrs.push_back(std::string(reinterpret_cast<const char*>(ip_addr),
                                      len));
      }
    }
  }
  X509_NAME *subjectname = X509_get_subject_name(cert);
  if(!subjectname) {
    LOG(ERROR) << "Could not get X509 name object from the certificate.";
    return -1;
  }
  int lastpos = -1;
  while(1) {
    lastpos = X509_NAME_get_index_by_NID(subjectname, NID_commonName,
                                         lastpos);
    if(lastpos == -1) {
      break;
    }
    X509_NAME_ENTRY *entry = X509_NAME_get_entry(subjectname, lastpos);
    unsigned char *out;
    int outlen = ASN1_STRING_to_UTF8(&out, X509_NAME_ENTRY_get_data(entry));
    if(outlen < 0) {
      continue;
    }
    if(std::find(out, out+outlen, '\0') != out+outlen) {
      // Embedded NULL is not permitted.
      continue;
    }
    common_name.assign(&out[0], &out[outlen]);
    OPENSSL_free(out);
    break;
  }
  if(verify_hostname(get_config()->downstream_host,
                     &get_config()->downstream_addr,
                     get_config()->downstream_addrlen,
                     dns_names, ip_addrs, common_name) != 0) {
    LOG(ERROR) << "Certificate verification failed: hostname does not match";
    return -1;
  }
  return 0;
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
namespace {
pthread_mutex_t *ssl_locks;
} // namespace

namespace {
void ssl_locking_cb(int mode, int type, const char *file, int line)
{
  if(mode & CRYPTO_LOCK) {
    pthread_mutex_lock(&(ssl_locks[type]));
  } else {
    pthread_mutex_unlock(&(ssl_locks[type]));
  }
}
} // namespace

void setup_ssl_lock()
{
  ssl_locks = new pthread_mutex_t[CRYPTO_num_locks()];
  for(int i = 0; i < CRYPTO_num_locks(); ++i) {
    // Always returns 0
    pthread_mutex_init(&(ssl_locks[i]), 0);
  }
  //CRYPTO_set_id_callback(ssl_thread_id); OpenSSL manual says that if
  // threadid_func is not specified using
  // CRYPTO_THREADID_set_callback(), then default implementation is
  // used. We use this default one.
  CRYPTO_set_locking_callback(ssl_locking_cb);
}

void teardown_ssl_lock()
{
  for(int i = 0; i < CRYPTO_num_locks(); ++i) {
    pthread_mutex_destroy(&(ssl_locks[i]));
  }
  delete [] ssl_locks;
}

486 487 488
} // namespace ssl

} // namespace shrpx