1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
|
/* -*- indent-tabs-mode: nil -*- */
#include "log/cert_checker.h"
#include <glog/logging.h>
#include <openssl/asn1.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <string.h>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "log/cert.h"
#include "log/ct_extensions.h"
#include "util/openssl_scoped_types.h"
#include "util/openssl_util.h" // for LOG_OPENSSL_ERRORS
#include "util/util.h"
using std::move;
using std::multimap;
using std::pair;
using std::string;
using std::unique_ptr;
using std::vector;
using util::ClearOpenSSLErrors;
using util::Status;
using util::StatusOr;
using util::error::Code;
namespace cert_trans {
bool CertChecker::LoadTrustedCertificates(const string& cert_file) {
// A read-only BIO.
ScopedBIO bio_in(BIO_new(BIO_s_file()));
if (!bio_in) {
LOG_OPENSSL_ERRORS(ERROR);
return false;
}
if (BIO_read_filename(bio_in.get(), cert_file.c_str()) <= 0) {
LOG(ERROR) << "Failed to open file " << cert_file << " for reading";
LOG_OPENSSL_ERRORS(ERROR);
return false;
}
return LoadTrustedCertificatesFromBIO(bio_in.get());
}
bool CertChecker::LoadTrustedCertificates(
const vector<string>& trusted_certs) {
string concat_certs;
for (vector<string>::const_iterator it = trusted_certs.begin();
it != trusted_certs.end(); ++it) {
concat_certs.append(*it);
}
// A read-only memory BIO.
ScopedBIO bio_in(BIO_new_mem_buf(
const_cast<void*>(reinterpret_cast<const void*>(concat_certs.c_str())),
-1 /* no length, since null-terminated */));
if (!bio_in) {
LOG_OPENSSL_ERRORS(ERROR);
return false;
}
return LoadTrustedCertificatesFromBIO(bio_in.get());
}
bool CertChecker::LoadTrustedCertificatesFromBIO(BIO* bio_in) {
CHECK_NOTNULL(bio_in);
vector<pair<string, unique_ptr<const Cert>>> certs_to_add;
bool error = false;
// certs_to_add may be empty if no new certs were added, so keep track of
// successfully parsed cert count separately.
size_t cert_count = 0;
while (!error) {
ScopedX509 x509(PEM_read_bio_X509(bio_in, nullptr, nullptr, nullptr));
if (x509) {
// TODO(ekasper): check that the issuing CA cert is temporally valid
// and at least warn if it isn't.
unique_ptr<Cert> cert(Cert::FromX509(move(x509)));
string subject_name;
const StatusOr<bool> is_trusted(IsTrusted(*cert, &subject_name));
if (!is_trusted.ok()) {
error = true;
break;
}
++cert_count;
if (!is_trusted.ValueOrDie()) {
certs_to_add.push_back(make_pair(subject_name, move(cert)));
}
} else {
// See if we reached the end of the file.
auto err = ERR_peek_last_error();
if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
ClearOpenSSLErrors();
break;
} else {
// A real error.
LOG(ERROR) << "Badly encoded certificate file.";
LOG_OPENSSL_ERRORS(WARNING);
error = true;
break;
}
}
}
if (error || !cert_count) {
return false;
}
size_t new_certs = certs_to_add.size();
while (!certs_to_add.empty()) {
trusted_.insert(move(certs_to_add.back()));
certs_to_add.pop_back();
}
LOG(INFO) << "Added " << new_certs << " new certificate(s) to trusted store";
return true;
}
Status CertChecker::CheckCertChain(CertChain* chain) const {
if (!chain || !chain->IsLoaded())
return Status(util::error::INVALID_ARGUMENT, "invalid certificate chain");
// Weed out things that should obviously be precert chains instead.
const StatusOr<bool> has_poison =
chain->LeafCert()->HasCriticalExtension(cert_trans::NID_ctPoison);
if (!has_poison.ok()) {
return Status(util::error::INTERNAL, "internal error");
}
if (has_poison.ValueOrDie()) {
return Status(util::error::INVALID_ARGUMENT,
"precert extension in certificate chain");
}
return CheckIssuerChain(chain);
}
Status CertChecker::CheckIssuerChain(CertChain* chain) const {
if (!chain->RemoveCertsAfterFirstSelfSigned()) {
LOG(ERROR) << "Failed to trim chain";
return Status(util::error::INTERNAL, "failed to trim chain");
}
// Note that it is OK to allow a root cert that is not CA:true
// because we will later check that it is trusted.
Status status = chain->IsValidCaIssuerChainMaybeLegacyRoot();
if (!status.ok()) {
LOG(ERROR) << "Failed to check issuer chain";
return Status(status.CanonicalCode(), "invalid certificate chain");
}
const Status valid_chain(chain->IsValidSignatureChain());
if (!valid_chain.ok()) {
return valid_chain;
}
return GetTrustedCa(chain);
}
Status CertChecker::CheckPreCertChain(PreCertChain* chain,
string* issuer_key_hash,
string* tbs_certificate) const {
if (!chain || !chain->IsLoaded()) {
return Status(util::error::INVALID_ARGUMENT, "invalid certificate chain");
}
const StatusOr<bool> chain_well_formed(chain->IsWellFormed());
if (chain_well_formed.ok() && !chain_well_formed.ValueOrDie()) {
return Status(util::error::INVALID_ARGUMENT, "prechain not well formed");
}
if (!chain_well_formed.ok()) {
LOG(ERROR) << "Failed to check precert chain format";
return Status(util::error::INTERNAL, "internal error");
}
// Check the issuer and signature chain.
// We do not, at this point, concern ourselves with whether the CA
// certificate that issued the precert is a Precertificate Signing
// Certificate (i.e., has restricted Extended Key Usage) or not,
// since this does not influence the validity of the chain. The
// purpose of the EKU is effectively to allow CAs to create an
// intermediate whose scope can be limited to CT precerts only (by
// making this extension critical).
// TODO(ekasper): determine (i.e., ask CAs) if CA:false
// Precertificate Signing Certificates should be tolerated if they
// have the necessary EKU set.
// Preference is "no".
// TODO(pphaneuf): Once Cert::IsWellFormed returns a util::Status,
// remove the braces and re-use the one above.
{
Status status(CheckIssuerChain(chain));
if (!status.ok())
return status;
}
const StatusOr<bool> uses_pre_issuer =
chain->UsesPrecertSigningCertificate();
if (!uses_pre_issuer.ok()) {
return Status(util::error::INTERNAL, "internal error");
}
string key_hash;
if (uses_pre_issuer.ValueOrDie()) {
if (chain->Length() < 3 ||
chain->CertAt(2)->SPKISha256Digest(&key_hash) != util::Status::OK)
return Status(util::error::INTERNAL, "internal error");
} else if (chain->Length() < 2 ||
chain->CertAt(1)->SPKISha256Digest(&key_hash) !=
util::Status::OK) {
return Status(util::error::INTERNAL, "internal error");
}
// A well-formed chain always has a precert.
TbsCertificate tbs(*chain->PreCert());
if (!tbs.IsLoaded() || !tbs.DeleteExtension(cert_trans::NID_ctPoison).ok()) {
return Status(util::error::INTERNAL, "internal error");
}
// If the issuing cert is the special Precert Signing Certificate,
// replace the issuer with the one that will sign the final cert.
// Should always succeed as we've already verified that the chain
// is well-formed.
if (uses_pre_issuer.ValueOrDie() &&
!tbs.CopyIssuerFrom(*chain->PrecertIssuingCert()).ok()) {
return Status(util::error::INTERNAL, "internal error");
}
string der_tbs;
if (!tbs.DerEncoding(&der_tbs).ok()) {
return Status(util::error::INTERNAL,
"could not DER-encode tbs certificate");
}
issuer_key_hash->assign(key_hash);
tbs_certificate->assign(der_tbs);
return Status::OK;
}
Status CertChecker::GetTrustedCa(CertChain* chain) const {
const Cert* subject = chain->LastCert();
if (!subject) {
LOG(ERROR) << "Chain has no valid certs";
return Status(util::error::INTERNAL, "chain has no valid certificate");
}
// Look up issuer from the trusted store.
if (trusted_.empty()) {
LOG(WARNING) << "No trusted certificates loaded";
return Status(util::error::FAILED_PRECONDITION,
"no trusted certificates loaded");
}
string subject_name;
const StatusOr<bool> is_trusted(IsTrusted(*subject, &subject_name));
// Either an error, or true, meaning the last cert is in our trusted
// store. Note the trusted cert need not necessarily be
// self-signed.
if (!is_trusted.ok() || is_trusted.ValueOrDie())
return is_trusted.status();
string issuer_name;
util::Status status = subject->DerEncodedIssuerName(&issuer_name);
if (status != util::Status::OK) {
// Doesn't matter whether the extension doesn't or exist or is corrupt,
// it's still a bad chain
return Status(util::error::INVALID_ARGUMENT, "invalid certificate chain");
}
if (subject_name == issuer_name) {
// Self-signed: no need to scan again.
return Status(util::error::FAILED_PRECONDITION,
"untrusted self-signed certificate");
}
const auto issuer_range(trusted_.equal_range(issuer_name));
const Cert* issuer(nullptr);
for (multimap<string, unique_ptr<const Cert>>::const_iterator it =
issuer_range.first;
it != issuer_range.second; ++it) {
const unique_ptr<const Cert>& issuer_cand(it->second);
StatusOr<bool> signed_by_issuer = subject->IsSignedBy(*issuer_cand);
if (signed_by_issuer.status().CanonicalCode() == Code::UNIMPLEMENTED) {
// If the cert's algorithm is unsupported, then there's no point
// continuing: it's unconditionally invalid.
return Status(util::error::INVALID_ARGUMENT,
"unsupported algorithm in certificate chain");
}
if (!signed_by_issuer.ok()) {
LOG(ERROR) << "Failed to check signature for trusted root";
return Status(util::error::INTERNAL,
"failed to check signature for trusted root");
}
if (signed_by_issuer.ValueOrDie()) {
issuer = issuer_cand.get();
break;
}
}
if (!issuer) {
return Status(util::error::FAILED_PRECONDITION, "unknown root");
}
// Clone creates a new Cert but AddCert takes ownership even if Clone
// failed and the cert can't be added, so we don't have to explicitly
// check for IsLoaded here.
if (!chain->AddCert(issuer->Clone())) {
LOG(ERROR) << "Failed to add trusted root to chain";
return Status(util::error::INTERNAL,
"failed to add trusted root to chain");
}
return Status::OK;
}
StatusOr<bool> CertChecker::IsTrusted(const Cert& cert,
string* subject_name) const {
string cert_name;
util::Status status = cert.DerEncodedSubjectName(&cert_name);
if (status != util::Status::OK) {
// Doesn't matter whether it failed to decode or did not exist
return Status(util::error::INVALID_ARGUMENT, "invalid certificate chain");
}
*subject_name = cert_name;
const auto cand_range(trusted_.equal_range(cert_name));
for (multimap<string, unique_ptr<const Cert>>::const_iterator it(
cand_range.first);
it != cand_range.second; ++it) {
if (cert.IsIdenticalTo(*it->second)) {
return true;
}
}
return false;
}
} // namespace cert_trans
|