nikoladsp

download cert chain

Aug 9th, 2025
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | Source Code | 0 0
  1. std::vector<std::string> fetchCertChain(const std::string& host, int port) {
  2.       std::vector<std::string> certPaths;
  3.  
  4.       SSL_library_init();
  5.       SSL_load_error_strings();
  6.  
  7.       SSL_CTX* ctx = nullptr;
  8.       SSL* ssl = nullptr;
  9.       BIO* bio = nullptr;
  10.  
  11.       auto cleanup = [&]() {
  12.           if (bio)
  13.             BIO_free_all(bio);
  14.  
  15.           if (ctx)
  16.             SSL_CTX_free(ctx);
  17.       };
  18.  
  19.       const SSL_METHOD* method = TLS_client_method();
  20.       ctx = SSL_CTX_new(method);
  21.  
  22.       bio = BIO_new_ssl_connect(ctx);
  23.       BIO_get_ssl(bio, &ssl);
  24.       SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
  25.  
  26.       std::string target = host + ":" + std::to_string(port);
  27.       const auto pos = target.find("://");
  28.       if (pos != std::string::npos) {
  29.         target.erase(0, pos + 3);
  30.       }
  31.  
  32.       BIO_set_conn_hostname(bio, target.c_str());
  33.  
  34.       if (BIO_do_connect(bio) <= 0) {
  35.         std::cerr << "Connection failed\n";
  36.         cleanup();
  37.         return certPaths;
  38.       }
  39.  
  40.       STACK_OF(X509)* certs = SSL_get_peer_cert_chain(ssl);
  41.       if (!certs) {
  42.         std::cerr << "No cert chain received.\n";
  43.         cleanup();
  44.         return certPaths;
  45.       }
  46.  
  47.       for (int i = 0; i < sk_X509_num(certs); ++i) {
  48.         X509* cert = sk_X509_value(certs, i);
  49. //        X509_NAME* subj = X509_get_subject_name(cert);
  50.         const std::string name = getCertSha1(cert);
  51. //        std::string name = getSubjectField(cert, NID_commonName);
  52. //        if (name.empty())
  53. //          name = getCertSha1(cert);
  54. //        std::cout << "name: " << name << "\n";
  55. //        const std::string name = "cert_" + std::to_string(i) + ".pem";
  56. ////        const std::string name = "cert_" + std::to_string(i) + ".pem";
  57.         const fs::path certPath = getPath() / name;
  58. //        fs::path derPath{certPath};
  59. //        derPath.replace_extension(".der");
  60.         FILE* fp = fopen(certPath.c_str(), "w");
  61.         if (fp) {
  62.           PEM_write_X509(fp, cert);
  63.           fclose(fp);
  64.           certPaths.push_back(certPath);
  65. //          ::convertPemToDer(pemPath, derPath);
  66.           std::cout << "Saved: " << certPath << "\n";
  67.         }
  68.       }
  69.  
  70. //      BIO_free_all(bio);
  71. //      SSL_CTX_free(ctx);
  72.       cleanup();
  73.  
  74.       return certPaths;
  75.     }
Advertisement
Add Comment
Please, Sign In to add comment