host_name_verification.ipp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // ssl/impl/host_name_verification.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP
  11. #define ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include <cctype>
  17. #include <cstring>
  18. #include "asio/ip/address.hpp"
  19. #include "asio/ssl/host_name_verification.hpp"
  20. #include "asio/ssl/detail/openssl_types.hpp"
  21. #include "asio/detail/push_options.hpp"
  22. namespace asio {
  23. namespace ssl {
  24. bool host_name_verification::operator()(
  25. bool preverified, verify_context& ctx) const
  26. {
  27. using namespace std; // For memcmp.
  28. // Don't bother looking at certificates that have failed pre-verification.
  29. if (!preverified)
  30. return false;
  31. // We're only interested in checking the certificate at the end of the chain.
  32. int depth = X509_STORE_CTX_get_error_depth(ctx.native_handle());
  33. if (depth > 0)
  34. return true;
  35. // Try converting the host name to an address. If it is an address then we
  36. // need to look for an IP address in the certificate rather than a host name.
  37. asio::error_code ec;
  38. ip::address address = ip::make_address(host_, ec);
  39. const bool is_address = !ec;
  40. (void)address;
  41. X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
  42. if (is_address)
  43. {
  44. return X509_check_ip_asc(cert, host_.c_str(), 0) == 1;
  45. }
  46. else
  47. {
  48. char* peername = 0;
  49. const int result = X509_check_host(cert,
  50. host_.c_str(), host_.size(), 0, &peername);
  51. OPENSSL_free(peername);
  52. return result == 1;
  53. }
  54. }
  55. } // namespace ssl
  56. } // namespace asio
  57. #include "asio/detail/pop_options.hpp"
  58. #endif // ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP