blob: 2ef05e4deb3c3098b5ef0f1ed011f1a378b657f3 [file] [log] [blame]
Adrien Béraud612b55b2023-05-29 10:42:04 -04001/*
2 * Copyright (C) 2004-2023 Savoir-faire Linux Inc.
3 *
Adrien Béraudcb753622023-07-17 22:32:49 -04004 * This program is free software: you can redistribute it and/or modify
Adrien Béraud612b55b2023-05-29 10:42:04 -04005 * it under the terms of the GNU General Public License as published by
Adrien Béraudcb753622023-07-17 22:32:49 -04006 * the Free Software Foundation, either version 3 of the License, or
Adrien Béraud612b55b2023-05-29 10:42:04 -04007 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Adrien Béraudcb753622023-07-17 22:32:49 -040011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Adrien Béraud612b55b2023-05-29 10:42:04 -040012 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
Adrien Béraudcb753622023-07-17 22:32:49 -040015 * along with this program. If not, see <https://www.gnu.org/licenses/>.
Adrien Béraud612b55b2023-05-29 10:42:04 -040016 */
Adrien Béraud612b55b2023-05-29 10:42:04 -040017#include "certstore.h"
18#include "security_const.h"
19
20#include "fileutils.h"
21
22#include <opendht/thread_pool.h>
23#include <opendht/logger.h>
24
25#include <gnutls/ocsp.h>
26
27#include <thread>
28#include <sstream>
29#include <fmt/format.h>
30
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040031namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040032namespace tls {
33
34CertificateStore::CertificateStore(const std::string& path, std::shared_ptr<Logger> logger)
35 : logger_(std::move(logger))
36 , certPath_(fmt::format("{}/certificates", path))
37 , crlPath_(fmt::format("{}/crls", path))
38 , ocspPath_(fmt::format("{}/oscp", path))
39{
40 fileutils::check_dir(certPath_.c_str());
41 fileutils::check_dir(crlPath_.c_str());
42 fileutils::check_dir(ocspPath_.c_str());
43 loadLocalCertificates();
44}
45
46unsigned
47CertificateStore::loadLocalCertificates()
48{
49 std::lock_guard<std::mutex> l(lock_);
50
51 auto dir_content = fileutils::readDirectory(certPath_);
52 unsigned n = 0;
53 for (const auto& f : dir_content) {
54 try {
55 auto crt = std::make_shared<crypto::Certificate>(
56 fileutils::loadFile(certPath_ + DIR_SEPARATOR_CH + f));
57 auto id = crt->getId().toString();
58 auto longId = crt->getLongId().toString();
59 if (id != f && longId != f)
60 throw std::logic_error("Certificate id mismatch");
61 while (crt) {
62 id = crt->getId().toString();
63 longId = crt->getLongId().toString();
64 certs_.emplace(std::move(id), crt);
65 certs_.emplace(std::move(longId), crt);
66 loadRevocations(*crt);
67 crt = crt->issuer;
68 ++n;
69 }
70 } catch (const std::exception& e) {
71 if (logger_)
72 logger_->warn("Remove cert. {}", e.what());
73 remove(fmt::format("{}/{}", certPath_, f).c_str());
74 }
75 }
76 if (logger_)
77 logger_->debug("CertificateStore: loaded {} local certificates.", n);
78 return n;
79}
80
81void
82CertificateStore::loadRevocations(crypto::Certificate& crt) const
83{
84 auto dir = fmt::format("{:s}/{:s}", crlPath_, crt.getId().toString());
85 for (const auto& crl : fileutils::readDirectory(dir)) {
86 try {
87 crt.addRevocationList(std::make_shared<crypto::RevocationList>(
88 fileutils::loadFile(fmt::format("{}/{}", dir, crl))));
89 } catch (const std::exception& e) {
90 if (logger_)
91 logger_->warn("Can't load revocation list: %s", e.what());
92 }
93 }
94 auto ocsp_dir = ocspPath_ + DIR_SEPARATOR_CH + crt.getId().toString();
95 for (const auto& ocsp : fileutils::readDirectory(ocsp_dir)) {
96 try {
97 auto ocsp_filepath = fmt::format("{}/{}", ocsp_dir, ocsp);
98 if (logger_) logger_->debug("Found {:s}", ocsp_filepath);
99 auto serial = crt.getSerialNumber();
100 if (dht::toHex(serial.data(), serial.size()) != ocsp)
101 continue;
102 // Save the response
103 auto ocspBlob = fileutils::loadFile(ocsp_filepath);
104 crt.ocspResponse = std::make_shared<dht::crypto::OcspResponse>(ocspBlob.data(),
105 ocspBlob.size());
106 unsigned int status = crt.ocspResponse->getCertificateStatus();
107 if (status == GNUTLS_OCSP_CERT_GOOD) {
108 if (logger_) logger_->debug("Certificate {:s} has good OCSP status", crt.getId());
109 } else if (status == GNUTLS_OCSP_CERT_REVOKED) {
110 if (logger_) logger_->error("Certificate {:s} has revoked OCSP status", crt.getId());
111 } else if (status == GNUTLS_OCSP_CERT_UNKNOWN) {
112 if (logger_) logger_->error("Certificate {:s} has unknown OCSP status", crt.getId());
113 } else {
114 if (logger_) logger_->error("Certificate {:s} has invalid OCSP status", crt.getId());
115 }
116 } catch (const std::exception& e) {
117 if (logger_)
118 logger_->warn("Can't load OCSP revocation status: {:s}", e.what());
119 }
120 }
121}
122
123std::vector<std::string>
124CertificateStore::getPinnedCertificates() const
125{
126 std::lock_guard<std::mutex> l(lock_);
127
128 std::vector<std::string> certIds;
129 certIds.reserve(certs_.size());
130 for (const auto& crt : certs_)
131 certIds.emplace_back(crt.first);
132 return certIds;
133}
134
135std::shared_ptr<crypto::Certificate>
136CertificateStore::getCertificate(const std::string& k)
137{
138 auto getCertificate_ = [this](const std::string& k) -> std::shared_ptr<crypto::Certificate> {
139 auto cit = certs_.find(k);
140 if (cit == certs_.cend())
141 return {};
142 return cit->second;
143 };
144 std::unique_lock<std::mutex> l(lock_);
145 auto crt = getCertificate_(k);
146 // Check if certificate is complete
147 // If the certificate has been splitted, reconstruct it
148 auto top_issuer = crt;
149 while (top_issuer && top_issuer->getUID() != top_issuer->getIssuerUID()) {
150 if (top_issuer->issuer) {
151 top_issuer = top_issuer->issuer;
152 } else if (auto cert = getCertificate_(top_issuer->getIssuerUID())) {
153 top_issuer->issuer = cert;
154 top_issuer = cert;
155 } else {
156 // In this case, a certificate was not found
157 if (logger_)
158 logger_->warn("Incomplete certificate detected {:s}", k);
159 break;
160 }
161 }
162 return crt;
163}
164
165std::shared_ptr<crypto::Certificate>
166CertificateStore::getCertificateLegacy(const std::string& dataDir, const std::string& k)
167{
168 auto oldPath = fmt::format("{}/certificates/{}", dataDir, k);
169 if (fileutils::isFile(oldPath)) {
170 auto crt = std::make_shared<crypto::Certificate>(oldPath);
171 pinCertificate(crt, true);
172 return crt;
173 }
174 return {};
175}
176
177std::shared_ptr<crypto::Certificate>
178CertificateStore::findCertificateByName(const std::string& name, crypto::NameType type) const
179{
180 std::unique_lock<std::mutex> l(lock_);
181 for (auto& i : certs_) {
182 if (i.second->getName() == name)
183 return i.second;
184 if (type != crypto::NameType::UNKNOWN) {
185 for (const auto& alt : i.second->getAltNames())
186 if (alt.first == type and alt.second == name)
187 return i.second;
188 }
189 }
190 return {};
191}
192
193std::shared_ptr<crypto::Certificate>
194CertificateStore::findCertificateByUID(const std::string& uid) const
195{
196 std::unique_lock<std::mutex> l(lock_);
197 for (auto& i : certs_) {
198 if (i.second->getUID() == uid)
199 return i.second;
200 }
201 return {};
202}
203
204std::shared_ptr<crypto::Certificate>
205CertificateStore::findIssuer(const std::shared_ptr<crypto::Certificate>& crt) const
206{
207 std::shared_ptr<crypto::Certificate> ret {};
208 auto n = crt->getIssuerUID();
209 if (not n.empty()) {
210 if (crt->issuer and crt->issuer->getUID() == n)
211 ret = crt->issuer;
212 else
213 ret = findCertificateByUID(n);
214 }
215 if (not ret) {
216 n = crt->getIssuerName();
217 if (not n.empty())
218 ret = findCertificateByName(n);
219 }
220 if (not ret)
221 return ret;
222 unsigned verify_out = 0;
223 int err = gnutls_x509_crt_verify(crt->cert, &ret->cert, 1, 0, &verify_out);
224 if (err != GNUTLS_E_SUCCESS) {
225 if (logger_)
226 logger_->warn("gnutls_x509_crt_verify failed: {:s}", gnutls_strerror(err));
227 return {};
228 }
229 if (verify_out & GNUTLS_CERT_INVALID)
230 return {};
231 return ret;
232}
233
234static std::vector<crypto::Certificate>
235readCertificates(const std::string& path, const std::string& crl_path)
236{
237 std::vector<crypto::Certificate> ret;
238 if (fileutils::isDirectory(path)) {
239 auto files = fileutils::readDirectory(path);
240 for (const auto& file : files) {
241 auto certs = readCertificates(fmt::format("{}/{}", path, file), crl_path);
242 ret.insert(std::end(ret),
243 std::make_move_iterator(std::begin(certs)),
244 std::make_move_iterator(std::end(certs)));
245 }
246 } else {
247 try {
248 auto data = fileutils::loadFile(path);
249 const gnutls_datum_t dt {data.data(), (unsigned) data.size()};
250 gnutls_x509_crt_t* certs {nullptr};
251 unsigned cert_num {0};
252 gnutls_x509_crt_list_import2(&certs, &cert_num, &dt, GNUTLS_X509_FMT_PEM, 0);
253 for (unsigned i = 0; i < cert_num; i++)
254 ret.emplace_back(certs[i]);
255 gnutls_free(certs);
256 } catch (const std::exception& e) {
257 };
258 }
259 return ret;
260}
261
262void
263CertificateStore::pinCertificatePath(const std::string& path,
264 std::function<void(const std::vector<std::string>&)> cb)
265{
266 dht::ThreadPool::computation().run([&, path, cb]() {
267 auto certs = readCertificates(path, crlPath_);
268 std::vector<std::string> ids;
269 std::vector<std::weak_ptr<crypto::Certificate>> scerts;
270 ids.reserve(certs.size());
271 scerts.reserve(certs.size());
272 {
273 std::lock_guard<std::mutex> l(lock_);
274
275 for (auto& cert : certs) {
276 auto shared = std::make_shared<crypto::Certificate>(std::move(cert));
277 scerts.emplace_back(shared);
278 auto e = certs_.emplace(shared->getId().toString(), shared);
279 ids.emplace_back(e.first->first);
280 e = certs_.emplace(shared->getLongId().toString(), shared);
281 ids.emplace_back(e.first->first);
282 }
283 paths_.emplace(path, std::move(scerts));
284 }
285 if (logger_) logger_->d("CertificateStore: loaded %zu certificates from %s.", certs.size(), path.c_str());
286 if (cb)
287 cb(ids);
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400288 //emitSignal<libdhtnet::ConfigurationSignal::CertificatePathPinned>(path, ids);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400289 });
290}
291
292unsigned
293CertificateStore::unpinCertificatePath(const std::string& path)
294{
295 std::lock_guard<std::mutex> l(lock_);
296
297 auto certs = paths_.find(path);
298 if (certs == std::end(paths_))
299 return 0;
300 unsigned n = 0;
301 for (const auto& wcert : certs->second) {
302 if (auto cert = wcert.lock()) {
303 certs_.erase(cert->getId().toString());
304 ++n;
305 }
306 }
307 paths_.erase(certs);
308 return n;
309}
310
311std::vector<std::string>
312CertificateStore::pinCertificate(const std::vector<uint8_t>& cert, bool local) noexcept
313{
314 try {
315 return pinCertificate(crypto::Certificate(cert), local);
316 } catch (const std::exception& e) {
317 }
318 return {};
319}
320
321std::vector<std::string>
322CertificateStore::pinCertificate(crypto::Certificate&& cert, bool local)
323{
324 return pinCertificate(std::make_shared<crypto::Certificate>(std::move(cert)), local);
325}
326
327std::vector<std::string>
328CertificateStore::pinCertificate(const std::shared_ptr<crypto::Certificate>& cert, bool local)
329{
330 bool sig {false};
331 std::vector<std::string> ids {};
332 {
333 auto c = cert;
334 std::lock_guard<std::mutex> l(lock_);
335 while (c) {
336 bool inserted;
337 auto id = c->getId().toString();
338 auto longId = c->getLongId().toString();
339 decltype(certs_)::iterator it;
340 std::tie(it, inserted) = certs_.emplace(id, c);
341 if (not inserted)
342 it->second = c;
343 std::tie(it, inserted) = certs_.emplace(longId, c);
344 if (not inserted)
345 it->second = c;
346 if (local) {
347 for (const auto& crl : c->getRevocationLists())
348 pinRevocationList(id, *crl);
349 }
350 ids.emplace_back(longId);
351 ids.emplace_back(id);
352 c = c->issuer;
353 sig |= inserted;
354 }
355 if (local) {
356 if (sig)
357 fileutils::saveFile(certPath_ + DIR_SEPARATOR_CH + ids.front(), cert->getPacked());
358 }
359 }
360 //for (const auto& id : ids)
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400361 // emitSignal<libdhtnet::ConfigurationSignal::CertificatePinned>(id);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400362 return ids;
363}
364
365bool
366CertificateStore::unpinCertificate(const std::string& id)
367{
368 std::lock_guard<std::mutex> l(lock_);
369
370 certs_.erase(id);
371 return remove((certPath_ + DIR_SEPARATOR_CH + id).c_str()) == 0;
372}
373
374bool
375CertificateStore::setTrustedCertificate(const std::string& id, TrustStatus status)
376{
377 if (status == TrustStatus::TRUSTED) {
378 if (auto crt = getCertificate(id)) {
379 trustedCerts_.emplace_back(crt);
380 return true;
381 }
382 } else {
383 auto tc = std::find_if(trustedCerts_.begin(),
384 trustedCerts_.end(),
385 [&](const std::shared_ptr<crypto::Certificate>& crt) {
386 return crt->getId().toString() == id;
387 });
388 if (tc != trustedCerts_.end()) {
389 trustedCerts_.erase(tc);
390 return true;
391 }
392 }
393 return false;
394}
395
396std::vector<gnutls_x509_crt_t>
397CertificateStore::getTrustedCertificates() const
398{
399 std::vector<gnutls_x509_crt_t> crts;
400 crts.reserve(trustedCerts_.size());
401 for (auto& crt : trustedCerts_)
402 crts.emplace_back(crt->getCopy());
403 return crts;
404}
405
406void
407CertificateStore::pinRevocationList(const std::string& id,
408 const std::shared_ptr<dht::crypto::RevocationList>& crl)
409{
410 try {
411 if (auto c = getCertificate(id))
412 c->addRevocationList(crl);
413 pinRevocationList(id, *crl);
414 } catch (...) {
415 if (logger_)
416 logger_->warn("Can't add revocation list");
417 }
418}
419
420void
421CertificateStore::pinRevocationList(const std::string& id, const dht::crypto::RevocationList& crl)
422{
423 fileutils::check_dir((crlPath_ + DIR_SEPARATOR_CH + id).c_str());
424 fileutils::saveFile(crlPath_ + DIR_SEPARATOR_CH + id + DIR_SEPARATOR_CH
425 + dht::toHex(crl.getNumber()),
426 crl.getPacked());
427}
428
429void
430CertificateStore::pinOcspResponse(const dht::crypto::Certificate& cert)
431{
432 if (not cert.ocspResponse)
433 return;
434 try {
435 cert.ocspResponse->getCertificateStatus();
436 } catch (dht::crypto::CryptoException& e) {
437 if (logger_) logger_->error("Failed to read certificate status of OCSP response: {:s}", e.what());
438 return;
439 }
440 auto id = cert.getId().toString();
441 auto serial = cert.getSerialNumber();
442 auto serialhex = dht::toHex(serial);
443 auto dir = ocspPath_ + DIR_SEPARATOR_CH + id;
444
445 if (auto localCert = getCertificate(id)) {
446 // Update certificate in the local store if relevant
447 if (localCert.get() != &cert && serial == localCert->getSerialNumber()) {
448 if (logger_) logger_->d("Updating OCSP for certificate %s in the local store", id.c_str());
449 localCert->ocspResponse = cert.ocspResponse;
450 }
451 }
452
453 dht::ThreadPool::io().run([l=logger_,
454 path = dir + DIR_SEPARATOR_CH + serialhex,
455 dir = std::move(dir),
456 id = std::move(id),
457 serialhex = std::move(serialhex),
458 ocspResponse = cert.ocspResponse] {
459 if (l) l->d("Saving OCSP Response of device %s with serial %s", id.c_str(), serialhex.c_str());
460 std::lock_guard<std::mutex> lock(fileutils::getFileLock(path));
461 fileutils::check_dir(dir.c_str());
462 fileutils::saveFile(path, ocspResponse->pack());
463 });
464}
465
466TrustStore::PermissionStatus
467TrustStore::statusFromStr(const char* str)
468{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400469 if (!std::strcmp(str, libdhtnet::Certificate::Status::ALLOWED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400470 return PermissionStatus::ALLOWED;
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400471 if (!std::strcmp(str, libdhtnet::Certificate::Status::BANNED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400472 return PermissionStatus::BANNED;
473 return PermissionStatus::UNDEFINED;
474}
475
476const char*
477TrustStore::statusToStr(TrustStore::PermissionStatus s)
478{
479 switch (s) {
480 case PermissionStatus::ALLOWED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400481 return libdhtnet::Certificate::Status::ALLOWED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400482 case PermissionStatus::BANNED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400483 return libdhtnet::Certificate::Status::BANNED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400484 case PermissionStatus::UNDEFINED:
485 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400486 return libdhtnet::Certificate::Status::UNDEFINED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400487 }
488}
489
490TrustStatus
491trustStatusFromStr(const char* str)
492{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400493 if (!std::strcmp(str, libdhtnet::Certificate::TrustStatus::TRUSTED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400494 return TrustStatus::TRUSTED;
495 return TrustStatus::UNTRUSTED;
496}
497
498const char*
499statusToStr(TrustStatus s)
500{
501 switch (s) {
502 case TrustStatus::TRUSTED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400503 return libdhtnet::Certificate::TrustStatus::TRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400504 case TrustStatus::UNTRUSTED:
505 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400506 return libdhtnet::Certificate::TrustStatus::UNTRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400507 }
508}
509
510bool
511TrustStore::addRevocationList(dht::crypto::RevocationList&& crl)
512{
513 allowed_.add(crl);
514 return true;
515}
516
517bool
518TrustStore::setCertificateStatus(const std::string& cert_id,
519 const TrustStore::PermissionStatus status)
520{
521 return setCertificateStatus(nullptr, cert_id, status, false);
522}
523
524bool
525TrustStore::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
526 const TrustStore::PermissionStatus status,
527 bool local)
528{
529 return setCertificateStatus(cert, cert->getId().toString(), status, local);
530}
531
532bool
533TrustStore::setCertificateStatus(std::shared_ptr<crypto::Certificate> cert,
534 const std::string& cert_id,
535 const TrustStore::PermissionStatus status,
536 bool local)
537{
538 if (cert)
539 certStore_.pinCertificate(cert, local);
540 std::lock_guard<std::recursive_mutex> lk(mutex_);
541 updateKnownCerts();
542 bool dirty {false};
543 if (status == PermissionStatus::UNDEFINED) {
544 unknownCertStatus_.erase(cert_id);
545 dirty = certStatus_.erase(cert_id);
546 } else {
547 bool allowed = (status == PermissionStatus::ALLOWED);
548 auto s = certStatus_.find(cert_id);
549 if (s == std::end(certStatus_)) {
550 // Certificate state is currently undefined
551 if (not cert)
552 cert = certStore_.getCertificate(cert_id);
553 if (cert) {
554 unknownCertStatus_.erase(cert_id);
555 auto& crt_status = certStatus_[cert_id];
556 if (not crt_status.first)
557 crt_status.first = cert;
558 crt_status.second.allowed = allowed;
559 setStoreCertStatus(*cert, allowed);
560 } else {
561 // Can't find certificate
562 unknownCertStatus_[cert_id].allowed = allowed;
563 }
564 } else {
565 // Certificate is already allowed or banned
566 if (s->second.second.allowed != allowed) {
567 s->second.second.allowed = allowed;
568 if (allowed) // Certificate is re-added after ban, rebuld needed
569 dirty = true;
570 else
571 allowed_.remove(*s->second.first, false);
572 }
573 }
574 }
575 if (dirty)
576 rebuildTrust();
577 return true;
578}
579
580TrustStore::PermissionStatus
581TrustStore::getCertificateStatus(const std::string& cert_id) const
582{
583 std::lock_guard<std::recursive_mutex> lk(mutex_);
584 auto s = certStatus_.find(cert_id);
585 if (s == std::end(certStatus_)) {
586 auto us = unknownCertStatus_.find(cert_id);
587 if (us == std::end(unknownCertStatus_))
588 return PermissionStatus::UNDEFINED;
589 return us->second.allowed ? PermissionStatus::ALLOWED : PermissionStatus::BANNED;
590 }
591 return s->second.second.allowed ? PermissionStatus::ALLOWED : PermissionStatus::BANNED;
592}
593
594std::vector<std::string>
595TrustStore::getCertificatesByStatus(TrustStore::PermissionStatus status) const
596{
597 std::lock_guard<std::recursive_mutex> lk(mutex_);
598 std::vector<std::string> ret;
599 for (const auto& i : certStatus_)
600 if (i.second.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
601 ret.emplace_back(i.first);
602 for (const auto& i : unknownCertStatus_)
603 if (i.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
604 ret.emplace_back(i.first);
605 return ret;
606}
607
608bool
609TrustStore::isAllowed(const crypto::Certificate& crt, bool allowPublic)
610{
611 // Match by certificate pinning
612 std::lock_guard<std::recursive_mutex> lk(mutex_);
613 bool allowed {allowPublic};
614 for (auto c = &crt; c; c = c->issuer.get()) {
615 auto status = getCertificateStatus(c->getId().toString()); // lock mutex_
616 if (status == PermissionStatus::ALLOWED)
617 allowed = true;
618 else if (status == PermissionStatus::BANNED)
619 return false;
620 }
621
622 // Match by certificate chain
623 updateKnownCerts();
624 auto ret = allowed_.verify(crt);
625 // Unknown issuer (only that) are accepted if allowPublic is true
626 if (not ret
627 and !(allowPublic and ret.result == (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND))) {
628 if (certStore_.logger())
629 certStore_.logger()->warn("%s", ret.toString().c_str());
630 return false;
631 }
632
633 return allowed;
634}
635
636void
637TrustStore::updateKnownCerts()
638{
639 auto i = std::begin(unknownCertStatus_);
640 while (i != std::end(unknownCertStatus_)) {
641 if (auto crt = certStore_.getCertificate(i->first)) {
642 certStatus_.emplace(i->first, std::make_pair(crt, i->second));
643 setStoreCertStatus(*crt, i->second.allowed);
644 i = unknownCertStatus_.erase(i);
645 } else
646 ++i;
647 }
648}
649
650void
651TrustStore::setStoreCertStatus(const crypto::Certificate& crt, bool status)
652{
653 if (status)
654 allowed_.add(crt);
655 else
656 allowed_.remove(crt, false);
657}
658
659void
660TrustStore::rebuildTrust()
661{
662 allowed_ = {};
663 for (const auto& c : certStatus_)
664 setStoreCertStatus(*c.second.first, c.second.second.allowed);
665}
666
667} // namespace tls
Sébastien Blin464bdff2023-07-19 08:02:53 -0400668} // namespace dhtnet