host_name_verification.ipp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // ssl/impl/host_name_verification.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 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 BOOST_ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP
  11. #define BOOST_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 <boost/asio/detail/config.hpp>
  16. #include <cctype>
  17. #include <cstring>
  18. #include <boost/asio/ip/address.hpp>
  19. #include <boost/asio/ssl/host_name_verification.hpp>
  20. #include <boost/asio/ssl/detail/openssl_types.hpp>
  21. #include <boost/asio/detail/push_options.hpp>
  22. namespace boost {
  23. namespace asio {
  24. namespace ssl {
  25. bool host_name_verification::operator()(
  26. bool preverified, verify_context& ctx) const
  27. {
  28. using namespace std; // For memcmp.
  29. // Don't bother looking at certificates that have failed pre-verification.
  30. if (!preverified)
  31. return false;
  32. // We're only interested in checking the certificate at the end of the chain.
  33. int depth = X509_STORE_CTX_get_error_depth(ctx.native_handle());
  34. if (depth > 0)
  35. return true;
  36. // Try converting the host name to an address. If it is an address then we
  37. // need to look for an IP address in the certificate rather than a host name.
  38. boost::system::error_code ec;
  39. ip::address address = ip::make_address(host_, ec);
  40. const bool is_address = !ec;
  41. (void)address;
  42. X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
  43. if (is_address)
  44. {
  45. return X509_check_ip_asc(cert, host_.c_str(), 0) == 1;
  46. }
  47. else
  48. {
  49. char* peername = 0;
  50. const int result = X509_check_host(cert,
  51. host_.c_str(), host_.size(), 0, &peername);
  52. OPENSSL_free(peername);
  53. return result == 1;
  54. }
  55. }
  56. } // namespace ssl
  57. } // namespace asio
  58. } // namespace boost
  59. #include <boost/asio/detail/pop_options.hpp>
  60. #endif // BOOST_ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP