Consistency in namespace-closing comments
[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 #include <folly/portability/Unistd.h>
26
27 namespace {
28 #ifdef OPENSSL_IS_BORINGSSL
29 // BoringSSL doesn't (as of May 2016) export the equivalent
30 // of BIO_sock_should_retry, so this is one way around it :(
31 static int boringssl_bio_fd_should_retry(int err);
32 #endif
33
34 }
35
36 namespace folly {
37 namespace ssl {
38
39 bool OpenSSLUtils::getTLSMasterKey(
40     const SSL_SESSION* session,
41     MutableByteRange keyOut) {
42 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
43   if (session &&
44       session->master_key_length == static_cast<int>(keyOut.size())) {
45     auto masterKey = session->master_key;
46     std::copy(
47         masterKey, masterKey + session->master_key_length, keyOut.begin());
48     return true;
49   }
50 #else
51   (SSL_SESSION*)session;
52   (MutableByteRange) keyOut;
53 #endif
54   return false;
55 }
56
57 bool OpenSSLUtils::getTLSClientRandom(
58     const SSL* ssl,
59     MutableByteRange randomOut) {
60 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
61   if ((SSL_version(ssl) >> 8) == TLS1_VERSION_MAJOR && ssl->s3 &&
62       randomOut.size() == SSL3_RANDOM_SIZE) {
63     auto clientRandom = ssl->s3->client_random;
64     std::copy(clientRandom, clientRandom + SSL3_RANDOM_SIZE, randomOut.begin());
65     return true;
66   }
67 #else
68   (SSL*)ssl;
69   (MutableByteRange) randomOut;
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       size_t const rawIpLen = size_t(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 (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
173     const SSL_CIPHER* c = sk_SSL_CIPHER_value(sk, i);
174     unsigned long id = SSL_CIPHER_get_id(c);
175     // OpenSSL 1.0.2 and prior does weird things such as stuff the SSL/TLS
176     // version into the top 16 bits. Let's ignore those for now. This is
177     // BoringSSL compatible (their id can be cast as uint16_t)
178     uint16_t cipherCode = id & 0xffffL;
179     ret[cipherCode] = SSL_CIPHER_get_name(c);
180   }
181   return ret;
182 }
183
184 const std::string& OpenSSLUtils::getCipherName(uint16_t cipherCode) {
185   // Having this in a hash map saves the binary search inside OpenSSL
186   static std::unordered_map<uint16_t, std::string> cipherCodeToName(
187       getOpenSSLCipherNames());
188
189   const auto& iter = cipherCodeToName.find(cipherCode);
190   if (iter != cipherCodeToName.end()) {
191     return iter->second;
192   } else {
193     static std::string empty("");
194     return empty;
195   }
196 }
197
198 void OpenSSLUtils::setSSLInitialCtx(SSL* ssl, SSL_CTX* ctx) {
199   (void)ssl;
200   (void)ctx;
201 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
202   if (ssl) {
203     if (ctx) {
204       SSL_CTX_up_ref(ctx);
205     }
206     ssl->initial_ctx = ctx;
207   }
208 #endif
209 }
210
211 SSL_CTX* OpenSSLUtils::getSSLInitialCtx(SSL* ssl) {
212   (void)ssl;
213 #if !FOLLY_OPENSSL_IS_110 && !defined(OPENSSL_NO_TLSEXT)
214   if (ssl) {
215     return ssl->initial_ctx;
216   }
217 #endif
218   return nullptr;
219 }
220
221 BioMethodUniquePtr OpenSSLUtils::newSocketBioMethod() {
222   BIO_METHOD* newmeth = nullptr;
223 #if FOLLY_OPENSSL_IS_110
224   if (!(newmeth = BIO_meth_new(BIO_TYPE_SOCKET, "socket_bio_method"))) {
225     return nullptr;
226   }
227   auto meth = const_cast<BIO_METHOD*>(BIO_s_socket());
228   BIO_meth_set_create(newmeth, BIO_meth_get_create(meth));
229   BIO_meth_set_destroy(newmeth, BIO_meth_get_destroy(meth));
230   BIO_meth_set_ctrl(newmeth, BIO_meth_get_ctrl(meth));
231   BIO_meth_set_callback_ctrl(newmeth, BIO_meth_get_callback_ctrl(meth));
232   BIO_meth_set_read(newmeth, BIO_meth_get_read(meth));
233   BIO_meth_set_write(newmeth, BIO_meth_get_write(meth));
234   BIO_meth_set_gets(newmeth, BIO_meth_get_gets(meth));
235   BIO_meth_set_puts(newmeth, BIO_meth_get_puts(meth));
236 #else
237   if (!(newmeth = (BIO_METHOD*)OPENSSL_malloc(sizeof(BIO_METHOD)))) {
238     return nullptr;
239   }
240   memcpy(newmeth, BIO_s_socket(), sizeof(BIO_METHOD));
241 #endif
242
243   return BioMethodUniquePtr(newmeth);
244 }
245
246 bool OpenSSLUtils::setCustomBioReadMethod(
247     BIO_METHOD* bioMeth,
248     int (*meth)(BIO*, char*, int)) {
249   bool ret = false;
250   ret = (BIO_meth_set_read(bioMeth, meth) == 1);
251   return ret;
252 }
253
254 bool OpenSSLUtils::setCustomBioWriteMethod(
255     BIO_METHOD* bioMeth,
256     int (*meth)(BIO*, const char*, int)) {
257   bool ret = false;
258   ret = (BIO_meth_set_write(bioMeth, meth) == 1);
259   return ret;
260 }
261
262 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
263   int ret = 0;
264 #ifdef OPENSSL_IS_BORINGSSL
265   ret = boringssl_bio_fd_should_retry(r);
266 #else
267   ret = BIO_sock_should_retry(r);
268 #endif
269   return ret;
270 }
271
272 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
273 #ifdef OPENSSL_IS_BORINGSSL
274   BIO_set_callback_arg(b, static_cast<char*>(ptr));
275 #else
276   BIO_set_app_data(b, ptr);
277 #endif
278 }
279
280 void* OpenSSLUtils::getBioAppData(BIO* b) {
281 #ifdef OPENSSL_IS_BORINGSSL
282   return BIO_get_callback_arg(b);
283 #else
284   return BIO_get_app_data(b);
285 #endif
286 }
287
288 int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
289 #ifdef _WIN32
290   int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
291   if (fd != nullptr) {
292     *fd = ret;
293   }
294   return ret;
295 #else
296   return BIO_get_fd(b, fd);
297 #endif
298 }
299
300 void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
301 #ifdef _WIN32
302   SOCKET socket = portability::sockets::fd_to_socket(fd);
303   // Internally OpenSSL uses this as an int for reasons completely
304   // beyond any form of sanity, so we do the cast ourselves to avoid
305   // the warnings that would be generated.
306   int sock = int(socket);
307 #else
308   int sock = fd;
309 #endif
310   BIO_set_fd(b, sock, flags);
311 }
312
313 } // namespace ssl
314 } // namespace folly
315
316 namespace {
317 #ifdef OPENSSL_IS_BORINGSSL
318
319 static int boringssl_bio_fd_non_fatal_error(int err) {
320   if (
321 #ifdef EWOULDBLOCK
322     err == EWOULDBLOCK ||
323 #endif
324 #ifdef WSAEWOULDBLOCK
325     err == WSAEWOULDBLOCK ||
326 #endif
327 #ifdef ENOTCONN
328     err == ENOTCONN ||
329 #endif
330 #ifdef EINTR
331     err == EINTR ||
332 #endif
333 #ifdef EAGAIN
334     err == EAGAIN ||
335 #endif
336 #ifdef EPROTO
337     err == EPROTO ||
338 #endif
339 #ifdef EINPROGRESS
340     err == EINPROGRESS ||
341 #endif
342 #ifdef EALREADY
343     err == EALREADY ||
344 #endif
345     0) {
346     return 1;
347   }
348   return 0;
349 }
350
351 #if defined(OPENSSL_WINDOWS)
352
353 int boringssl_bio_fd_should_retry(int i) {
354   if (i == -1) {
355     return boringssl_bio_fd_non_fatal_error((int)GetLastError());
356   }
357   return 0;
358 }
359
360 #else // !OPENSSL_WINDOWS
361
362 int boringssl_bio_fd_should_retry(int i) {
363   if (i == -1) {
364     return boringssl_bio_fd_non_fatal_error(errno);
365   }
366   return 0;
367 }
368 #endif // OPENSSL_WINDOWS
369
370 #endif // OEPNSSL_IS_BORINGSSL
371
372 }