Cleanup of how we use BIO/BIO_METHODs
[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::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
47                                                   sockaddr_storage* addrStorage,
48                                                   socklen_t* addrLen) {
49   // Grab the ssl idx and then the ssl object so that we can get the peer
50   // name to compare against the ips in the subjectAltName
51   auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
52   auto ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
53   int fd = SSL_get_fd(ssl);
54   if (fd < 0) {
55     LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
56     return false;
57   }
58
59   *addrLen = sizeof(*addrStorage);
60   if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
61     PLOG(ERROR) << "Unable to get peer name";
62     return false;
63   }
64   CHECK(*addrLen <= sizeof(*addrStorage));
65   return true;
66 }
67
68 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
69                                          const sockaddr* addr,
70                                          socklen_t /* addrLen */) {
71   // Try to extract the names within the SAN extension from the certificate
72   auto altNames = reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
73       X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
74   SCOPE_EXIT {
75     if (altNames != nullptr) {
76       sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
77     }
78   };
79   if (altNames == nullptr) {
80     LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
81     return false;
82   }
83
84   const sockaddr_in* addr4 = nullptr;
85   const sockaddr_in6* addr6 = nullptr;
86   if (addr != nullptr) {
87     if (addr->sa_family == AF_INET) {
88       addr4 = reinterpret_cast<const sockaddr_in*>(addr);
89     } else if (addr->sa_family == AF_INET6) {
90       addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
91     } else {
92       LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
93     }
94   }
95
96   for (int i = 0; i < sk_GENERAL_NAME_num(altNames); i++) {
97     auto name = sk_GENERAL_NAME_value(altNames, i);
98     if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
99       // Extra const-ness for paranoia
100       unsigned char const* const rawIpStr = name->d.iPAddress->data;
101       int const rawIpLen = name->d.iPAddress->length;
102
103       if (rawIpLen == 4 && addr4 != nullptr) {
104         if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
105           return true;
106         }
107       } else if (rawIpLen == 16 && addr6 != nullptr) {
108         if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
109           return true;
110         }
111       } else if (rawIpLen != 4 && rawIpLen != 16) {
112         LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
113       }
114     }
115   }
116
117   LOG(WARNING) << "Unable to match client cert against alt name ip";
118   return false;
119 }
120
121 bool OpenSSLUtils::setCustomBioReadMethod(
122     BIO_METHOD* bioMeth,
123     int (*meth)(BIO*, char*, int)) {
124   bool ret = false;
125 #if OPENSSL_IS_110
126   ret = (BIO_meth_set_read(bioMeth, meth) == 1);
127 #elif (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_IS_101 || OPENSSL_IS_102)
128   bioMeth->bread = meth;
129   ret = true;
130 #endif
131
132   return ret;
133 }
134
135 bool OpenSSLUtils::setCustomBioWriteMethod(
136     BIO_METHOD* bioMeth,
137     int (*meth)(BIO*, const char*, int)) {
138   bool ret = false;
139 #if OPENSSL_IS_110
140   ret = (BIO_meth_set_write(bioMeth, meth) == 1);
141 #elif (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_IS_101 || OPENSSL_IS_102)
142   bioMeth->bwrite = meth;
143   ret = true;
144 #endif
145
146   return ret;
147 }
148
149 int OpenSSLUtils::getBioShouldRetryWrite(int r) {
150   int ret = 0;
151 #if defined(OPENSSL_IS_BORINGSSL)
152   ret = boringssl_bio_fd_should_retry(r);
153 #else
154   ret = BIO_sock_should_retry(r);
155 #endif
156   return ret;
157 }
158
159 void OpenSSLUtils::setBioAppData(BIO* b, void* ptr) {
160 #if defined(OPENSSL_IS_BORINGSSL)
161   BIO_set_callback_arg(b, static_cast<char*>(ptr));
162 #else
163   BIO_set_app_data(b, ptr);
164 #endif
165 }
166
167 void* OpenSSLUtils::getBioAppData(BIO* b) {
168 #if defined(OPENSSL_IS_BORINGSSL)
169   return BIO_get_callback_arg(b);
170 #else
171   return BIO_get_app_data(b);
172 #endif
173 }
174
175 void OpenSSLUtils::setCustomBioMethod(BIO* b, BIO_METHOD* meth) {
176 #if defined(OPENSSL_IS_BORINGSSL)
177   b->method = meth;
178 #else
179   BIO_set(b, meth);
180 #endif
181 }
182
183 } // ssl
184 } // folly
185
186 namespace {
187 #if defined(OPENSSL_IS_BORINGSSL)
188
189 static int boringssl_bio_fd_non_fatal_error(int err) {
190   if (
191 #ifdef EWOULDBLOCK
192     err == EWOULDBLOCK ||
193 #endif
194 #ifdef WSAEWOULDBLOCK
195     err == WSAEWOULDBLOCK ||
196 #endif
197 #ifdef ENOTCONN
198     err == ENOTCONN ||
199 #endif
200 #ifdef EINTR
201     err == EINTR ||
202 #endif
203 #ifdef EAGAIN
204     err == EAGAIN ||
205 #endif
206 #ifdef EPROTO
207     err == EPROTO ||
208 #endif
209 #ifdef EINPROGRESS
210     err == EINPROGRESS ||
211 #endif
212 #ifdef EALREADY
213     err == EALREADY ||
214 #endif
215     0) {
216     return 1;
217   }
218   return 0;
219 }
220
221 #if defined(OPENSSL_WINDOWS)
222
223 #include <io.h>
224 #pragma warning(push, 3)
225 #include <windows.h>
226 #pragma warning(pop)
227
228 int boringssl_bio_fd_should_retry(int i) {
229   if (i == -1) {
230     return boringssl_bio_fd_non_fatal_error((int)GetLastError());
231   }
232   return 0;
233 }
234
235 #else // !OPENSSL_WINDOWS
236
237 #include <unistd.h>
238 int boringssl_bio_fd_should_retry(int i) {
239   if (i == -1) {
240     return boringssl_bio_fd_non_fatal_error(errno);
241   }
242   return 0;
243 }
244 #endif // OPENSSL_WINDOWS
245
246 #endif // OEPNSSL_IS_BORINGSSL
247
248 }