OpenSSLUtils.cpp 10 KB

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