2 * Copyright 2017 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.
16 #include <folly/io/async/ssl/OpenSSLUtils.h>
17 #include <folly/ScopeGuard.h>
18 #include <folly/portability/OpenSSL.h>
19 #include <folly/portability/Sockets.h>
20 #include <glog/logging.h>
21 #include <openssl/bio.h>
22 #include <openssl/err.h>
23 #include <openssl/rand.h>
24 #include <openssl/ssl.h>
25 #include <openssl/x509v3.h>
26 #include <unordered_map>
29 #ifdef OPENSSL_IS_BORINGSSL
30 // BoringSSL doesn't (as of May 2016) export the equivalent
31 // of BIO_sock_should_retry, so this is one way around it :(
32 static int boringssl_bio_fd_should_retry(int err);
40 bool OpenSSLUtils::getTLSMasterKey(
41 const SSL_SESSION* session,
42 MutableByteRange keyOut) {
43 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
45 session->master_key_length == static_cast<int>(keyOut.size())) {
46 auto masterKey = session->master_key;
48 masterKey, masterKey + session->master_key_length, keyOut.begin());
52 (SSL_SESSION*)session;
53 (MutableByteRange) keyOut;
58 bool OpenSSLUtils::getTLSClientRandom(
60 MutableByteRange randomOut) {
61 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
62 if ((SSL_version(ssl) >> 8) == TLS1_VERSION_MAJOR && ssl->s3 &&
63 randomOut.size() == SSL3_RANDOM_SIZE) {
64 auto clientRandom = ssl->s3->client_random;
65 std::copy(clientRandom, clientRandom + SSL3_RANDOM_SIZE, randomOut.begin());
70 (MutableByteRange) randomOut;
75 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
76 sockaddr_storage* addrStorage,
78 // Grab the ssl idx and then the ssl object so that we can get the peer
79 // name to compare against the ips in the subjectAltName
80 auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
81 auto ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
82 int fd = SSL_get_fd(ssl);
84 LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
88 *addrLen = sizeof(*addrStorage);
89 if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
90 PLOG(ERROR) << "Unable to get peer name";
93 CHECK(*addrLen <= sizeof(*addrStorage));
97 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
99 socklen_t /* addrLen */) {
100 // Try to extract the names within the SAN extension from the certificate
101 auto altNames = reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
102 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
104 if (altNames != nullptr) {
105 sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
108 if (altNames == nullptr) {
109 LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
113 const sockaddr_in* addr4 = nullptr;
114 const sockaddr_in6* addr6 = nullptr;
115 if (addr != nullptr) {
116 if (addr->sa_family == AF_INET) {
117 addr4 = reinterpret_cast<const sockaddr_in*>(addr);
118 } else if (addr->sa_family == AF_INET6) {
119 addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
121 LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
125 for (size_t i = 0; i < (size_t)sk_GENERAL_NAME_num(altNames); i++) {
126 auto name = sk_GENERAL_NAME_value(altNames, i);
127 if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
128 // Extra const-ness for paranoia
129 unsigned char const* const rawIpStr = name->d.iPAddress->data;
130 size_t const rawIpLen = size_t(name->d.iPAddress->length);
132 if (rawIpLen == 4 && addr4 != nullptr) {
133 if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
136 } else if (rawIpLen == 16 && addr6 != nullptr) {
137 if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
140 } else if (rawIpLen != 4 && rawIpLen != 16) {
141 LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
146 LOG(WARNING) << "Unable to match client cert against alt name ip";
150 static std::unordered_map<uint16_t, std::string> getOpenSSLCipherNames() {
151 std::unordered_map<uint16_t, std::string> ret;
152 SSL_CTX* ctx = nullptr;
155 const SSL_METHOD* meth = SSLv23_server_method();
156 OpenSSL_add_ssl_algorithms();
158 if ((ctx = SSL_CTX_new(meth)) == nullptr) {
165 if ((ssl = SSL_new(ctx)) == nullptr) {
172 STACK_OF(SSL_CIPHER)* sk = SSL_get_ciphers(ssl);
173 for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
174 const SSL_CIPHER* c = sk_SSL_CIPHER_value(sk, i);
175 unsigned long id = SSL_CIPHER_get_id(c);
176 // OpenSSL 1.0.2 and prior does weird things such as stuff the SSL/TLS
177 // version into the top 16 bits. Let's ignore those for now. This is
178 // BoringSSL compatible (their id can be cast as uint16_t)
179 uint16_t cipherCode = id & 0xffffL;
180 ret[cipherCode] = SSL_CIPHER_get_name(c);
185 const std::string& OpenSSLUtils::getCipherName(uint16_t cipherCode) {
186 // Having this in a hash map saves the binary search inside OpenSSL
187 static std::unordered_map<uint16_t, std::string> cipherCodeToName(
188 getOpenSSLCipherNames());
190 const auto& iter = cipherCodeToName.find(cipherCode);
191 if (iter != cipherCodeToName.end()) {
194 static std::string empty("");
199 void OpenSSLUtils::setSSLInitialCtx(SSL* ssl, SSL_CTX* ctx) {
200 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
202 ssl->initial_ctx = ctx;
207 SSL_CTX* OpenSSLUtils::getSSLInitialCtx(SSL* ssl) {
208 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
210 return ssl->initial_ctx;
216 BioMethodUniquePtr OpenSSLUtils::newSocketBioMethod() {
217 BIO_METHOD* newmeth = nullptr;
218 #if FOLLY_OPENSSL_IS_110
219 if (!(newmeth = BIO_meth_new(BIO_TYPE_SOCKET, "socket_bio_method"))) {
222 auto meth = const_cast<BIO_METHOD*>(BIO_s_socket());
223 BIO_meth_set_create(newmeth, BIO_meth_get_create(meth));
224 BIO_meth_set_destroy(newmeth, BIO_meth_get_destroy(meth));
225 BIO_meth_set_ctrl(newmeth, BIO_meth_get_ctrl(meth));
226 BIO_meth_set_callback_ctrl(newmeth, BIO_meth_get_callback_ctrl(meth));
227 BIO_meth_set_read(newmeth, BIO_meth_get_read(meth));
228 BIO_meth_set_write(newmeth, BIO_meth_get_write(meth));
229 BIO_meth_set_gets(newmeth, BIO_meth_get_gets(meth));
230 BIO_meth_set_puts(newmeth, BIO_meth_get_puts(meth));
232 if (!(newmeth = (BIO_METHOD*)OPENSSL_malloc(sizeof(BIO_METHOD)))) {
235 memcpy(newmeth, BIO_s_socket(), sizeof(BIO_METHOD));
238 return BioMethodUniquePtr(newmeth);
241 bool OpenSSLUtils::setCustomBioReadMethod(
243 int (*meth)(BIO*, char*, int)) {
245 ret = (BIO_meth_set_read(bioMeth, meth) == 1);
249 bool OpenSSLUtils::setCustomBioWriteMethod(
251 int (*meth)(BIO*, const char*, int)) {
253 ret = (BIO_meth_set_write(bioMeth, meth) == 1);
257 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
259 #ifdef OPENSSL_IS_BORINGSSL
260 ret = boringssl_bio_fd_should_retry(r);
262 ret = BIO_sock_should_retry(r);
267 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
268 #ifdef OPENSSL_IS_BORINGSSL
269 BIO_set_callback_arg(b, static_cast<char*>(ptr));
271 BIO_set_app_data(b, ptr);
275 void* OpenSSLUtils::getBioAppData(BIO* b) {
276 #ifdef OPENSSL_IS_BORINGSSL
277 return BIO_get_callback_arg(b);
279 return BIO_get_app_data(b);
283 int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
285 int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
291 return BIO_get_fd(b, fd);
295 void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
297 SOCKET socket = portability::sockets::fd_to_socket(fd);
298 // Internally OpenSSL uses this as an int for reasons completely
299 // beyond any form of sanity, so we do the cast ourselves to avoid
300 // the warnings that would be generated.
301 int sock = int(socket);
305 BIO_set_fd(b, sock, flags);
312 #ifdef OPENSSL_IS_BORINGSSL
314 static int boringssl_bio_fd_non_fatal_error(int err) {
317 err == EWOULDBLOCK ||
319 #ifdef WSAEWOULDBLOCK
320 err == WSAEWOULDBLOCK ||
335 err == EINPROGRESS ||
346 #if defined(OPENSSL_WINDOWS)
349 #pragma warning(push, 3)
353 int boringssl_bio_fd_should_retry(int i) {
355 return boringssl_bio_fd_non_fatal_error((int)GetLastError());
360 #else // !OPENSSL_WINDOWS
363 int boringssl_bio_fd_should_retry(int i) {
365 return boringssl_bio_fd_non_fatal_error(errno);
369 #endif // OPENSSL_WINDOWS
371 #endif // OEPNSSL_IS_BORINGSSL