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