blob: a3d72c9a285ea1bc2980ef6431675b94ee4e7ab4 [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)) {
255 for (const auto& file : std::filesystem::directory_iterator(path)) {
256 auto certs = readCertificates(file, crl_path);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400257 ret.insert(std::end(ret),
258 std::make_move_iterator(std::begin(certs)),
259 std::make_move_iterator(std::end(certs)));
260 }
261 } else {
262 try {
263 auto data = fileutils::loadFile(path);
264 const gnutls_datum_t dt {data.data(), (unsigned) data.size()};
265 gnutls_x509_crt_t* certs {nullptr};
266 unsigned cert_num {0};
267 gnutls_x509_crt_list_import2(&certs, &cert_num, &dt, GNUTLS_X509_FMT_PEM, 0);
268 for (unsigned i = 0; i < cert_num; i++)
269 ret.emplace_back(certs[i]);
270 gnutls_free(certs);
271 } catch (const std::exception& e) {
272 };
273 }
274 return ret;
275}
276
277void
278CertificateStore::pinCertificatePath(const std::string& path,
279 std::function<void(const std::vector<std::string>&)> cb)
280{
281 dht::ThreadPool::computation().run([&, path, cb]() {
Aline Gondim Santos406c0f42023-09-13 12:10:23 -0300282 auto certs = readCertificates(path, crlPath_.string());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400283 std::vector<std::string> ids;
284 std::vector<std::weak_ptr<crypto::Certificate>> scerts;
285 ids.reserve(certs.size());
286 scerts.reserve(certs.size());
287 {
288 std::lock_guard<std::mutex> l(lock_);
289
290 for (auto& cert : certs) {
Adrien Béraud8b831a82023-07-21 14:13:06 -0400291 try {
292 auto shared = std::make_shared<crypto::Certificate>(std::move(cert));
293 scerts.emplace_back(shared);
294 auto e = certs_.emplace(shared->getId().toString(), shared);
295 ids.emplace_back(e.first->first);
296 e = certs_.emplace(shared->getLongId().toString(), shared);
297 ids.emplace_back(e.first->first);
298 } catch (const std::exception& e) {
299 if (logger_)
300 logger_->warn("Can't load certificate: {:s}", e.what());
301 }
Adrien Béraud612b55b2023-05-29 10:42:04 -0400302 }
303 paths_.emplace(path, std::move(scerts));
304 }
305 if (logger_) logger_->d("CertificateStore: loaded %zu certificates from %s.", certs.size(), path.c_str());
306 if (cb)
307 cb(ids);
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400308 //emitSignal<libdhtnet::ConfigurationSignal::CertificatePathPinned>(path, ids);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400309 });
310}
311
312unsigned
313CertificateStore::unpinCertificatePath(const std::string& path)
314{
315 std::lock_guard<std::mutex> l(lock_);
316
317 auto certs = paths_.find(path);
318 if (certs == std::end(paths_))
319 return 0;
320 unsigned n = 0;
321 for (const auto& wcert : certs->second) {
322 if (auto cert = wcert.lock()) {
323 certs_.erase(cert->getId().toString());
324 ++n;
325 }
326 }
327 paths_.erase(certs);
328 return n;
329}
330
331std::vector<std::string>
332CertificateStore::pinCertificate(const std::vector<uint8_t>& cert, bool local) noexcept
333{
334 try {
335 return pinCertificate(crypto::Certificate(cert), local);
336 } catch (const std::exception& e) {
337 }
338 return {};
339}
340
341std::vector<std::string>
342CertificateStore::pinCertificate(crypto::Certificate&& cert, bool local)
343{
344 return pinCertificate(std::make_shared<crypto::Certificate>(std::move(cert)), local);
345}
346
347std::vector<std::string>
348CertificateStore::pinCertificate(const std::shared_ptr<crypto::Certificate>& cert, bool local)
349{
350 bool sig {false};
351 std::vector<std::string> ids {};
352 {
353 auto c = cert;
354 std::lock_guard<std::mutex> l(lock_);
355 while (c) {
356 bool inserted;
357 auto id = c->getId().toString();
358 auto longId = c->getLongId().toString();
359 decltype(certs_)::iterator it;
360 std::tie(it, inserted) = certs_.emplace(id, c);
361 if (not inserted)
362 it->second = c;
363 std::tie(it, inserted) = certs_.emplace(longId, c);
364 if (not inserted)
365 it->second = c;
366 if (local) {
367 for (const auto& crl : c->getRevocationLists())
368 pinRevocationList(id, *crl);
369 }
370 ids.emplace_back(longId);
371 ids.emplace_back(id);
372 c = c->issuer;
373 sig |= inserted;
374 }
375 if (local) {
376 if (sig)
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400377 fileutils::saveFile(certPath_ / ids.front(), cert->getPacked());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400378 }
379 }
380 //for (const auto& id : ids)
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400381 // emitSignal<libdhtnet::ConfigurationSignal::CertificatePinned>(id);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400382 return ids;
383}
384
385bool
386CertificateStore::unpinCertificate(const std::string& id)
387{
388 std::lock_guard<std::mutex> l(lock_);
389
390 certs_.erase(id);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400391 return remove(certPath_ / id);
Adrien Béraud612b55b2023-05-29 10:42:04 -0400392}
393
394bool
395CertificateStore::setTrustedCertificate(const std::string& id, TrustStatus status)
396{
397 if (status == TrustStatus::TRUSTED) {
398 if (auto crt = getCertificate(id)) {
399 trustedCerts_.emplace_back(crt);
400 return true;
401 }
402 } else {
403 auto tc = std::find_if(trustedCerts_.begin(),
404 trustedCerts_.end(),
405 [&](const std::shared_ptr<crypto::Certificate>& crt) {
406 return crt->getId().toString() == id;
407 });
408 if (tc != trustedCerts_.end()) {
409 trustedCerts_.erase(tc);
410 return true;
411 }
412 }
413 return false;
414}
415
416std::vector<gnutls_x509_crt_t>
417CertificateStore::getTrustedCertificates() const
418{
419 std::vector<gnutls_x509_crt_t> crts;
420 crts.reserve(trustedCerts_.size());
421 for (auto& crt : trustedCerts_)
422 crts.emplace_back(crt->getCopy());
423 return crts;
424}
425
426void
427CertificateStore::pinRevocationList(const std::string& id,
428 const std::shared_ptr<dht::crypto::RevocationList>& crl)
429{
430 try {
431 if (auto c = getCertificate(id))
432 c->addRevocationList(crl);
433 pinRevocationList(id, *crl);
434 } catch (...) {
435 if (logger_)
436 logger_->warn("Can't add revocation list");
437 }
438}
439
440void
441CertificateStore::pinRevocationList(const std::string& id, const dht::crypto::RevocationList& crl)
442{
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400443 fileutils::check_dir(crlPath_ / id);
444 fileutils::saveFile(crlPath_ / id / dht::toHex(crl.getNumber()),
Adrien Béraud612b55b2023-05-29 10:42:04 -0400445 crl.getPacked());
446}
447
448void
449CertificateStore::pinOcspResponse(const dht::crypto::Certificate& cert)
450{
451 if (not cert.ocspResponse)
452 return;
453 try {
454 cert.ocspResponse->getCertificateStatus();
455 } catch (dht::crypto::CryptoException& e) {
456 if (logger_) logger_->error("Failed to read certificate status of OCSP response: {:s}", e.what());
457 return;
458 }
459 auto id = cert.getId().toString();
460 auto serial = cert.getSerialNumber();
461 auto serialhex = dht::toHex(serial);
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400462 auto dir = ocspPath_ / id;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400463
464 if (auto localCert = getCertificate(id)) {
465 // Update certificate in the local store if relevant
466 if (localCert.get() != &cert && serial == localCert->getSerialNumber()) {
467 if (logger_) logger_->d("Updating OCSP for certificate %s in the local store", id.c_str());
468 localCert->ocspResponse = cert.ocspResponse;
469 }
470 }
471
472 dht::ThreadPool::io().run([l=logger_,
Adrien Béraud2a4e73d2023-08-27 12:53:55 -0400473 path = dir / serialhex,
Adrien Béraud612b55b2023-05-29 10:42:04 -0400474 dir = std::move(dir),
475 id = std::move(id),
476 serialhex = std::move(serialhex),
477 ocspResponse = cert.ocspResponse] {
478 if (l) l->d("Saving OCSP Response of device %s with serial %s", id.c_str(), serialhex.c_str());
479 std::lock_guard<std::mutex> lock(fileutils::getFileLock(path));
480 fileutils::check_dir(dir.c_str());
481 fileutils::saveFile(path, ocspResponse->pack());
482 });
483}
484
485TrustStore::PermissionStatus
486TrustStore::statusFromStr(const char* str)
487{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400488 if (!std::strcmp(str, libdhtnet::Certificate::Status::ALLOWED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400489 return PermissionStatus::ALLOWED;
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400490 if (!std::strcmp(str, libdhtnet::Certificate::Status::BANNED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400491 return PermissionStatus::BANNED;
492 return PermissionStatus::UNDEFINED;
493}
494
495const char*
496TrustStore::statusToStr(TrustStore::PermissionStatus s)
497{
498 switch (s) {
499 case PermissionStatus::ALLOWED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400500 return libdhtnet::Certificate::Status::ALLOWED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400501 case PermissionStatus::BANNED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400502 return libdhtnet::Certificate::Status::BANNED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400503 case PermissionStatus::UNDEFINED:
504 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400505 return libdhtnet::Certificate::Status::UNDEFINED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400506 }
507}
508
509TrustStatus
510trustStatusFromStr(const char* str)
511{
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400512 if (!std::strcmp(str, libdhtnet::Certificate::TrustStatus::TRUSTED))
Adrien Béraud612b55b2023-05-29 10:42:04 -0400513 return TrustStatus::TRUSTED;
514 return TrustStatus::UNTRUSTED;
515}
516
517const char*
518statusToStr(TrustStatus s)
519{
520 switch (s) {
521 case TrustStatus::TRUSTED:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400522 return libdhtnet::Certificate::TrustStatus::TRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400523 case TrustStatus::UNTRUSTED:
524 default:
Adrien Béraud1ae60aa2023-07-07 09:55:09 -0400525 return libdhtnet::Certificate::TrustStatus::UNTRUSTED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400526 }
527}
528
529bool
530TrustStore::addRevocationList(dht::crypto::RevocationList&& crl)
531{
532 allowed_.add(crl);
533 return true;
534}
535
536bool
537TrustStore::setCertificateStatus(const std::string& cert_id,
538 const TrustStore::PermissionStatus status)
539{
540 return setCertificateStatus(nullptr, cert_id, status, false);
541}
542
543bool
544TrustStore::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert,
545 const TrustStore::PermissionStatus status,
546 bool local)
547{
548 return setCertificateStatus(cert, cert->getId().toString(), status, local);
549}
550
551bool
552TrustStore::setCertificateStatus(std::shared_ptr<crypto::Certificate> cert,
553 const std::string& cert_id,
554 const TrustStore::PermissionStatus status,
555 bool local)
556{
557 if (cert)
558 certStore_.pinCertificate(cert, local);
559 std::lock_guard<std::recursive_mutex> lk(mutex_);
560 updateKnownCerts();
561 bool dirty {false};
562 if (status == PermissionStatus::UNDEFINED) {
563 unknownCertStatus_.erase(cert_id);
564 dirty = certStatus_.erase(cert_id);
565 } else {
566 bool allowed = (status == PermissionStatus::ALLOWED);
567 auto s = certStatus_.find(cert_id);
568 if (s == std::end(certStatus_)) {
569 // Certificate state is currently undefined
570 if (not cert)
571 cert = certStore_.getCertificate(cert_id);
572 if (cert) {
573 unknownCertStatus_.erase(cert_id);
574 auto& crt_status = certStatus_[cert_id];
575 if (not crt_status.first)
576 crt_status.first = cert;
577 crt_status.second.allowed = allowed;
578 setStoreCertStatus(*cert, allowed);
579 } else {
580 // Can't find certificate
581 unknownCertStatus_[cert_id].allowed = allowed;
582 }
583 } else {
584 // Certificate is already allowed or banned
585 if (s->second.second.allowed != allowed) {
586 s->second.second.allowed = allowed;
587 if (allowed) // Certificate is re-added after ban, rebuld needed
588 dirty = true;
589 else
590 allowed_.remove(*s->second.first, false);
591 }
592 }
593 }
594 if (dirty)
595 rebuildTrust();
596 return true;
597}
598
599TrustStore::PermissionStatus
600TrustStore::getCertificateStatus(const std::string& cert_id) const
601{
602 std::lock_guard<std::recursive_mutex> lk(mutex_);
Sébastien Blin57928252023-08-08 14:22:03 -0400603 auto cert = certStore_.getCertificate(cert_id);
604 if (!cert)
605 return PermissionStatus::UNDEFINED;
606 auto allowed = false; auto found = false;
607 while (cert) {
608 auto s = certStatus_.find(cert->getId().toString());
609 if (s != std::end(certStatus_)) {
610 if (!found) {
611 found = true; allowed = true; // we need to find at least a certificate
612 }
613 allowed &= s->second.second.allowed;
614 if (!allowed)
615 return PermissionStatus::BANNED;
616 } else {
617 auto us = unknownCertStatus_.find(cert->getId().toString());
618 if (us != std::end(unknownCertStatus_)) {
619 if (!found) {
620 found = true; allowed = true; // we need to find at least a certificate
621 }
622 allowed &= s->second.second.allowed;
623 if (!us->second.allowed)
624 return PermissionStatus::BANNED;
625 }
626 }
627 if (cert->getUID() == cert->getIssuerUID())
628 break;
629 cert = cert->issuer? cert->issuer : certStore_.getCertificate(cert->getIssuerUID());
Adrien Béraud612b55b2023-05-29 10:42:04 -0400630 }
Sébastien Blin57928252023-08-08 14:22:03 -0400631
632 return allowed? PermissionStatus::ALLOWED : PermissionStatus::UNDEFINED;
Adrien Béraud612b55b2023-05-29 10:42:04 -0400633}
634
635std::vector<std::string>
636TrustStore::getCertificatesByStatus(TrustStore::PermissionStatus status) const
637{
638 std::lock_guard<std::recursive_mutex> lk(mutex_);
639 std::vector<std::string> ret;
640 for (const auto& i : certStatus_)
641 if (i.second.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
642 ret.emplace_back(i.first);
643 for (const auto& i : unknownCertStatus_)
644 if (i.second.allowed == (status == TrustStore::PermissionStatus::ALLOWED))
645 ret.emplace_back(i.first);
646 return ret;
647}
648
649bool
650TrustStore::isAllowed(const crypto::Certificate& crt, bool allowPublic)
651{
652 // Match by certificate pinning
653 std::lock_guard<std::recursive_mutex> lk(mutex_);
654 bool allowed {allowPublic};
655 for (auto c = &crt; c; c = c->issuer.get()) {
656 auto status = getCertificateStatus(c->getId().toString()); // lock mutex_
657 if (status == PermissionStatus::ALLOWED)
658 allowed = true;
659 else if (status == PermissionStatus::BANNED)
660 return false;
661 }
662
663 // Match by certificate chain
664 updateKnownCerts();
665 auto ret = allowed_.verify(crt);
666 // Unknown issuer (only that) are accepted if allowPublic is true
667 if (not ret
668 and !(allowPublic and ret.result == (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND))) {
669 if (certStore_.logger())
670 certStore_.logger()->warn("%s", ret.toString().c_str());
671 return false;
672 }
673
674 return allowed;
675}
676
677void
678TrustStore::updateKnownCerts()
679{
680 auto i = std::begin(unknownCertStatus_);
681 while (i != std::end(unknownCertStatus_)) {
682 if (auto crt = certStore_.getCertificate(i->first)) {
683 certStatus_.emplace(i->first, std::make_pair(crt, i->second));
684 setStoreCertStatus(*crt, i->second.allowed);
685 i = unknownCertStatus_.erase(i);
686 } else
687 ++i;
688 }
689}
690
691void
692TrustStore::setStoreCertStatus(const crypto::Certificate& crt, bool status)
693{
694 if (status)
695 allowed_.add(crt);
696 else
697 allowed_.remove(crt, false);
698}
699
700void
701TrustStore::rebuildTrust()
702{
703 allowed_ = {};
704 for (const auto& c : certStatus_)
705 setStoreCertStatus(*c.second.first, c.second.second.allowed);
706}
707
708} // namespace tls
Sébastien Blin464bdff2023-07-19 08:02:53 -0400709} // namespace dhtnet