67cc119727519271c6938159081b7db24b7e8ced
[folly.git] / folly / io / async / ssl / OpenSSLUtils.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
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 <folly/io/async/ssl/OpenSSLUtils.h>
18
19 #include <glog/logging.h>
20
21 #include <unordered_map>
22
23 #include <folly/ScopeGuard.h>
24 #include <folly/portability/Sockets.h>
25
26 namespace {
27 #ifdef OPENSSL_IS_BORINGSSL
28 // BoringSSL doesn't (as of May 2016) export the equivalent
29 // of BIO_sock_should_retry, so this is one way around it :(
30 static int boringssl_bio_fd_should_retry(int err);
31 #endif
32
33 }
34
35 namespace folly {
36 namespace ssl {
37
38 bool OpenSSLUtils::getTLSMasterKey(
39     const SSL_SESSION* session,
40     MutableByteRange keyOut) {
41 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
42   if (session &&
43       session->master_key_length == static_cast<int>(keyOut.size())) {
44     auto masterKey = session->master_key;
45     std::copy(
46         masterKey, masterKey + session->master_key_length, keyOut.begin());
47     return true;
48   }
49 #else
50   (SSL_SESSION*)session;
51   (MutableByteRange) keyOut;
52 #endif
53   return false;
54 }
55
56 bool OpenSSLUtils::getTLSClientRandom(
57     const SSL* ssl,
58     MutableByteRange randomOut) {
59 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
60   if ((SSL_version(ssl) >> 8) == TLS1_VERSION_MAJOR && ssl->s3 &&
61       randomOut.size() == SSL3_RANDOM_SIZE) {
62     auto clientRandom = ssl->s3->client_random;
63     std::copy(clientRandom, clientRandom + SSL3_RANDOM_SIZE, randomOut.begin());
64     return true;
65   }
66 #else
67   (SSL*)ssl;
68   (MutableByteRange) randomOut;
69 #endif
70   return false;
71 }
72
73 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
74                                                   sockaddr_storage* addrStorage,
75                                                   socklen_t* addrLen) {
76   // Grab the ssl idx and then the ssl object so that we can get the peer
77   // name to compare against the ips in the subjectAltName
78   auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
79   auto ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
80   int fd = SSL_get_fd(ssl);
81   if (fd < 0) {
82     LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
83     return false;
84   }
85
86   *addrLen = sizeof(*addrStorage);
87   if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
88     PLOG(ERROR) << "Unable to get peer name";
89     return false;
90   }
91   CHECK(*addrLen <= sizeof(*addrStorage));
92   return true;
93 }
94
95 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
96                                          const sockaddr* addr,
97                                          socklen_t /* addrLen */) {
98   // Try to extract the names within the SAN extension from the certificate
99   auto altNames = reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
100       X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
101   SCOPE_EXIT {
102     if (altNames != nullptr) {
103       sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
104     }
105   };
106   if (altNames == nullptr) {
107     LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
108     return false;
109   }
110
111   const sockaddr_in* addr4 = nullptr;
112   const sockaddr_in6* addr6 = nullptr;
113   if (addr != nullptr) {
114     if (addr->sa_family == AF_INET) {
115       addr4 = reinterpret_cast<const sockaddr_in*>(addr);
116     } else if (addr->sa_family == AF_INET6) {
117       addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
118     } else {
119       LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
120     }
121   }
122
123   for (size_t i = 0; i < (size_t)sk_GENERAL_NAME_num(altNames); i++) {
124     auto name = sk_GENERAL_NAME_value(altNames, i);
125     if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
126       // Extra const-ness for paranoia
127       unsigned char const* const rawIpStr = name->d.iPAddress->data;
128       size_t const rawIpLen = size_t(name->d.iPAddress->length);
129
130       if (rawIpLen == 4 && addr4 != nullptr) {
131         if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
132           return true;
133         }
134       } else if (rawIpLen == 16 && addr6 != nullptr) {
135         if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
136           return true;
137         }
138       } else if (rawIpLen != 4 && rawIpLen != 16) {
139         LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
140       }
141     }
142   }
143
144   LOG(WARNING) << "Unable to match client cert against alt name ip";
145   return false;
146 }
147
148 static std::unordered_map<uint16_t, std::string> getOpenSSLCipherNames() {
149   std::unordered_map<uint16_t, std::string> ret;
150   SSL_CTX* ctx = nullptr;
151   SSL* ssl = nullptr;
152
153   const SSL_METHOD* meth = SSLv23_server_method();
154   OpenSSL_add_ssl_algorithms();
155
156   if ((ctx = SSL_CTX_new(meth)) == nullptr) {
157     return ret;
158   }
159   SCOPE_EXIT {
160     SSL_CTX_free(ctx);
161   };
162
163   if ((ssl = SSL_new(ctx)) == nullptr) {
164     return ret;
165   }
166   SCOPE_EXIT {
167     SSL_free(ssl);
168   };
169
170   STACK_OF(SSL_CIPHER)* sk = SSL_get_ciphers(ssl);
171   for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
172     const SSL_CIPHER* c = sk_SSL_CIPHER_value(sk, i);
173     unsigned long id = SSL_CIPHER_get_id(c);
174     // OpenSSL 1.0.2 and prior does weird things such as stuff the SSL/TLS
175     // version into the top 16 bits. Let's ignore those for now. This is
176     // BoringSSL compatible (their id can be cast as uint16_t)
177     uint16_t cipherCode = id & 0xffffL;
178     ret[cipherCode] = SSL_CIPHER_get_name(c);
179   }
180   return ret;
181 }
182
183 const std::string& OpenSSLUtils::getCipherName(uint16_t cipherCode) {
184   // Having this in a hash map saves the binary search inside OpenSSL
185   static std::unordered_map<uint16_t, std::string> cipherCodeToName(
186       getOpenSSLCipherNames());
187
188   const auto& iter = cipherCodeToName.find(cipherCode);
189   if (iter != cipherCodeToName.end()) {
190     return iter->second;
191   } else {
192     static std::string empty("");
193     return empty;
194   }
195 }
196
197 void OpenSSLUtils::setSSLInitialCtx(SSL* ssl, SSL_CTX* ctx) {
198 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
199   if (ssl) {
200     ssl->initial_ctx = ctx;
201   }
202 #endif
203 }
204
205 SSL_CTX* OpenSSLUtils::getSSLInitialCtx(SSL* ssl) {
206 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
207   if (ssl) {
208     return ssl->initial_ctx;
209   }
210 #endif
211   return nullptr;
212 }
213
214 BioMethodUniquePtr OpenSSLUtils::newSocketBioMethod() {
215   BIO_METHOD* newmeth = nullptr;
216 #if FOLLY_OPENSSL_IS_110
217   if (!(newmeth = BIO_meth_new(BIO_TYPE_SOCKET, "socket_bio_method"))) {
218     return nullptr;
219   }
220   auto meth = const_cast<BIO_METHOD*>(BIO_s_socket());
221   BIO_meth_set_create(newmeth, BIO_meth_get_create(meth));
222   BIO_meth_set_destroy(newmeth, BIO_meth_get_destroy(meth));
223   BIO_meth_set_ctrl(newmeth, BIO_meth_get_ctrl(meth));
224   BIO_meth_set_callback_ctrl(newmeth, BIO_meth_get_callback_ctrl(meth));
225   BIO_meth_set_read(newmeth, BIO_meth_get_read(meth));
226   BIO_meth_set_write(newmeth, BIO_meth_get_write(meth));
227   BIO_meth_set_gets(newmeth, BIO_meth_get_gets(meth));
228   BIO_meth_set_puts(newmeth, BIO_meth_get_puts(meth));
229 #else
230   if (!(newmeth = (BIO_METHOD*)OPENSSL_malloc(sizeof(BIO_METHOD)))) {
231     return nullptr;
232   }
233   memcpy(newmeth, BIO_s_socket(), sizeof(BIO_METHOD));
234 #endif
235
236   return BioMethodUniquePtr(newmeth);
237 }
238
239 bool OpenSSLUtils::setCustomBioReadMethod(
240     BIO_METHOD* bioMeth,
241     int (*meth)(BIO*, char*, int)) {
242   bool ret = false;
243   ret = (BIO_meth_set_read(bioMeth, meth) == 1);
244   return ret;
245 }
246
247 bool OpenSSLUtils::setCustomBioWriteMethod(
248     BIO_METHOD* bioMeth,
249     int (*meth)(BIO*, const char*, int)) {
250   bool ret = false;
251   ret = (BIO_meth_set_write(bioMeth, meth) == 1);
252   return ret;
253 }
254
255 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
256   int ret = 0;
257 #ifdef OPENSSL_IS_BORINGSSL
258   ret = boringssl_bio_fd_should_retry(r);
259 #else
260   ret = BIO_sock_should_retry(r);
261 #endif
262   return ret;
263 }
264
265 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
266 #ifdef OPENSSL_IS_BORINGSSL
267   BIO_set_callback_arg(b, static_cast<char*>(ptr));
268 #else
269   BIO_set_app_data(b, ptr);
270 #endif
271 }
272
273 void* OpenSSLUtils::getBioAppData(BIO* b) {
274 #ifdef OPENSSL_IS_BORINGSSL
275   return BIO_get_callback_arg(b);
276 #else
277   return BIO_get_app_data(b);
278 #endif
279 }
280
281 int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
282 #ifdef _WIN32
283   int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
284   if (fd != nullptr) {
285     *fd = ret;
286   }
287   return ret;
288 #else
289   return BIO_get_fd(b, fd);
290 #endif
291 }
292
293 void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
294 #ifdef _WIN32
295   SOCKET socket = portability::sockets::fd_to_socket(fd);
296   // Internally OpenSSL uses this as an int for reasons completely
297   // beyond any form of sanity, so we do the cast ourselves to avoid
298   // the warnings that would be generated.
299   int sock = int(socket);
300 #else
301   int sock = fd;
302 #endif
303   BIO_set_fd(b, sock, flags);
304 }
305
306 } // ssl
307 } // folly
308
309 namespace {
310 #ifdef OPENSSL_IS_BORINGSSL
311
312 static int boringssl_bio_fd_non_fatal_error(int err) {
313   if (
314 #ifdef EWOULDBLOCK
315     err == EWOULDBLOCK ||
316 #endif
317 #ifdef WSAEWOULDBLOCK
318     err == WSAEWOULDBLOCK ||
319 #endif
320 #ifdef ENOTCONN
321     err == ENOTCONN ||
322 #endif
323 #ifdef EINTR
324     err == EINTR ||
325 #endif
326 #ifdef EAGAIN
327     err == EAGAIN ||
328 #endif
329 #ifdef EPROTO
330     err == EPROTO ||
331 #endif
332 #ifdef EINPROGRESS
333     err == EINPROGRESS ||
334 #endif
335 #ifdef EALREADY
336     err == EALREADY ||
337 #endif
338     0) {
339     return 1;
340   }
341   return 0;
342 }
343
344 #if defined(OPENSSL_WINDOWS)
345
346 #include <io.h>
347 #pragma warning(push, 3)
348 #include <windows.h>
349 #pragma warning(pop)
350
351 int boringssl_bio_fd_should_retry(int i) {
352   if (i == -1) {
353     return boringssl_bio_fd_non_fatal_error((int)GetLastError());
354   }
355   return 0;
356 }
357
358 #else // !OPENSSL_WINDOWS
359
360 #include <unistd.h>
361 int boringssl_bio_fd_should_retry(int i) {
362   if (i == -1) {
363     return boringssl_bio_fd_non_fatal_error(errno);
364   }
365   return 0;
366 }
367 #endif // OPENSSL_WINDOWS
368
369 #endif // OEPNSSL_IS_BORINGSSL
370
371 }