81bdc1a33e1319524026d8dedb7731cedac88649
[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
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
26 #include <glog/logging.h>
27
28 #define OPENSSL_IS_101 (OPENSSL_VERSION_NUMBER >= 0x1000105fL && \
29                          OPENSSL_VERSION_NUMBER < 0x1000200fL)
30 #define OPENSSL_IS_102 (OPENSSL_VERSION_NUMBER >= 0x1000200fL && \
31                         OPENSSL_VERSION_NUMBER < 0x10100000L)
32 #define OPENSSL_IS_110 (OPENSSL_VERSION_NUMBER >= 0x10100000L)
33
34 namespace {
35 #if defined(OPENSSL_IS_BORINGSSL)
36 // BoringSSL doesn't (as of May 2016) export the equivalent
37 // of BIO_sock_should_retry, so this is one way around it :(
38 static int boringssl_bio_fd_should_retry(int err);
39 #endif
40
41 }
42
43 namespace folly {
44 namespace ssl {
45
46 bool OpenSSLUtils::getTLSMasterKey(
47     const SSL_SESSION* session,
48     MutableByteRange keyOut) {
49 #if OPENSSL_IS_101 || OPENSSL_IS_102
50   if (session &&
51       session->master_key_length == static_cast<int>(keyOut.size())) {
52     auto masterKey = session->master_key;
53     std::copy(
54         masterKey, masterKey + session->master_key_length, keyOut.begin());
55     return true;
56   }
57 #endif
58   return false;
59 }
60
61 bool OpenSSLUtils::getTLSClientRandom(
62     const SSL* ssl,
63     MutableByteRange randomOut) {
64 #if OPENSSL_IS_101 || OPENSSL_IS_102
65   if ((SSL_version(ssl) >> 8) == TLS1_VERSION_MAJOR && ssl->s3 &&
66       randomOut.size() == SSL3_RANDOM_SIZE) {
67     auto clientRandom = ssl->s3->client_random;
68     std::copy(clientRandom, clientRandom + SSL3_RANDOM_SIZE, randomOut.begin());
69     return true;
70   }
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 (int i = 0; i < 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 bool OpenSSLUtils::setCustomBioReadMethod(
151     BIO_METHOD* bioMeth,
152     int (*meth)(BIO*, char*, int)) {
153   bool ret = false;
154 #if OPENSSL_IS_110
155   ret = (BIO_meth_set_read(bioMeth, meth) == 1);
156 #elif (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_IS_101 || OPENSSL_IS_102)
157   bioMeth->bread = meth;
158   ret = true;
159 #endif
160
161   return ret;
162 }
163
164 bool OpenSSLUtils::setCustomBioWriteMethod(
165     BIO_METHOD* bioMeth,
166     int (*meth)(BIO*, const char*, int)) {
167   bool ret = false;
168 #if OPENSSL_IS_110
169   ret = (BIO_meth_set_write(bioMeth, meth) == 1);
170 #elif (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_IS_101 || OPENSSL_IS_102)
171   bioMeth->bwrite = meth;
172   ret = true;
173 #endif
174
175   return ret;
176 }
177
178 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
179   int ret = 0;
180 #if defined(OPENSSL_IS_BORINGSSL)
181   ret = boringssl_bio_fd_should_retry(r);
182 #else
183   ret = BIO_sock_should_retry(r);
184 #endif
185   return ret;
186 }
187
188 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
189 #if defined(OPENSSL_IS_BORINGSSL)
190   BIO_set_callback_arg(b, static_cast<char*>(ptr));
191 #else
192   BIO_set_app_data(b, ptr);
193 #endif
194 }
195
196 void* OpenSSLUtils::getBioAppData(BIO* b) {
197 #if defined(OPENSSL_IS_BORINGSSL)
198   return BIO_get_callback_arg(b);
199 #else
200   return BIO_get_app_data(b);
201 #endif
202 }
203
204 void OpenSSLUtils::setCustomBioMethod(BIO* b, BIO_METHOD* meth) {
205 #if defined(OPENSSL_IS_BORINGSSL)
206   b->method = meth;
207 #else
208   BIO_set(b, meth);
209 #endif
210 }
211
212 int OpenSSLUtils::getBioFd(BIO* b, int* fd) {
213 #ifdef _WIN32
214   int ret = portability::sockets::socket_to_fd((SOCKET)BIO_get_fd(b, fd));
215   if (fd != nullptr) {
216     *fd = ret;
217   }
218   return ret;
219 #else
220   return BIO_get_fd(b, fd);
221 #endif
222 }
223
224 void OpenSSLUtils::setBioFd(BIO* b, int fd, int flags) {
225 #ifdef _WIN32
226   SOCKET sock = portability::sockets::fd_to_socket(fd);
227 #else
228   int sock = fd;
229 #endif
230   BIO_set_fd(b, sock, flags);
231 }
232
233 } // ssl
234 } // folly
235
236 namespace {
237 #if defined(OPENSSL_IS_BORINGSSL)
238
239 static int boringssl_bio_fd_non_fatal_error(int err) {
240   if (
241 #ifdef EWOULDBLOCK
242     err == EWOULDBLOCK ||
243 #endif
244 #ifdef WSAEWOULDBLOCK
245     err == WSAEWOULDBLOCK ||
246 #endif
247 #ifdef ENOTCONN
248     err == ENOTCONN ||
249 #endif
250 #ifdef EINTR
251     err == EINTR ||
252 #endif
253 #ifdef EAGAIN
254     err == EAGAIN ||
255 #endif
256 #ifdef EPROTO
257     err == EPROTO ||
258 #endif
259 #ifdef EINPROGRESS
260     err == EINPROGRESS ||
261 #endif
262 #ifdef EALREADY
263     err == EALREADY ||
264 #endif
265     0) {
266     return 1;
267   }
268   return 0;
269 }
270
271 #if defined(OPENSSL_WINDOWS)
272
273 #include <io.h>
274 #pragma warning(push, 3)
275 #include <windows.h>
276 #pragma warning(pop)
277
278 int boringssl_bio_fd_should_retry(int i) {
279   if (i == -1) {
280     return boringssl_bio_fd_non_fatal_error((int)GetLastError());
281   }
282   return 0;
283 }
284
285 #else // !OPENSSL_WINDOWS
286
287 #include <unistd.h>
288 int boringssl_bio_fd_should_retry(int i) {
289   if (i == -1) {
290     return boringssl_bio_fd_non_fatal_error(errno);
291   }
292   return 0;
293 }
294 #endif // OPENSSL_WINDOWS
295
296 #endif // OEPNSSL_IS_BORINGSSL
297
298 }