1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_CERT_X509_CERTIFICATE_H_ 6 #define NET_CERT_X509_CERTIFICATE_H_ 7 8 #include <string.h> 9 10 #include <string> 11 #include <vector> 12 13 #include "base/gtest_prod_util.h" 14 #include "base/memory/ref_counted.h" 15 #include "base/strings/string_piece.h" 16 #include "base/time/time.h" 17 #include "net/base/net_export.h" 18 #include "net/cert/cert_type.h" 19 #include "net/cert/x509_cert_types.h" 20 21 #if defined(OS_WIN) 22 #include <windows.h> 23 #include <wincrypt.h> 24 #elif defined(OS_MACOSX) 25 #include <CoreFoundation/CFArray.h> 26 #include <Security/SecBase.h> 27 28 #elif defined(USE_OPENSSL_CERTS) 29 // Forward declaration; real one in <x509.h> 30 typedef struct x509_st X509; 31 typedef struct x509_store_st X509_STORE; 32 #elif defined(USE_NSS) 33 // Forward declaration; real one in <cert.h> 34 struct CERTCertificateStr; 35 #endif 36 37 class Pickle; 38 class PickleIterator; 39 40 namespace net { 41 42 class CRLSet; 43 class CertVerifyResult; 44 45 typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; 46 47 // X509Certificate represents a X.509 certificate, which is comprised a 48 // particular identity or end-entity certificate, such as an SSL server 49 // identity or an SSL client certificate, and zero or more intermediate 50 // certificates that may be used to build a path to a root certificate. 51 class NET_EXPORT X509Certificate 52 : public base::RefCountedThreadSafe<X509Certificate> { 53 public: 54 // An OSCertHandle is a handle to a certificate object in the underlying 55 // crypto library. We assume that OSCertHandle is a pointer type on all 56 // platforms and that NULL represents an invalid OSCertHandle. 57 #if defined(OS_WIN) 58 typedef PCCERT_CONTEXT OSCertHandle; 59 #elif defined(OS_MACOSX) 60 typedef SecCertificateRef OSCertHandle; 61 #elif defined(USE_OPENSSL_CERTS) 62 typedef X509* OSCertHandle; 63 #elif defined(USE_NSS) 64 typedef struct CERTCertificateStr* OSCertHandle; 65 #else 66 // TODO(ericroman): not implemented 67 typedef void* OSCertHandle; 68 #endif 69 70 typedef std::vector<OSCertHandle> OSCertHandles; 71 72 enum PublicKeyType { 73 kPublicKeyTypeUnknown, 74 kPublicKeyTypeRSA, 75 kPublicKeyTypeDSA, 76 kPublicKeyTypeECDSA, 77 kPublicKeyTypeDH, 78 kPublicKeyTypeECDH 79 }; 80 81 // Predicate functor used in maps when X509Certificate is used as the key. 82 class NET_EXPORT LessThan { 83 public: 84 bool operator()(const scoped_refptr<X509Certificate>& lhs, 85 const scoped_refptr<X509Certificate>& rhs) const; 86 }; 87 88 enum Format { 89 // The data contains a single DER-encoded certificate, or a PEM-encoded 90 // DER certificate with the PEM encoding block name of "CERTIFICATE". 91 // Any subsequent blocks will be ignored. 92 FORMAT_SINGLE_CERTIFICATE = 1 << 0, 93 94 // The data contains a sequence of one or more PEM-encoded, DER 95 // certificates, with the PEM encoding block name of "CERTIFICATE". 96 // All PEM blocks will be parsed, until the first error is encountered. 97 FORMAT_PEM_CERT_SEQUENCE = 1 << 1, 98 99 // The data contains a PKCS#7 SignedData structure, whose certificates 100 // member is to be used to initialize the certificate and intermediates. 101 // The data may further be encoded using PEM, specifying block names of 102 // either "PKCS7" or "CERTIFICATE". 103 FORMAT_PKCS7 = 1 << 2, 104 105 // Automatically detect the format. 106 FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE | 107 FORMAT_PKCS7, 108 }; 109 110 // PickleType is intended for deserializing certificates that were pickled 111 // by previous releases as part of a net::HttpResponseInfo. 112 // When serializing certificates to a new Pickle, 113 // PICKLETYPE_CERTIFICATE_CHAIN_V3 is always used. 114 enum PickleType { 115 // When reading a certificate from a Pickle, the Pickle only contains a 116 // single certificate. 117 PICKLETYPE_SINGLE_CERTIFICATE, 118 119 // When reading a certificate from a Pickle, the Pickle contains the 120 // the certificate plus any certificates that were stored in 121 // |intermediate_ca_certificates_| at the time it was serialized. 122 // The count of certificates is stored as a size_t, which is either 32 123 // or 64 bits. 124 PICKLETYPE_CERTIFICATE_CHAIN_V2, 125 126 // The Pickle contains the certificate and any certificates that were 127 // stored in |intermediate_ca_certs_| at the time it was serialized. 128 // The format is [int count], [data - this certificate], 129 // [data - intermediate1], ... [data - intermediateN]. 130 // All certificates are stored in DER form. 131 PICKLETYPE_CERTIFICATE_CHAIN_V3, 132 }; 133 134 // Creates a X509Certificate from the ground up. Used by tests that simulate 135 // SSL connections. 136 X509Certificate(const std::string& subject, const std::string& issuer, 137 base::Time start_date, base::Time expiration_date); 138 139 // Create an X509Certificate from a handle to the certificate object in the 140 // underlying crypto library. The returned pointer must be stored in a 141 // scoped_refptr<X509Certificate>. 142 static X509Certificate* CreateFromHandle(OSCertHandle cert_handle, 143 const OSCertHandles& intermediates); 144 145 // Create an X509Certificate from a chain of DER encoded certificates. The 146 // first certificate in the chain is the end-entity certificate to which a 147 // handle is returned. The other certificates in the chain are intermediate 148 // certificates. The returned pointer must be stored in a 149 // scoped_refptr<X509Certificate>. 150 static X509Certificate* CreateFromDERCertChain( 151 const std::vector<base::StringPiece>& der_certs); 152 153 // Create an X509Certificate from the DER-encoded representation. 154 // Returns NULL on failure. 155 // 156 // The returned pointer must be stored in a scoped_refptr<X509Certificate>. 157 static X509Certificate* CreateFromBytes(const char* data, int length); 158 159 #if defined(USE_NSS) 160 // Create an X509Certificate from the DER-encoded representation. 161 // |nickname| can be NULL if an auto-generated nickname is desired. 162 // Returns NULL on failure. The returned pointer must be stored in a 163 // scoped_refptr<X509Certificate>. 164 // 165 // This function differs from CreateFromBytes in that it takes a 166 // nickname that will be used when the certificate is imported into PKCS#11. 167 static X509Certificate* CreateFromBytesWithNickname(const char* data, 168 int length, 169 const char* nickname); 170 171 // The default nickname of the certificate, based on the certificate type 172 // passed in. If this object was created using CreateFromBytesWithNickname, 173 // then this will return the nickname specified upon creation. 174 std::string GetDefaultNickname(CertType type) const; 175 #endif 176 177 // Create an X509Certificate from the representation stored in the given 178 // pickle. The data for this object is found relative to the given 179 // pickle_iter, which should be passed to the pickle's various Read* methods. 180 // Returns NULL on failure. 181 // 182 // The returned pointer must be stored in a scoped_refptr<X509Certificate>. 183 static X509Certificate* CreateFromPickle(const Pickle& pickle, 184 PickleIterator* pickle_iter, 185 PickleType type); 186 187 // Parses all of the certificates possible from |data|. |format| is a 188 // bit-wise OR of Format, indicating the possible formats the 189 // certificates may have been serialized as. If an error occurs, an empty 190 // collection will be returned. 191 static CertificateList CreateCertificateListFromBytes(const char* data, 192 int length, 193 int format); 194 195 // Appends a representation of this object to the given pickle. 196 void Persist(Pickle* pickle); 197 198 // The serial number, DER encoded, possibly including a leading 00 byte. serial_number()199 const std::string& serial_number() const { return serial_number_; } 200 201 // The subject of the certificate. For HTTPS server certificates, this 202 // represents the web server. The common name of the subject should match 203 // the host name of the web server. subject()204 const CertPrincipal& subject() const { return subject_; } 205 206 // The issuer of the certificate. issuer()207 const CertPrincipal& issuer() const { return issuer_; } 208 209 // Time period during which the certificate is valid. More precisely, this 210 // certificate is invalid before the |valid_start| date and invalid after 211 // the |valid_expiry| date. 212 // If we were unable to parse either date from the certificate (or if the cert 213 // lacks either date), the date will be null (i.e., is_null() will be true). valid_start()214 const base::Time& valid_start() const { return valid_start_; } valid_expiry()215 const base::Time& valid_expiry() const { return valid_expiry_; } 216 217 // The fingerprint of this certificate. fingerprint()218 const SHA1HashValue& fingerprint() const { return fingerprint_; } 219 220 // The fingerprint of the intermediate CA certificates. ca_fingerprint()221 const SHA1HashValue& ca_fingerprint() const { 222 return ca_fingerprint_; 223 } 224 225 // Gets the DNS names in the certificate. Pursuant to RFC 2818, Section 3.1 226 // Server Identity, if the certificate has a subjectAltName extension of 227 // type dNSName, this method gets the DNS names in that extension. 228 // Otherwise, it gets the common name in the subject field. 229 void GetDNSNames(std::vector<std::string>* dns_names) const; 230 231 // Gets the subjectAltName extension field from the certificate, if any. 232 // For future extension; currently this only returns those name types that 233 // are required for HTTP certificate name verification - see VerifyHostname. 234 // Unrequired parameters may be passed as NULL. 235 void GetSubjectAltName(std::vector<std::string>* dns_names, 236 std::vector<std::string>* ip_addrs) const; 237 238 // Convenience method that returns whether this certificate has expired as of 239 // now. 240 bool HasExpired() const; 241 242 // Returns true if this object and |other| represent the same certificate. 243 bool Equals(const X509Certificate* other) const; 244 245 // Returns intermediate certificates added via AddIntermediateCertificate(). 246 // Ownership follows the "get" rule: it is the caller's responsibility to 247 // retain the elements of the result. GetIntermediateCertificates()248 const OSCertHandles& GetIntermediateCertificates() const { 249 return intermediate_ca_certs_; 250 } 251 252 #if defined(OS_MACOSX) 253 // Does this certificate's usage allow SSL client authentication? 254 bool SupportsSSLClientAuth() const; 255 256 // Returns a new CFArrayRef containing this certificate and its intermediate 257 // certificates in the form expected by Security.framework and Keychain 258 // Services, or NULL on failure. 259 // The first item in the array will be this certificate, followed by its 260 // intermediates, if any. 261 CFArrayRef CreateOSCertChainForCert() const; 262 #endif 263 264 // Do any of the given issuer names appear in this cert's chain of trust? 265 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames. 266 bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers); 267 268 #if defined(OS_WIN) 269 // Returns a new PCCERT_CONTEXT containing this certificate and its 270 // intermediate certificates, or NULL on failure. The returned 271 // PCCERT_CONTEXT *MUST NOT* be stored in an X509Certificate, as this will 272 // cause os_cert_handle() to return incorrect results. This function is only 273 // necessary if the CERT_CONTEXT.hCertStore member will be accessed or 274 // enumerated, which is generally true for any CryptoAPI functions involving 275 // certificate chains, including validation or certificate display. 276 // 277 // Remarks: 278 // Depending on the CryptoAPI function, Windows may need to access the 279 // HCERTSTORE that the passed-in PCCERT_CONTEXT belongs to, such as to 280 // locate additional intermediates. However, all certificate handles are added 281 // to a NULL HCERTSTORE, allowing the system to manage the resources. As a 282 // result, intermediates for |cert_handle_| cannot be located simply via 283 // |cert_handle_->hCertStore|, as it refers to a magic value indicating 284 // "only this certificate". 285 // 286 // To avoid this problems, a new in-memory HCERTSTORE is created containing 287 // just this certificate and its intermediates. The handle to the version of 288 // the current certificate in the new HCERTSTORE is then returned, with the 289 // PCCERT_CONTEXT's HCERTSTORE set to be automatically freed when the returned 290 // certificate handle is freed. 291 // 292 // This function is only needed when the HCERTSTORE of the os_cert_handle() 293 // will be accessed, which is generally only during certificate validation 294 // or display. While the returned PCCERT_CONTEXT and its HCERTSTORE can 295 // safely be used on multiple threads if no further modifications happen, it 296 // is generally preferable for each thread that needs such a context to 297 // obtain its own, rather than risk thread-safety issues by sharing. 298 // 299 // Because of how X509Certificate caching is implemented, attempting to 300 // create an X509Certificate from the returned PCCERT_CONTEXT may result in 301 // the original handle (and thus the originall HCERTSTORE) being returned by 302 // os_cert_handle(). For this reason, the returned PCCERT_CONTEXT *MUST NOT* 303 // be stored in an X509Certificate. 304 PCCERT_CONTEXT CreateOSCertChainForCert() const; 305 #endif 306 307 #if defined(USE_OPENSSL_CERTS) 308 // Returns a handle to a global, in-memory certificate store. We 309 // use it for test code, e.g. importing the test server's certificate. 310 static X509_STORE* cert_store(); 311 #endif 312 313 // Verifies that |hostname| matches this certificate. 314 // Does not verify that the certificate is valid, only that the certificate 315 // matches this host. 316 // Returns true if it matches, and updates |*common_name_fallback_used|, 317 // setting it to true if a fallback to the CN was used, rather than 318 // subjectAltName. 319 bool VerifyNameMatch(const std::string& hostname, 320 bool* common_name_fallback_used) const; 321 322 // Obtains the DER encoded certificate data for |cert_handle|. On success, 323 // returns true and writes the DER encoded certificate to |*der_encoded|. 324 static bool GetDEREncoded(OSCertHandle cert_handle, 325 std::string* der_encoded); 326 327 // Returns the PEM encoded data from a DER encoded certificate. If the return 328 // value is true, then the PEM encoded certificate is written to 329 // |pem_encoded|. 330 static bool GetPEMEncodedFromDER(const std::string& der_encoded, 331 std::string* pem_encoded); 332 333 // Returns the PEM encoded data from an OSCertHandle. If the return value is 334 // true, then the PEM encoded certificate is written to |pem_encoded|. 335 static bool GetPEMEncoded(OSCertHandle cert_handle, 336 std::string* pem_encoded); 337 338 // Encodes the entire certificate chain (this certificate and any 339 // intermediate certificates stored in |intermediate_ca_certs_|) as a series 340 // of PEM encoded strings. Returns true if all certificates were encoded, 341 // storig the result in |*pem_encoded|, with this certificate stored as 342 // the first element. 343 bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const; 344 345 // Sets |*size_bits| to be the length of the public key in bits, and sets 346 // |*type| to one of the |PublicKeyType| values. In case of 347 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0. 348 static void GetPublicKeyInfo(OSCertHandle cert_handle, 349 size_t* size_bits, 350 PublicKeyType* type); 351 352 // Returns the OSCertHandle of this object. Because of caching, this may 353 // differ from the OSCertHandle originally supplied during initialization. 354 // Note: On Windows, CryptoAPI may return unexpected results if this handle 355 // is used across multiple threads. For more details, see 356 // CreateOSCertChainForCert(). os_cert_handle()357 OSCertHandle os_cert_handle() const { return cert_handle_; } 358 359 // Returns true if two OSCertHandles refer to identical certificates. 360 static bool IsSameOSCert(OSCertHandle a, OSCertHandle b); 361 362 // Creates an OS certificate handle from the DER-encoded representation. 363 // Returns NULL on failure. 364 static OSCertHandle CreateOSCertHandleFromBytes(const char* data, 365 int length); 366 367 #if defined(USE_NSS) 368 // Creates an OS certificate handle from the DER-encoded representation. 369 // Returns NULL on failure. Sets the default nickname if |nickname| is 370 // non-NULL. 371 static OSCertHandle CreateOSCertHandleFromBytesWithNickname( 372 const char* data, 373 int length, 374 const char* nickname); 375 #endif 376 377 // Creates all possible OS certificate handles from |data| encoded in a 378 // specific |format|. Returns an empty collection on failure. 379 static OSCertHandles CreateOSCertHandlesFromBytes( 380 const char* data, 381 int length, 382 Format format); 383 384 // Duplicates (or adds a reference to) an OS certificate handle. 385 static OSCertHandle DupOSCertHandle(OSCertHandle cert_handle); 386 387 // Frees (or releases a reference to) an OS certificate handle. 388 static void FreeOSCertHandle(OSCertHandle cert_handle); 389 390 // Calculates the SHA-1 fingerprint of the certificate. Returns an empty 391 // (all zero) fingerprint on failure. 392 // 393 // For calculating fingerprints, prefer SHA-1 for performance when indexing, 394 // but callers should use IsSameOSCert() before assuming two certificates are 395 // the same. 396 static SHA1HashValue CalculateFingerprint(OSCertHandle cert_handle); 397 398 // Calculates the SHA-1 fingerprint of the intermediate CA certificates. 399 // Returns an empty (all zero) fingerprint on failure. 400 // 401 // See SHA-1 caveat on CalculateFingerprint(). 402 static SHA1HashValue CalculateCAFingerprint( 403 const OSCertHandles& intermediates); 404 405 // Calculates the SHA-256 fingerprint of the intermediate CA certificates. 406 // Returns an empty (all zero) fingerprint on failure. 407 // 408 // As part of the cross-platform implementation of this function, it currently 409 // copies the certificate bytes into local variables which makes it 410 // potentially slower than implementing it directly for each platform. For 411 // now, the expected consumers are not performance critical, but if 412 // performance is a concern going forward, it may warrant implementing this on 413 // a per-platform basis. 414 static SHA256HashValue CalculateCAFingerprint256( 415 const OSCertHandles& intermediates); 416 417 // Calculates the SHA-256 fingerprint for the complete chain, including the 418 // leaf certificate and all intermediate CA certificates. Returns an empty 419 // (all zero) fingerprint on failure. 420 static SHA256HashValue CalculateChainFingerprint256( 421 OSCertHandle leaf, 422 const OSCertHandles& intermediates); 423 424 private: 425 friend class base::RefCountedThreadSafe<X509Certificate>; 426 friend class TestRootCerts; // For unit tests 427 428 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname); 429 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers); 430 431 // Construct an X509Certificate from a handle to the certificate object 432 // in the underlying crypto library. 433 X509Certificate(OSCertHandle cert_handle, 434 const OSCertHandles& intermediates); 435 436 ~X509Certificate(); 437 438 // Common object initialization code. Called by the constructors only. 439 void Initialize(); 440 441 #if defined(USE_OPENSSL_CERTS) 442 // Resets the store returned by cert_store() to default state. Used by 443 // TestRootCerts to undo modifications. 444 static void ResetCertStore(); 445 #endif 446 447 // Verifies that |hostname| matches one of the certificate names or IP 448 // addresses supplied, based on TLS name matching rules - specifically, 449 // following http://tools.ietf.org/html/rfc6125. 450 // |cert_common_name| is the Subject CN, e.g. from X509Certificate::subject(). 451 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled 452 // from the dNSName and iPAddress components of the subject alternative name 453 // extension, if present. Note these IP addresses are NOT ascii-encoded: 454 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6 455 // addresses, respectively. 456 // |common_name_fallback_used| will be updated to true if cert_common_name 457 // was used to match the hostname, or false if either of the |cert_san_*| 458 // parameters was used to match the hostname. 459 static bool VerifyHostname(const std::string& hostname, 460 const std::string& cert_common_name, 461 const std::vector<std::string>& cert_san_dns_names, 462 const std::vector<std::string>& cert_san_ip_addrs, 463 bool* common_name_fallback_used); 464 465 // Reads a single certificate from |pickle_iter| and returns a 466 // platform-specific certificate handle. The format of the certificate 467 // stored in |pickle_iter| is not guaranteed to be the same across different 468 // underlying cryptographic libraries, nor acceptable to CreateFromBytes(). 469 // Returns an invalid handle, NULL, on failure. 470 // NOTE: This should not be used for any new code. It is provided for 471 // migration purposes and should eventually be removed. 472 static OSCertHandle ReadOSCertHandleFromPickle(PickleIterator* pickle_iter); 473 474 // Writes a single certificate to |pickle| in DER form. Returns false on 475 // failure. 476 static bool WriteOSCertHandleToPickle(OSCertHandle handle, Pickle* pickle); 477 478 // The subject of the certificate. 479 CertPrincipal subject_; 480 481 // The issuer of the certificate. 482 CertPrincipal issuer_; 483 484 // This certificate is not valid before |valid_start_| 485 base::Time valid_start_; 486 487 // This certificate is not valid after |valid_expiry_| 488 base::Time valid_expiry_; 489 490 // The fingerprint of this certificate. 491 SHA1HashValue fingerprint_; 492 493 // The fingerprint of the intermediate CA certificates. 494 SHA1HashValue ca_fingerprint_; 495 496 // The serial number of this certificate, DER encoded. 497 std::string serial_number_; 498 499 // A handle to the certificate object in the underlying crypto library. 500 OSCertHandle cert_handle_; 501 502 // Untrusted intermediate certificates associated with this certificate 503 // that may be needed for chain building. 504 OSCertHandles intermediate_ca_certs_; 505 506 #if defined(USE_NSS) 507 // This stores any default nickname that has been set on the certificate 508 // at creation time with CreateFromBytesWithNickname. 509 // If this is empty, then GetDefaultNickname will return a generated name 510 // based on the type of the certificate. 511 std::string default_nickname_; 512 #endif 513 514 DISALLOW_COPY_AND_ASSIGN(X509Certificate); 515 }; 516 517 } // namespace net 518 519 #endif // NET_CERT_X509_CERTIFICATE_H_ 520