Add OpenSSL portability layer
[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/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>
27
28 namespace {
29 #if defined(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);
33 #endif
34
35 }
36
37 namespace folly {
38 namespace ssl {
39
40 bool OpenSSLUtils::getTLSMasterKey(
41     const SSL_SESSION* session,
42     MutableByteRange keyOut) {
43 #if FOLLY_OPENSSL_IS_101 || FOLLY_OPENSSL_IS_102
44   if (session &&
45       session->master_key_length == static_cast<int>(keyOut.size())) {
46     auto masterKey = session->master_key;
47     std::copy(
48         masterKey, masterKey + session->master_key_length, keyOut.begin());
49     return true;
50   }
51 #else
52   (SSL_SESSION*)session;
53   (MutableByteRange) keyOut;
54 #endif
55   return false;
56 }
57
58 bool OpenSSLUtils::getTLSClientRandom(
59     const SSL* ssl,
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());
66     return true;
67   }
68 #else
69   (SSL*)ssl;
70   (MutableByteRange) randomOut;
71 #endif
72   return false;
73 }
74
75 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
76                                                   sockaddr_storage* addrStorage,
77                                                   socklen_t* addrLen) {
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);
83   if (fd < 0) {
84     LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
85     return false;
86   }
87
88   *addrLen = sizeof(*addrStorage);
89   if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
90     PLOG(ERROR) << "Unable to get peer name";
91     return false;
92   }
93   CHECK(*addrLen <= sizeof(*addrStorage));
94   return true;
95 }
96
97 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
98                                          const sockaddr* addr,
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));
103   SCOPE_EXIT {
104     if (altNames != nullptr) {
105       sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
106     }
107   };
108   if (altNames == nullptr) {
109     LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
110     return false;
111   }
112
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);
120     } else {
121       LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
122     }
123   }
124
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       int const rawIpLen = name->d.iPAddress->length;
131
132       if (rawIpLen == 4 && addr4 != nullptr) {
133         if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
134           return true;
135         }
136       } else if (rawIpLen == 16 && addr6 != nullptr) {
137         if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
138           return true;
139         }
140       } else if (rawIpLen != 4 && rawIpLen != 16) {
141         LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
142       }
143     }
144   }
145
146   LOG(WARNING) << "Unable to match client cert against alt name ip";
147   return false;
148 }
149
150 static std::unordered_map<uint16_t, std::string> getOpenSSLCipherNames() {
151   std::unordered_map<uint16_t, std::string> ret;
152   SSL_CTX* ctx = nullptr;
153   SSL* ssl = nullptr;
154
155   const SSL_METHOD* meth = SSLv23_server_method();
156   OpenSSL_add_ssl_algorithms();
157
158   if ((ctx = SSL_CTX_new(meth)) == nullptr) {
159     return ret;
160   }
161   SCOPE_EXIT {
162     SSL_CTX_free(ctx);
163   };
164
165   if ((ssl = SSL_new(ctx)) == nullptr) {
166     return ret;
167   }
168   SCOPE_EXIT {
169     SSL_free(ssl);
170   };
171
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);
181   }
182   return ret;
183 }
184
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());
189
190   const auto& iter = cipherCodeToName.find(cipherCode);
191   if (iter != cipherCodeToName.end()) {
192     return iter->second;
193   } else {
194     static std::string empty("");
195     return empty;
196   }
197 }
198
199 bool OpenSSLUtils::setCustomBioReadMethod(
200     BIO_METHOD* bioMeth,
201     int (*meth)(BIO*, char*, int)) {
202   bool ret = false;
203   ret = (BIO_meth_set_read(bioMeth, meth) == 1);
204   return ret;
205 }
206
207 bool OpenSSLUtils::setCustomBioWriteMethod(
208     BIO_METHOD* bioMeth,
209     int (*meth)(BIO*, const char*, int)) {
210   bool ret = false;
211   ret = (BIO_meth_set_write(bioMeth, meth) == 1);
212   return ret;
213 }
214
215 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
216   int ret = 0;
217 #if defined(OPENSSL_IS_BORINGSSL)
218   ret = boringssl_bio_fd_should_retry(r);
219 #else
220   ret = BIO_sock_should_retry(r);
221 #endif
222   return ret;
223 }
224
225 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
226 #if defined(OPENSSL_IS_BORINGSSL)
227   BIO_set_callback_arg(b, static_cast<char*>(ptr));
228 #else
229   BIO_set_app_data(b, ptr);
230 #endif
231 }
232
233 void* OpenSSLUtils::getBioAppData(BIO* b) {
234 #if defined(OPENSSL_IS_BORINGSSL)
235   return BIO_get_callback_arg(b);
236 #else
237   return BIO_get_app_data(b);
238 #endif
239 }
240
241 void OpenSSLUtils::setCustomBioMethod(BIO* b, BIO_METHOD* meth) {
242 #if defined(OPENSSL_IS_BORINGSSL)
243   b->method = meth;
244 #else
245   BIO_set(b, meth);
246 #endif
247 }
248
249 int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
250 #ifdef _WIN32
251   int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
252   if (fd != nullptr) {
253     *fd = ret;
254   }
255   return ret;
256 #else
257   return BIO_get_fd(b, fd);
258 #endif
259 }
260
261 void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
262 #ifdef _WIN32
263   SOCKET sock = portability::sockets::fd_to_socket(fd);
264 #else
265   int sock = fd;
266 #endif
267   BIO_set_fd(b, sock, flags);
268 }
269
270 } // ssl
271 } // folly
272
273 namespace {
274 #if defined(OPENSSL_IS_BORINGSSL)
275
276 static int boringssl_bio_fd_non_fatal_error(int err) {
277   if (
278 #ifdef EWOULDBLOCK
279     err == EWOULDBLOCK ||
280 #endif
281 #ifdef WSAEWOULDBLOCK
282     err == WSAEWOULDBLOCK ||
283 #endif
284 #ifdef ENOTCONN
285     err == ENOTCONN ||
286 #endif
287 #ifdef EINTR
288     err == EINTR ||
289 #endif
290 #ifdef EAGAIN
291     err == EAGAIN ||
292 #endif
293 #ifdef EPROTO
294     err == EPROTO ||
295 #endif
296 #ifdef EINPROGRESS
297     err == EINPROGRESS ||
298 #endif
299 #ifdef EALREADY
300     err == EALREADY ||
301 #endif
302     0) {
303     return 1;
304   }
305   return 0;
306 }
307
308 #if defined(OPENSSL_WINDOWS)
309
310 #include <io.h>
311 #pragma warning(push, 3)
312 #include <windows.h>
313 #pragma warning(pop)
314
315 int boringssl_bio_fd_should_retry(int i) {
316   if (i == -1) {
317     return boringssl_bio_fd_non_fatal_error((int)GetLastError());
318   }
319   return 0;
320 }
321
322 #else // !OPENSSL_WINDOWS
323
324 #include <unistd.h>
325 int boringssl_bio_fd_should_retry(int i) {
326   if (i == -1) {
327     return boringssl_bio_fd_non_fatal_error(errno);
328   }
329   return 0;
330 }
331 #endif // OPENSSL_WINDOWS
332
333 #endif // OEPNSSL_IS_BORINGSSL
334
335 }