3#include <openssl/ssl.h>
4#include <openssl/x509_vfy.h>
9#include "absl/status/status.h"
10#include "absl/strings/str_cat.h"
11#include "asio/ip/address.hpp"
12#include "asio/ssl/verify_mode.hpp"
18absl::Status LoadError(
const std::string& path,
const std::error_code& error) {
19 return absl::FailedPreconditionError(
20 absl::StrCat(
"couldn't load ", path,
": ", error.message(),
21 ". scripts/certificates.sh makes them."));
26absl::StatusOr<asio::ssl::context>
ServerTls(
const std::string& certificate,
27 const std::string& key) {
28 asio::ssl::context tls(asio::ssl::context::tlsv13_server);
29 std::error_code error;
30 tls.use_certificate_chain_file(certificate, error);
32 return LoadError(certificate, error);
34 tls.use_private_key_file(key, asio::ssl::context::pem, error);
36 return LoadError(key, error);
41absl::StatusOr<asio::ssl::context>
ClientTls(
const std::string& authority) {
42 asio::ssl::context tls(asio::ssl::context::tlsv13_client);
43 std::error_code error;
44 tls.load_verify_file(authority, error);
46 return LoadError(authority, error);
48 tls.set_verify_mode(asio::ssl::verify_peer);
54 X509_VERIFY_PARAM* check = SSL_get0_param(stream.native_handle());
55 std::error_code not_an_address;
56 asio::ip::make_address(host, not_an_address);
58 X509_VERIFY_PARAM_set1_host(check, host.c_str(), host.size());
60 X509_VERIFY_PARAM_set1_ip_asc(check, host.c_str());
65 const std::error_code& error) {
66 switch (SSL_get_verify_result(stream.native_handle())) {
67 case X509_V_ERR_HOSTNAME_MISMATCH:
68 case X509_V_ERR_IP_ADDRESS_MISMATCH:
69 return absl::StrCat(
"its certificate doesn't name ", host,
70 ". On the server, make it again with "
71 "scripts/certificates.sh tls ",
72 host,
", and start the servers again");
75 case X509_V_ERR_CERT_SIGNATURE_FAILURE:
76 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
77 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
78 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
79 return "its certificate isn't from the authority we trust. Copy the "
80 "server's tls/ca.crt here, or set NANOMMO_TLS_CA to where it is";
81 case X509_V_ERR_CERT_HAS_EXPIRED:
82 return "its certificate has expired. On the server, make new ones with "
83 "scripts/certificates.sh";
85 return error.message();
std::string HandshakeError(TlsStream &stream, const std::string &host, const std::error_code &error)
Why a client's handshake with host failed, and what to do about it.
asio::ssl::stream< asio::ip::tcp::socket > TlsStream
absl::StatusOr< asio::ssl::context > ServerTls(const std::string &certificate, const std::string &key)
absl::StatusOr< asio::ssl::context > ClientTls(const std::string &authority)
void ExpectName(TlsStream &stream, const std::string &host)