2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "SSLContext.h"
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #include <openssl/ssl.h>
22 #include <openssl/x509v3.h>
24 #include <folly/Format.h>
25 #include <folly/SpinLock.h>
27 // ---------------------------------------------------------------------
28 // SSLContext implementation
29 // ---------------------------------------------------------------------
31 struct CRYPTO_dynlock_value {
37 bool SSLContext::initialized_ = false;
41 std::mutex& initMutex() {
46 } // anonymous namespace
48 #ifdef OPENSSL_NPN_NEGOTIATED
49 int SSLContext::sNextProtocolsExDataIndex_ = -1;
52 // SSLContext implementation
53 SSLContext::SSLContext(SSLVersion version) {
55 std::lock_guard<std::mutex> g(initMutex());
56 initializeOpenSSLLocked();
59 ctx_ = SSL_CTX_new(SSLv23_method());
60 if (ctx_ == nullptr) {
61 throw std::runtime_error("SSL_CTX_new: " + getErrors());
67 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
70 opt = SSL_OP_NO_SSLv2;
76 int newOpt = SSL_CTX_set_options(ctx_, opt);
77 DCHECK((newOpt & opt) == opt);
79 SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
81 checkPeerName_ = false;
83 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
84 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
85 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
89 SSLContext::~SSLContext() {
90 if (ctx_ != nullptr) {
95 #ifdef OPENSSL_NPN_NEGOTIATED
96 deleteNextProtocolsStrings();
100 void SSLContext::ciphers(const std::string& ciphers) {
101 providedCiphersString_ = ciphers;
102 setCiphersOrThrow(ciphers);
105 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
106 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
107 if (ERR_peek_error() != 0) {
108 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
111 throw std::runtime_error("None of specified ciphers are supported");
115 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
117 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
118 verifyPeer_ = verifyPeer;
121 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
123 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
124 int mode = SSL_VERIFY_NONE;
126 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
129 case SSLVerifyPeerEnum::VERIFY:
130 mode = SSL_VERIFY_PEER;
133 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
134 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
137 case SSLVerifyPeerEnum::NO_VERIFY:
138 mode = SSL_VERIFY_NONE;
147 int SSLContext::getVerificationMode() {
148 return getVerificationMode(verifyPeer_);
151 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
152 const std::string& peerName) {
155 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
156 checkPeerName_ = checkPeerName;
157 peerFixedName_ = peerName;
159 mode = SSL_VERIFY_NONE;
160 checkPeerName_ = false; // can't check name without cert!
161 peerFixedName_.clear();
163 SSL_CTX_set_verify(ctx_, mode, nullptr);
166 void SSLContext::loadCertificate(const char* path, const char* format) {
167 if (path == nullptr || format == nullptr) {
168 throw std::invalid_argument(
169 "loadCertificateChain: either <path> or <format> is nullptr");
171 if (strcmp(format, "PEM") == 0) {
172 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
173 int errnoCopy = errno;
174 std::string reason("SSL_CTX_use_certificate_chain_file: ");
177 reason.append(getErrors(errnoCopy));
178 throw std::runtime_error(reason);
181 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
185 void SSLContext::loadPrivateKey(const char* path, const char* format) {
186 if (path == nullptr || format == nullptr) {
187 throw std::invalid_argument(
188 "loadPrivateKey: either <path> or <format> is nullptr");
190 if (strcmp(format, "PEM") == 0) {
191 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
192 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
195 throw std::runtime_error("Unsupported private key format: " + std::string(format));
199 void SSLContext::loadTrustedCertificates(const char* path) {
200 if (path == nullptr) {
201 throw std::invalid_argument(
202 "loadTrustedCertificates: <path> is nullptr");
204 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
205 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
209 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
210 SSL_CTX_set_cert_store(ctx_, store);
213 void SSLContext::loadClientCAList(const char* path) {
214 auto clientCAs = SSL_load_client_CA_file(path);
215 if (clientCAs == nullptr) {
216 LOG(ERROR) << "Unable to load ca file: " << path;
219 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
222 void SSLContext::randomize() {
226 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
227 if (collector == nullptr) {
228 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
231 collector_ = collector;
232 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
233 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
236 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
238 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
242 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
243 clientHelloCbs_.push_back(cb);
246 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
247 SSLContext* context = (SSLContext*)data;
249 if (context == nullptr) {
250 return SSL_TLSEXT_ERR_NOACK;
253 for (auto& cb : context->clientHelloCbs_) {
254 // Generic callbacks to happen after we receive the Client Hello.
255 // For example, we use one to switch which cipher we use depending
256 // on the user's TLS version. Because the primary purpose of
257 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
258 // are side-uses, we ignore any possible failures other than just logging
263 if (!context->serverNameCb_) {
264 return SSL_TLSEXT_ERR_NOACK;
267 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
269 case SERVER_NAME_FOUND:
270 return SSL_TLSEXT_ERR_OK;
271 case SERVER_NAME_NOT_FOUND:
272 return SSL_TLSEXT_ERR_NOACK;
273 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
274 *al = TLS1_AD_UNRECOGNIZED_NAME;
275 return SSL_TLSEXT_ERR_ALERT_FATAL;
280 return SSL_TLSEXT_ERR_NOACK;
283 void SSLContext::switchCiphersIfTLS11(
285 const std::string& tls11CipherString) {
287 CHECK(!tls11CipherString.empty()) << "Shouldn't call if empty alt ciphers";
289 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
290 // We only do this for TLS v 1.1 and later
294 // Prefer AES for TLS versions 1.1 and later since these are not
295 // vulnerable to BEAST attacks on AES. Note that we're setting the
296 // cipher list on the SSL object, not the SSL_CTX object, so it will
297 // only last for this request.
298 int rc = SSL_set_cipher_list(ssl, tls11CipherString.c_str());
299 if ((rc == 0) || ERR_peek_error() != 0) {
300 // This shouldn't happen since we checked for this when proxygen
302 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
303 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
308 #ifdef OPENSSL_NPN_NEGOTIATED
309 bool SSLContext::setAdvertisedNextProtocols(const std::list<std::string>& protocols) {
310 return setRandomizedAdvertisedNextProtocols({{1, protocols}});
313 bool SSLContext::setRandomizedAdvertisedNextProtocols(
314 const std::list<NextProtocolsItem>& items) {
315 unsetNextProtocols();
316 if (items.size() == 0) {
319 int total_weight = 0;
320 for (const auto &item : items) {
321 if (item.protocols.size() == 0) {
324 AdvertisedNextProtocolsItem advertised_item;
325 advertised_item.length = 0;
326 for (const auto& proto : item.protocols) {
327 ++advertised_item.length;
328 unsigned protoLength = proto.length();
329 if (protoLength >= 256) {
330 deleteNextProtocolsStrings();
333 advertised_item.length += protoLength;
335 advertised_item.protocols = new unsigned char[advertised_item.length];
336 if (!advertised_item.protocols) {
337 throw std::runtime_error("alloc failure");
339 unsigned char* dst = advertised_item.protocols;
340 for (auto& proto : item.protocols) {
341 unsigned protoLength = proto.length();
342 *dst++ = (unsigned char)protoLength;
343 memcpy(dst, proto.data(), protoLength);
346 total_weight += item.weight;
347 advertised_item.probability = item.weight;
348 advertisedNextProtocols_.push_back(advertised_item);
350 if (total_weight == 0) {
351 deleteNextProtocolsStrings();
354 for (auto &advertised_item : advertisedNextProtocols_) {
355 advertised_item.probability /= total_weight;
357 SSL_CTX_set_next_protos_advertised_cb(
358 ctx_, advertisedNextProtocolCallback, this);
359 SSL_CTX_set_next_proto_select_cb(
360 ctx_, selectNextProtocolCallback, this);
364 void SSLContext::deleteNextProtocolsStrings() {
365 for (auto protocols : advertisedNextProtocols_) {
366 delete[] protocols.protocols;
368 advertisedNextProtocols_.clear();
371 void SSLContext::unsetNextProtocols() {
372 deleteNextProtocolsStrings();
373 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
374 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
377 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
378 const unsigned char** out, unsigned int* outlen, void* data) {
379 SSLContext* context = (SSLContext*)data;
380 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
383 } else if (context->advertisedNextProtocols_.size() == 1) {
384 *out = context->advertisedNextProtocols_[0].protocols;
385 *outlen = context->advertisedNextProtocols_[0].length;
387 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
388 sNextProtocolsExDataIndex_));
389 if (selected_index) {
391 *out = context->advertisedNextProtocols_[selected_index].protocols;
392 *outlen = context->advertisedNextProtocols_[selected_index].length;
394 unsigned char random_byte;
395 RAND_bytes(&random_byte, 1);
396 double random_value = random_byte / 255.0;
398 for (size_t i = 0; i < context->advertisedNextProtocols_.size(); ++i) {
399 sum += context->advertisedNextProtocols_[i].probability;
400 if (sum < random_value &&
401 i + 1 < context->advertisedNextProtocols_.size()) {
404 uintptr_t selected = i + 1;
405 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void *)selected);
406 *out = context->advertisedNextProtocols_[i].protocols;
407 *outlen = context->advertisedNextProtocols_[i].length;
412 return SSL_TLSEXT_ERR_OK;
415 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
416 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
417 SSLContext::SSLFalseStartChecker::SSLFalseStartChecker() :
419 TLS1_CK_DHE_DSS_WITH_AES_128_SHA,
420 TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
421 TLS1_CK_DHE_DSS_WITH_AES_256_SHA,
422 TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
423 TLS1_CK_DHE_DSS_WITH_AES_128_SHA256,
424 TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
425 TLS1_CK_DHE_DSS_WITH_AES_256_SHA256,
426 TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
427 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
428 TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
429 TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256,
430 TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384,
431 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
432 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
433 TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
434 TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
435 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
436 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
437 TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256,
438 TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384,
439 TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
440 TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
441 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
442 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
443 TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
444 TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
446 length_ = sizeof(ciphers_)/sizeof(ciphers_[0]);
447 width_ = sizeof(ciphers_[0]);
448 qsort(ciphers_, length_, width_, compare_ulong);
451 bool SSLContext::SSLFalseStartChecker::canUseFalseStartWithCipher(
452 const SSL_CIPHER *cipher) {
453 unsigned long cid = cipher->id;
455 (unsigned long*)bsearch(&cid, ciphers_, length_, width_, compare_ulong);
460 SSLContext::SSLFalseStartChecker::compare_ulong(const void *x, const void *y) {
461 if (*(unsigned long *)x < *(unsigned long *)y) {
464 if (*(unsigned long *)x > *(unsigned long *)y) {
470 bool SSLContext::canUseFalseStartWithCipher(const SSL_CIPHER *cipher) {
471 return falseStartChecker_.canUseFalseStartWithCipher(cipher);
475 int SSLContext::selectNextProtocolCallback(
476 SSL* ssl, unsigned char **out, unsigned char *outlen,
477 const unsigned char *server, unsigned int server_len, void *data) {
479 SSLContext* ctx = (SSLContext*)data;
480 if (ctx->advertisedNextProtocols_.size() > 1) {
481 VLOG(3) << "SSLContext::selectNextProcolCallback() "
482 << "client should be deterministic in selecting protocols.";
485 unsigned char *client;
486 unsigned int client_len;
487 bool filtered = false;
488 auto cpf = ctx->getClientProtocolFilterCallback();
490 filtered = (*cpf)(&client, &client_len, server, server_len);
494 if (ctx->advertisedNextProtocols_.empty()) {
495 client = (unsigned char *) "";
498 client = ctx->advertisedNextProtocols_[0].protocols;
499 client_len = ctx->advertisedNextProtocols_[0].length;
503 int retval = SSL_select_next_proto(out, outlen, server, server_len,
505 if (retval != OPENSSL_NPN_NEGOTIATED) {
506 VLOG(3) << "SSLContext::selectNextProcolCallback() "
507 << "unable to pick a next protocol.";
508 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
509 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
511 const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
512 if (cipher && ctx->canUseFalseStartWithCipher(cipher)) {
513 SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
517 return SSL_TLSEXT_ERR_OK;
519 #endif // OPENSSL_NPN_NEGOTIATED
521 SSL* SSLContext::createSSL() const {
522 SSL* ssl = SSL_new(ctx_);
523 if (ssl == nullptr) {
524 throw std::runtime_error("SSL_new: " + getErrors());
530 * Match a name with a pattern. The pattern may include wildcard. A single
531 * wildcard "*" can match up to one component in the domain name.
533 * @param host Host name, typically the name of the remote host
534 * @param pattern Name retrieved from certificate
535 * @param size Size of "pattern"
536 * @return True, if "host" matches "pattern". False otherwise.
538 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
541 while (i < size && host[j] != '\0') {
542 if (toupper(pattern[i]) == toupper(host[j])) {
547 if (pattern[i] == '*') {
548 while (host[j] != '.' && host[j] != '\0') {
556 if (i == size && host[j] == '\0') {
562 int SSLContext::passwordCallback(char* password,
566 SSLContext* context = (SSLContext*)data;
567 if (context == nullptr || context->passwordCollector() == nullptr) {
570 std::string userPassword;
571 // call user defined password collector to get password
572 context->passwordCollector()->getPassword(userPassword, size);
573 int length = userPassword.size();
577 strncpy(password, userPassword.c_str(), length);
583 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
584 lockType(inLockType) {
588 if (lockType == SSLContext::LOCK_MUTEX) {
590 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
593 // lockType == LOCK_NONE, no-op
597 if (lockType == SSLContext::LOCK_MUTEX) {
599 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
602 // lockType == LOCK_NONE, no-op
605 SSLContext::SSLLockType lockType;
606 folly::SpinLock spinLock{};
610 // Statics are unsafe in environments that call exit().
611 // If one thread calls exit() while another thread is
612 // references a member of SSLContext, bad things can happen.
613 // SSLContext runs in such environments.
614 // Instead of declaring a static member we "new" the static
615 // member so that it won't be destructed on exit().
616 static std::unique_ptr<SSLLock[]>& locks() {
617 static auto locksInst = new std::unique_ptr<SSLLock[]>();
621 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
622 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
623 return *lockTypesInst;
626 static void callbackLocking(int mode, int n, const char*, int) {
627 if (mode & CRYPTO_LOCK) {
634 static unsigned long callbackThreadID() {
635 return static_cast<unsigned long>(
637 pthread_mach_thread_np(pthread_self())
644 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
645 return new CRYPTO_dynlock_value;
648 static void dyn_lock(int mode,
649 struct CRYPTO_dynlock_value* lock,
651 if (lock != nullptr) {
652 if (mode & CRYPTO_LOCK) {
655 lock->mutex.unlock();
660 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
664 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
665 lockTypes() = inLockTypes;
668 void SSLContext::markInitialized() {
669 std::lock_guard<std::mutex> g(initMutex());
673 void SSLContext::initializeOpenSSL() {
674 std::lock_guard<std::mutex> g(initMutex());
675 initializeOpenSSLLocked();
678 void SSLContext::initializeOpenSSLLocked() {
683 SSL_load_error_strings();
684 ERR_load_crypto_strings();
686 locks().reset(new SSLLock[::CRYPTO_num_locks()]);
687 for (auto it: lockTypes()) {
688 locks()[it.first].lockType = it.second;
690 CRYPTO_set_id_callback(callbackThreadID);
691 CRYPTO_set_locking_callback(callbackLocking);
693 CRYPTO_set_dynlock_create_callback(dyn_create);
694 CRYPTO_set_dynlock_lock_callback(dyn_lock);
695 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
697 #ifdef OPENSSL_NPN_NEGOTIATED
698 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
699 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
704 void SSLContext::cleanupOpenSSL() {
705 std::lock_guard<std::mutex> g(initMutex());
706 cleanupOpenSSLLocked();
709 void SSLContext::cleanupOpenSSLLocked() {
714 CRYPTO_set_id_callback(nullptr);
715 CRYPTO_set_locking_callback(nullptr);
716 CRYPTO_set_dynlock_create_callback(nullptr);
717 CRYPTO_set_dynlock_lock_callback(nullptr);
718 CRYPTO_set_dynlock_destroy_callback(nullptr);
719 CRYPTO_cleanup_all_ex_data();
724 initialized_ = false;
727 void SSLContext::setOptions(long options) {
728 long newOpt = SSL_CTX_set_options(ctx_, options);
729 if ((newOpt & options) != options) {
730 throw std::runtime_error("SSL_CTX_set_options failed");
734 std::string SSLContext::getErrors(int errnoCopy) {
736 unsigned long errorCode;
740 while ((errorCode = ERR_get_error()) != 0) {
741 if (!errors.empty()) {
744 const char* reason = ERR_reason_error_string(errorCode);
745 if (reason == nullptr) {
746 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
751 if (errors.empty()) {
752 errors = "error code: " + folly::to<std::string>(errnoCopy);
758 operator<<(std::ostream& os, const PasswordCollector& collector) {
759 os << collector.describe();
763 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
764 sockaddr_storage* addrStorage,
765 socklen_t* addrLen) {
766 // Grab the ssl idx and then the ssl object so that we can get the peer
767 // name to compare against the ips in the subjectAltName
768 auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
770 reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
771 int fd = SSL_get_fd(ssl);
773 LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
777 *addrLen = sizeof(*addrStorage);
778 if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
779 PLOG(ERROR) << "Unable to get peer name";
782 CHECK(*addrLen <= sizeof(*addrStorage));
786 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
787 const sockaddr* addr,
789 // Try to extract the names within the SAN extension from the certificate
791 reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
792 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
794 if (altNames != nullptr) {
795 sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
798 if (altNames == nullptr) {
799 LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
803 const sockaddr_in* addr4 = nullptr;
804 const sockaddr_in6* addr6 = nullptr;
805 if (addr != nullptr) {
806 if (addr->sa_family == AF_INET) {
807 addr4 = reinterpret_cast<const sockaddr_in*>(addr);
808 } else if (addr->sa_family == AF_INET6) {
809 addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
811 LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
816 for (int i = 0; i < sk_GENERAL_NAME_num(altNames); i++) {
817 auto name = sk_GENERAL_NAME_value(altNames, i);
818 if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
819 // Extra const-ness for paranoia
820 unsigned char const * const rawIpStr = name->d.iPAddress->data;
821 int const rawIpLen = name->d.iPAddress->length;
823 if (rawIpLen == 4 && addr4 != nullptr) {
824 if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
827 } else if (rawIpLen == 16 && addr6 != nullptr) {
828 if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
831 } else if (rawIpLen != 4 && rawIpLen != 16) {
832 LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
837 LOG(WARNING) << "Unable to match client cert against alt name ip";