blob: 8bd9236568b3d8c69ba86ac767a9416515121d90 [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
Amnab31c3742023-08-28 13:58:31 -040027#if __has_include(<fmt/std.h>)
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040028#include <fmt/std.h>
Amnab31c3742023-08-28 13:58:31 -040029#else
30#include <fmt/ostream.h>
31#endif
Adrien Béraud612b55b2023-05-29 10:42:04 -040032#include <thread>
33#include <sstream>
34#include <fmt/format.h>
35
Adrien Béraud1ae60aa2023-07-07 09:55:09 -040036namespace dhtnet {
Adrien Béraud612b55b2023-05-29 10:42:04 -040037namespace tls {
38
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040039CertificateStore::CertificateStore(const std::filesystem::path& path, std::shared_ptr<Logger> logger)
Adrien Béraud612b55b2023-05-29 10:42:04 -040040 : logger_(std::move(logger))
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040041 , certPath_(path / "certificates")
42 , crlPath_(path /"crls")
43 , ocspPath_(path /"oscp")
Adrien Béraud612b55b2023-05-29 10:42:04 -040044{
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040045 fileutils::check_dir(certPath_);
46 fileutils::check_dir(crlPath_);
47 fileutils::check_dir(ocspPath_);
Adrien Béraud612b55b2023-05-29 10:42:04 -040048 loadLocalCertificates();
49}
50
51unsigned
52CertificateStore::loadLocalCertificates()
53{
54 std::lock_guard<std::mutex> l(lock_);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040055 if (logger_)
56 logger_->debug("CertificateStore: loading certificates from {}", certPath_);
Adrien Béraud612b55b2023-05-29 10:42:04 -040057
Adrien Béraud612b55b2023-05-29 10:42:04 -040058 unsigned n = 0;
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040059 std::error_code ec;
60 for (const auto& crtPath : std::filesystem::directory_iterator(certPath_, ec)) {
61 const auto& path = crtPath.path();
62 auto fileName = path.filename().string();
Adrien Béraud612b55b2023-05-29 10:42:04 -040063 try {
64 auto crt = std::make_shared<crypto::Certificate>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040065 fileutils::loadFile(crtPath));
Adrien Béraud612b55b2023-05-29 10:42:04 -040066 auto id = crt->getId().toString();
67 auto longId = crt->getLongId().toString();
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040068 if (id != fileName && longId != fileName)
Adrien Béraud612b55b2023-05-29 10:42:04 -040069 throw std::logic_error("Certificate id mismatch");
70 while (crt) {
71 id = crt->getId().toString();
72 longId = crt->getLongId().toString();
73 certs_.emplace(std::move(id), crt);
74 certs_.emplace(std::move(longId), crt);
75 loadRevocations(*crt);
76 crt = crt->issuer;
77 ++n;
78 }
79 } catch (const std::exception& e) {
80 if (logger_)
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040081 logger_->warn("loadLocalCertificates: error loading {}: {}", path, e.what());
82 remove(path);
Adrien Béraud612b55b2023-05-29 10:42:04 -040083 }
84 }
85 if (logger_)
86 logger_->debug("CertificateStore: loaded {} local certificates.", n);
87 return n;
88}
89
90void
91CertificateStore::loadRevocations(crypto::Certificate& crt) const
92{
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040093 std::error_code ec;
94 auto dir = crlPath_ / crt.getId().toString();
95 for (const auto& crl : std::filesystem::directory_iterator(dir, ec)) {
Adrien Béraud612b55b2023-05-29 10:42:04 -040096 try {
97 crt.addRevocationList(std::make_shared<crypto::RevocationList>(
Adrien Béraud2a4e73d2023-08-27 12:53:55 -040098 fileutils::loadFile(crl)));
Adrien Béraud612b55b2023-05-29 10:42:04 -040099 } catch (const std::exception& e) {
100 if (logger_)
101 logger_->warn("Can't load revocation list: %s", e.what());
102 }
103 }
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400104
105 auto ocsp_dir = ocspPath_ / crt.getId().toString();
106 for (const auto& ocsp_filepath : std::filesystem::directory_iterator(ocsp_dir, ec)) {
Adrien Béraud612b55b2023-05-29 10:42:04 -0400107 try {
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400108 auto ocsp = ocsp_filepath.path().filename().string();
109 if (logger_) logger_->debug("Found {}", ocsp_filepath.path());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400110 auto serial = crt.getSerialNumber();
111 if (dht::toHex(serial.data(), serial.size()) != ocsp)
112 continue;
113 // Save the response
114 auto ocspBlob = fileutils::loadFile(ocsp_filepath);
115 crt.ocspResponse = std::make_shared<dht::crypto::OcspResponse>(ocspBlob.data(),
116 ocspBlob.size());
117 unsigned int status = crt.ocspResponse->getCertificateStatus();
118 if (status == GNUTLS_OCSP_CERT_GOOD) {
119 if (logger_) logger_->debug("Certificate {:s} has good OCSP status", crt.getId());
120 } else if (status == GNUTLS_OCSP_CERT_REVOKED) {
121 if (logger_) logger_->error("Certificate {:s} has revoked OCSP status", crt.getId());
122 } else if (status == GNUTLS_OCSP_CERT_UNKNOWN) {
123 if (logger_) logger_->error("Certificate {:s} has unknown OCSP status", crt.getId());
124 } else {
125 if (logger_) logger_->error("Certificate {:s} has invalid OCSP status", crt.getId());
126 }
127 } catch (const std::exception& e) {
128 if (logger_)
129 logger_->warn("Can't load OCSP revocation status: {:s}", e.what());
130 }
131 }
132}
133
134std::vector<std::string>
135CertificateStore::getPinnedCertificates() const
136{
137 std::lock_guard<std::mutex> l(lock_);
138
139 std::vector<std::string> certIds;
140 certIds.reserve(certs_.size());
141 for (const auto& crt : certs_)
142 certIds.emplace_back(crt.first);
143 return certIds;
144}
145
146std::shared_ptr<crypto::Certificate>
147CertificateStore::getCertificate(const std::string& k)
148{
149 auto getCertificate_ = [this](const std::string& k) -> std::shared_ptr<crypto::Certificate> {
150 auto cit = certs_.find(k);
151 if (cit == certs_.cend())
152 return {};
153 return cit->second;
154 };
155 std::unique_lock<std::mutex> l(lock_);
156 auto crt = getCertificate_(k);
157 // Check if certificate is complete
158 // If the certificate has been splitted, reconstruct it
159 auto top_issuer = crt;
160 while (top_issuer && top_issuer->getUID() != top_issuer->getIssuerUID()) {
161 if (top_issuer->issuer) {
162 top_issuer = top_issuer->issuer;
163 } else if (auto cert = getCertificate_(top_issuer->getIssuerUID())) {
164 top_issuer->issuer = cert;
165 top_issuer = cert;
166 } else {
167 // In this case, a certificate was not found
168 if (logger_)
169 logger_->warn("Incomplete certificate detected {:s}", k);
170 break;
171 }
172 }
173 return crt;
174}
175
176std::shared_ptr<crypto::Certificate>
177CertificateStore::getCertificateLegacy(const std::string& dataDir, const std::string& k)
178{
Adrien Béraud8b831a82023-07-21 14:13:06 -0400179 try {
180 auto oldPath = fmt::format("{}/certificates/{}", dataDir, k);
181 if (fileutils::isFile(oldPath)) {
182 auto crt = std::make_shared<crypto::Certificate>(oldPath);
183 pinCertificate(crt, true);
184 return crt;
185 }
186 } catch (const std::exception& e) {
187 if (logger_)
188 logger_->warn("Can't load certificate: {:s}", e.what());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400189 }
190 return {};
191}
192
193std::shared_ptr<crypto::Certificate>
194CertificateStore::findCertificateByName(const std::string& name, crypto::NameType type) const
195{
196 std::unique_lock<std::mutex> l(lock_);
197 for (auto& i : certs_) {
198 if (i.second->getName() == name)
199 return i.second;
200 if (type != crypto::NameType::UNKNOWN) {
201 for (const auto& alt : i.second->getAltNames())
202 if (alt.first == type and alt.second == name)
203 return i.second;
204 }
205 }
206 return {};
207}
208
209std::shared_ptr<crypto::Certificate>
210CertificateStore::findCertificateByUID(const std::string& uid) const
211{
212 std::unique_lock<std::mutex> l(lock_);
213 for (auto& i : certs_) {
214 if (i.second->getUID() == uid)
215 return i.second;
216 }
217 return {};
218}
219
220std::shared_ptr<crypto::Certificate>
221CertificateStore::findIssuer(const std::shared_ptr<crypto::Certificate>& crt) const
222{
223 std::shared_ptr<crypto::Certificate> ret {};
224 auto n = crt->getIssuerUID();
225 if (not n.empty()) {
226 if (crt->issuer and crt->issuer->getUID() == n)
227 ret = crt->issuer;
228 else
229 ret = findCertificateByUID(n);
230 }
231 if (not ret) {
232 n = crt->getIssuerName();
233 if (not n.empty())
234 ret = findCertificateByName(n);
235 }
236 if (not ret)
237 return ret;
238 unsigned verify_out = 0;
239 int err = gnutls_x509_crt_verify(crt->cert, &ret->cert, 1, 0, &verify_out);
240 if (err != GNUTLS_E_SUCCESS) {
241 if (logger_)
242 logger_->warn("gnutls_x509_crt_verify failed: {:s}", gnutls_strerror(err));
243 return {};
244 }
245 if (verify_out & GNUTLS_CERT_INVALID)
246 return {};
247 return ret;
248}
249
250static std::vector<crypto::Certificate>
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400251readCertificates(const std::filesystem::path& path, const std::string& crl_path)
Adrien Béraud612b55b2023-05-29 10:42:04 -0400252{
253 std::vector<crypto::Certificate> ret;
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400254 if (std::filesystem::is_directory(path)) {
Adrien Béraud67a24fc2023-10-13 12:04:59 -0400255 std::error_code ec;
256 for (const auto& file : std::filesystem::directory_iterator(path, ec)) {
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400257 auto certs = readCertificates(file, crl_path);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400258 ret.insert(std::end(ret),
259 std::make_move_iterator(std::begin(certs)),
260 std::make_move_iterator(std::end(certs)));
261 }
262 } else {
263 try {
264 auto data = fileutils::loadFile(path);
265 const gnutls_datum_t dt {data.data(), (unsigned) data.size()};
266 gnutls_x509_crt_t* certs {nullptr};
267 unsigned cert_num {0};
268 gnutls_x509_crt_list_import2(&certs, &cert_num, &dt, GNUTLS_X509_FMT_PEM, 0);
269 for (unsigned i = 0; i < cert_num; i++)
270 ret.emplace_back(certs[i]);
271 gnutls_free(certs);
272 } catch (const std::exception& e) {
273 };
274 }
275 return ret;
276}
277
278void
279CertificateStore::pinCertificatePath(const std::string& path,
280 std::function<void(const std::vector<std::string>&)> cb)
281{
282 dht::ThreadPool::computation().run([&, path, cb]() {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -0300283 auto certs = readCertificates(path, crlPath_.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400284 std::vector<std::string> ids;
285 std::vector<std::weak_ptr<crypto::Certificate>> scerts;
286 ids.reserve(certs.size());
287 scerts.reserve(certs.size());
288 {
289 std::lock_guard<std::mutex> l(lock_);
290
291 for (auto& cert : certs) {
Adrien Béraud8b831a82023-07-21 14:13:06 -0400292 try {
293 auto shared = std::make_shared<crypto::Certificate>(std::move(cert));
294 scerts.emplace_back(shared);
295 auto e = certs_.emplace(shared->getId().toString(), shared);
296 ids.emplace_back(e.first->first);
297 e = certs_.emplace(shared->getLongId().toString(), shared);
298 ids.emplace_back(e.first->first);
299 } catch (const std::exception& e) {
300 if (logger_)
301 logger_->warn("Can't load certificate: {:s}", e.what());
302 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400303 }
304 paths_.emplace(path, std::move(scerts));
305 }
306 if (logger_) logger_->d("CertificateStore: loaded %zu certificates from %s.", certs.size(), path.c_str());
307 if (cb)
308 cb(ids);
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400309 //emitSignal<libdhtnet::ConfigurationSignal::CertificatePathPinned>(path, ids);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400310 });
311}
312
313unsigned
314CertificateStore::unpinCertificatePath(const std::string& path)
315{
316 std::lock_guard<std::mutex> l(lock_);
317
318 auto certs = paths_.find(path);
319 if (certs == std::end(paths_))
320 return 0;
321 unsigned n = 0;
322 for (const auto& wcert : certs->second) {
323 if (auto cert = wcert.lock()) {
324 certs_.erase(cert->getId().toString());
325 ++n;
326 }
327 }
328 paths_.erase(certs);
329 return n;
330}
331
332std::vector<std::string>
333CertificateStore::pinCertificate(const std::vector<uint8_t>& cert, bool local) noexcept
334{
335 try {
336 return pinCertificate(crypto::Certificate(cert), local);
337 } catch (const std::exception& e) {
338 }
339 return {};
340}
341
342std::vector<std::string>
343CertificateStore::pinCertificate(crypto::Certificate&& cert, bool local)
344{
345 return pinCertificate(std::make_shared<crypto::Certificate>(std::move(cert)), local);
346}
347
348std::vector<std::string>
349CertificateStore::pinCertificate(const std::shared_ptr<crypto::Certificate>& cert, bool local)
350{
351 bool sig {false};
352 std::vector<std::string> ids {};
353 {
354 auto c = cert;
355 std::lock_guard<std::mutex> l(lock_);
356 while (c) {
357 bool inserted;
358 auto id = c->getId().toString();
359 auto longId = c->getLongId().toString();
360 decltype(certs_)::iterator it;
361 std::tie(it, inserted) = certs_.emplace(id, c);
362 if (not inserted)
363 it->second = c;
364 std::tie(it, inserted) = certs_.emplace(longId, c);
365 if (not inserted)
366 it->second = c;
367 if (local) {
368 for (const auto& crl : c->getRevocationLists())
369 pinRevocationList(id, *crl);
370 }
371 ids.emplace_back(longId);
372 ids.emplace_back(id);
373 c = c->issuer;
374 sig |= inserted;
375 }
376 if (local) {
377 if (sig)
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400378 fileutils::saveFile(certPath_ / ids.front(), cert->getPacked());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400379 }
380 }
381 //for (const auto& id : ids)
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400382 // emitSignal<libdhtnet::ConfigurationSignal::CertificatePinned>(id);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400383 return ids;
384}
385
386bool
387CertificateStore::unpinCertificate(const std::string& id)
388{
389 std::lock_guard<std::mutex> l(lock_);
390
391 certs_.erase(id);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400392 return remove(certPath_ / id);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400393}
394
395bool
396CertificateStore::setTrustedCertificate(const std::string& id, TrustStatus status)
397{
398 if (status == TrustStatus::TRUSTED) {
399 if (auto crt = getCertificate(id)) {
400 trustedCerts_.emplace_back(crt);
401 return true;
402 }
403 } else {
404 auto tc = std::find_if(trustedCerts_.begin(),
405 trustedCerts_.end(),
406 [&](const std::shared_ptr<crypto::Certificate>& crt) {
407 return crt->getId().toString() == id;
408 });
409 if (tc != trustedCerts_.end()) {
410 trustedCerts_.erase(tc);
411 return true;
412 }
413 }
414 return false;
415}
416
417std::vector<gnutls_x509_crt_t>
418CertificateStore::getTrustedCertificates() const
419{
420 std::vector<gnutls_x509_crt_t> crts;
421 crts.reserve(trustedCerts_.size());
422 for (auto& crt : trustedCerts_)
423 crts.emplace_back(crt->getCopy());
424 return crts;
425}
426
427void
428CertificateStore::pinRevocationList(const std::string& id,
429 const std::shared_ptr<dht::crypto::RevocationList>& crl)
430{
431 try {
432 if (auto c = getCertificate(id))
433 c->addRevocationList(crl);
434 pinRevocationList(id, *crl);
435 } catch (...) {
436 if (logger_)
437 logger_->warn("Can't add revocation list");
438 }
439}
440
441void
442CertificateStore::pinRevocationList(const std::string& id, const dht::crypto::RevocationList& crl)
443{
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400444 fileutils::check_dir(crlPath_ / id);
445 fileutils::saveFile(crlPath_ / id / dht::toHex(crl.getNumber()),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400446 crl.getPacked());
447}
448
449void
450CertificateStore::pinOcspResponse(const dht::crypto::Certificate& cert)
451{
452 if (not cert.ocspResponse)
453 return;
454 try {
455 cert.ocspResponse->getCertificateStatus();
456 } catch (dht::crypto::CryptoException& e) {
457 if (logger_) logger_->error("Failed to read certificate status of OCSP response: {:s}", e.what());
458 return;
459 }
460 auto id = cert.getId().toString();
461 auto serial = cert.getSerialNumber();
462 auto serialhex = dht::toHex(serial);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400463 auto dir = ocspPath_ / id;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400464
465 if (auto localCert = getCertificate(id)) {
466 // Update certificate in the local store if relevant
467 if (localCert.get() != &cert && serial == localCert->getSerialNumber()) {
468 if (logger_) logger_->d("Updating OCSP for certificate %s in the local store", id.c_str());
469 localCert->ocspResponse = cert.ocspResponse;
470 }
471 }
472
473 dht::ThreadPool::io().run([l=logger_,
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400474 path = dir / serialhex,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400475 dir = std::move(dir),
476 id = std::move(id),
477 serialhex = std::move(serialhex),
478 ocspResponse = cert.ocspResponse] {
479 if (l) l->d("Saving OCSP Response of device %s with serial %s", id.c_str(), serialhex.c_str());
480 std::lock_guard<std::mutex> lock(fileutils::getFileLock(path));
481 fileutils::check_dir(dir.c_str());
482 fileutils::saveFile(path, ocspResponse->pack());
483 });
484}
485
486TrustStore::PermissionStatus
487TrustStore::statusFromStr(const char* str)
488{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400489 if (!std::strcmp(str, libdhtnet::Certificate::Status::ALLOWED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400490 return PermissionStatus::ALLOWED;
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400491 if (!std::strcmp(str, libdhtnet::Certificate::Status::BANNED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400492 return PermissionStatus::BANNED;
493 return PermissionStatus::UNDEFINED;
494}
495
496const char*
497TrustStore::statusToStr(TrustStore::PermissionStatus s)
498{
499 switch (s) {
500 case PermissionStatus::ALLOWED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400501 return libdhtnet::Certificate::Status::ALLOWED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400502 case PermissionStatus::BANNED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400503 return libdhtnet::Certificate::Status::BANNED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400504 case PermissionStatus::UNDEFINED:
505 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400506 return libdhtnet::Certificate::Status::UNDEFINED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400507 }
508}
509
510TrustStatus
511trustStatusFromStr(const char* str)
512{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400513 if (!std::strcmp(str, libdhtnet::Certificate::TrustStatus::TRUSTED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400514 return TrustStatus::TRUSTED;
515 return TrustStatus::UNTRUSTED;
516}
517
518const char*
519statusToStr(TrustStatus s)
520{
521 switch (s) {
522 case TrustStatus::TRUSTED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400523 return libdhtnet::Certificate::TrustStatus::TRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400524 case TrustStatus::UNTRUSTED:
525 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400526 return libdhtnet::Certificate::TrustStatus::UNTRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400527 }
528}
529
530bool
531TrustStore::addRevocationList(dht::crypto::RevocationList&& crl)
532{
533 allowed_.add(crl);
534 return true;
535}
536
537bool
538TrustStore::setCertificateStatus(const std::string& cert_id,
539 const TrustStore::PermissionStatus status)
540{
541 return setCertificateStatus(nullptr, cert_id, status, false);
542}
543
544bool
545TrustStore::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
546 const TrustStore::PermissionStatus status,
547 bool local)
548{
549 return setCertificateStatus(cert, cert->getId().toString(), status, local);
550}
551
552bool
553TrustStore::setCertificateStatus(std::shared_ptr<crypto::Certificate> cert,
554 const std::string& cert_id,
555 const TrustStore::PermissionStatus status,
556 bool local)
557{
558 if (cert)
559 certStore_.pinCertificate(cert, local);
560 std::lock_guard<std::recursive_mutex> lk(mutex_);
561 updateKnownCerts();
562 bool dirty {false};
563 if (status == PermissionStatus::UNDEFINED) {
564 unknownCertStatus_.erase(cert_id);
565 dirty = certStatus_.erase(cert_id);
566 } else {
567 bool allowed = (status == PermissionStatus::ALLOWED);
568 auto s = certStatus_.find(cert_id);
569 if (s == std::end(certStatus_)) {
570 // Certificate state is currently undefined
571 if (not cert)
572 cert = certStore_.getCertificate(cert_id);
573 if (cert) {
574 unknownCertStatus_.erase(cert_id);
575 auto& crt_status = certStatus_[cert_id];
576 if (not crt_status.first)
577 crt_status.first = cert;
578 crt_status.second.allowed = allowed;
579 setStoreCertStatus(*cert, allowed);
580 } else {
581 // Can't find certificate
582 unknownCertStatus_[cert_id].allowed = allowed;
583 }
584 } else {
585 // Certificate is already allowed or banned
586 if (s->second.second.allowed != allowed) {
587 s->second.second.allowed = allowed;
588 if (allowed) // Certificate is re-added after ban, rebuld needed
589 dirty = true;
590 else
591 allowed_.remove(*s->second.first, false);
592 }
593 }
594 }
595 if (dirty)
596 rebuildTrust();
597 return true;
598}
599
600TrustStore::PermissionStatus
601TrustStore::getCertificateStatus(const std::string& cert_id) const
602{
603 std::lock_guard<std::recursive_mutex> lk(mutex_);
Sébastien Blin57928252023-08-08 14:22:03 -0400604 auto cert = certStore_.getCertificate(cert_id);
605 if (!cert)
606 return PermissionStatus::UNDEFINED;
Adrien Béraudd8fb8d92023-12-07 10:08:38 -0500607 auto allowed = false;
608 auto found = false;
Sébastien Blin57928252023-08-08 14:22:03 -0400609 while (cert) {
610 auto s = certStatus_.find(cert->getId().toString());
611 if (s != std::end(certStatus_)) {
612 if (!found) {
Adrien Béraudd8fb8d92023-12-07 10:08:38 -0500613 found = true;
614 allowed = true; // we need to find at least a certificate
Sébastien Blin57928252023-08-08 14:22:03 -0400615 }
616 allowed &= s->second.second.allowed;
617 if (!allowed)
618 return PermissionStatus::BANNED;
619 } else {
620 auto us = unknownCertStatus_.find(cert->getId().toString());
621 if (us != std::end(unknownCertStatus_)) {
622 if (!found) {
Adrien Béraudd8fb8d92023-12-07 10:08:38 -0500623 found = true;
624 allowed = true; // we need to find at least a certificate
Sébastien Blin57928252023-08-08 14:22:03 -0400625 }
Adrien Béraudd8fb8d92023-12-07 10:08:38 -0500626 allowed &= us->second.allowed;
627 if (!allowed)
Sébastien Blin57928252023-08-08 14:22:03 -0400628 return PermissionStatus::BANNED;
629 }
630 }
631 if (cert->getUID() == cert->getIssuerUID())
632 break;
633 cert = cert->issuer? cert->issuer : certStore_.getCertificate(cert->getIssuerUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400634 }
Sébastien Blin57928252023-08-08 14:22:03 -0400635
636 return allowed? PermissionStatus::ALLOWED : PermissionStatus::UNDEFINED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400637}
638
639std::vector<std::string>
640TrustStore::getCertificatesByStatus(TrustStore::PermissionStatus status) const
641{
642 std::lock_guard<std::recursive_mutex> lk(mutex_);
643 std::vector<std::string> ret;
644 for (const auto& i : certStatus_)
645 if (i.second.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
646 ret.emplace_back(i.first);
647 for (const auto& i : unknownCertStatus_)
648 if (i.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
649 ret.emplace_back(i.first);
650 return ret;
651}
652
653bool
654TrustStore::isAllowed(const crypto::Certificate& crt, bool allowPublic)
655{
656 // Match by certificate pinning
657 std::lock_guard<std::recursive_mutex> lk(mutex_);
658 bool allowed {allowPublic};
659 for (auto c = &crt; c; c = c->issuer.get()) {
660 auto status = getCertificateStatus(c->getId().toString()); // lock mutex_
661 if (status == PermissionStatus::ALLOWED)
662 allowed = true;
663 else if (status == PermissionStatus::BANNED)
664 return false;
665 }
666
667 // Match by certificate chain
668 updateKnownCerts();
669 auto ret = allowed_.verify(crt);
670 // Unknown issuer (only that) are accepted if allowPublic is true
671 if (not ret
672 and !(allowPublic and ret.result == (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND))) {
673 if (certStore_.logger())
674 certStore_.logger()->warn("%s", ret.toString().c_str());
675 return false;
676 }
677
678 return allowed;
679}
680
681void
682TrustStore::updateKnownCerts()
683{
684 auto i = std::begin(unknownCertStatus_);
685 while (i != std::end(unknownCertStatus_)) {
686 if (auto crt = certStore_.getCertificate(i->first)) {
687 certStatus_.emplace(i->first, std::make_pair(crt, i->second));
688 setStoreCertStatus(*crt, i->second.allowed);
689 i = unknownCertStatus_.erase(i);
690 } else
691 ++i;
692 }
693}
694
695void
696TrustStore::setStoreCertStatus(const crypto::Certificate& crt, bool status)
697{
698 if (status)
699 allowed_.add(crt);
700 else
701 allowed_.remove(crt, false);
702}
703
704void
705TrustStore::rebuildTrust()
706{
707 allowed_ = {};
708 for (const auto& c : certStatus_)
709 setStoreCertStatus(*c.second.first, c.second.second.allowed);
710}
711
712} // namespace tls
Sébastien Blin464bdff2023-07-19 08:02:53 -0400713} // namespace dhtnet