1 // Copyright 2012 The Chromium Authors 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 <stddef.h> 9 #include <string.h> 10 11 #include <string> 12 #include <string_view> 13 #include <vector> 14 15 #include "base/containers/span.h" 16 #include "base/gtest_prod_util.h" 17 #include "base/memory/ref_counted.h" 18 #include "base/time/time.h" 19 #include "net/base/hash_value.h" 20 #include "net/base/net_export.h" 21 #include "net/cert/x509_cert_types.h" 22 #include "third_party/boringssl/src/include/openssl/base.h" 23 24 namespace base { 25 class Pickle; 26 class PickleIterator; 27 } 28 29 namespace net { 30 31 class X509Certificate; 32 33 typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; 34 35 // A X.509 certificate represents a particular identity or end-entity 36 // certificate, such as an SSL server identity or an SSL client certificate. An 37 // X509Certificate contains this leaf certificate accessible via cert_buffer(). 38 // An X509Certificate may also contain 0 or more intermediary X.509 certificates 39 // that are used to build a path to a root certificate. These are accessed via 40 // intermediate_buffers(). 41 class NET_EXPORT X509Certificate 42 : public base::RefCountedThreadSafe<X509Certificate> { 43 public: 44 enum PublicKeyType { 45 kPublicKeyTypeUnknown, 46 kPublicKeyTypeRSA, 47 kPublicKeyTypeECDSA, 48 }; 49 50 enum Format { 51 // The data contains a single DER-encoded certificate, or a PEM-encoded 52 // DER certificate with the PEM encoding block name of "CERTIFICATE". 53 // Any subsequent blocks will be ignored. 54 FORMAT_SINGLE_CERTIFICATE = 1 << 0, 55 56 // The data contains a sequence of one or more PEM-encoded, DER 57 // certificates, with the PEM encoding block name of "CERTIFICATE". 58 // All PEM blocks will be parsed, until the first error is encountered. 59 FORMAT_PEM_CERT_SEQUENCE = 1 << 1, 60 61 // The data contains a PKCS#7 SignedData structure, whose certificates 62 // member is to be used to initialize the certificate and intermediates. 63 // The data may further be encoded using PEM, specifying block names of 64 // either "PKCS7" or "CERTIFICATE". 65 FORMAT_PKCS7 = 1 << 2, 66 67 // Automatically detect the format. 68 FORMAT_AUTO = FORMAT_SINGLE_CERTIFICATE | FORMAT_PEM_CERT_SEQUENCE | 69 FORMAT_PKCS7, 70 }; 71 72 // Create an X509Certificate from a CRYPTO_BUFFER containing the DER-encoded 73 // representation. Returns NULL on failure to parse or extract data from the 74 // the certificate. Note that this does not guarantee the certificate is 75 // fully parsed and validated, only that the members of this class, such as 76 // subject, issuer, expiry times, and serial number, could be successfully 77 // initialized from the certificate. 78 static scoped_refptr<X509Certificate> CreateFromBuffer( 79 bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer, 80 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates); 81 82 // Options for configuring certificate parsing. 83 // Do not use without consulting //net owners. 84 struct UnsafeCreateOptions { 85 bool printable_string_is_utf8 = false; 86 }; 87 // Create an X509Certificate with non-standard parsing options. 88 // Do not use without consulting //net owners. 89 static scoped_refptr<X509Certificate> CreateFromBufferUnsafeOptions( 90 bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer, 91 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates, 92 UnsafeCreateOptions options); 93 94 // Create an X509Certificate from a chain of DER encoded certificates. The 95 // first certificate in the chain is the end-entity certificate to which a 96 // handle is returned. The other certificates in the chain are intermediate 97 // certificates. 98 static scoped_refptr<X509Certificate> CreateFromDERCertChain( 99 const std::vector<std::string_view>& der_certs); 100 101 // Create an X509Certificate from a chain of DER encoded certificates with 102 // non-standard parsing options. 103 // Do not use without consulting //net owners. 104 static scoped_refptr<X509Certificate> CreateFromDERCertChainUnsafeOptions( 105 const std::vector<std::string_view>& der_certs, 106 UnsafeCreateOptions options); 107 108 // Create an X509Certificate from the DER-encoded representation. 109 // Returns NULL on failure. 110 static scoped_refptr<X509Certificate> CreateFromBytes( 111 base::span<const uint8_t> data); 112 113 // Create an X509Certificate with non-standard parsing options. 114 // Do not use without consulting //net owners. 115 static scoped_refptr<X509Certificate> CreateFromBytesUnsafeOptions( 116 base::span<const uint8_t> data, 117 UnsafeCreateOptions options); 118 119 // Create an X509Certificate from the representation stored in the given 120 // pickle. The data for this object is found relative to the given 121 // pickle_iter, which should be passed to the pickle's various Read* methods. 122 // Returns NULL on failure. 123 static scoped_refptr<X509Certificate> CreateFromPickle( 124 base::PickleIterator* pickle_iter); 125 126 // Create an X509Certificate from the representation stored in the given 127 // pickle with non-standard parsing options. 128 // Do not use without consulting //net owners. 129 static scoped_refptr<X509Certificate> CreateFromPickleUnsafeOptions( 130 base::PickleIterator* pickle_iter, 131 UnsafeCreateOptions options); 132 133 // Parses all of the certificates possible from |data|. |format| is a 134 // bit-wise OR of Format, indicating the possible formats the 135 // certificates may have been serialized as. If an error occurs, an empty 136 // collection will be returned. 137 static CertificateList CreateCertificateListFromBytes( 138 base::span<const uint8_t> data, 139 int format); 140 141 // Return a X509Certificate object representing the same certificate but 142 // with a different set of intermediates. If |intermediates| are the same as 143 // |intermediate_ca_certs_|, it will return a reference to the same 144 // X509Certificate object rather than cloning. 145 scoped_refptr<X509Certificate> CloneWithDifferentIntermediates( 146 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates); 147 148 X509Certificate(const X509Certificate&) = delete; 149 X509Certificate& operator=(const X509Certificate&) = delete; 150 151 // Appends a representation of this object to the given pickle. 152 // The Pickle contains the certificate and any certificates that were 153 // stored in |intermediate_ca_certs_| at the time it was serialized. 154 // The format is [int count], [data - this certificate], 155 // [data - intermediate1], ... [data - intermediateN]. 156 // All certificates are stored in DER form. 157 void Persist(base::Pickle* pickle) const; 158 159 // The serial number, DER encoded, possibly including a leading 00 byte. serial_number()160 const std::string& serial_number() const { return parsed_.serial_number_; } 161 162 // The subject of the certificate. For HTTPS server certificates, this 163 // represents the web server. The common name of the subject should match 164 // the host name of the web server. subject()165 const CertPrincipal& subject() const { return parsed_.subject_; } 166 167 // The issuer of the certificate. issuer()168 const CertPrincipal& issuer() const { return parsed_.issuer_; } 169 170 // Time period during which the certificate is valid. More precisely, this 171 // certificate is invalid before the |valid_start| date and invalid after 172 // the |valid_expiry| date. 173 // If we were unable to parse either date from the certificate (or if the cert 174 // lacks either date), the date will be null (i.e., is_null() will be true). valid_start()175 const base::Time& valid_start() const { return parsed_.valid_start_; } valid_expiry()176 const base::Time& valid_expiry() const { return parsed_.valid_expiry_; } 177 178 // Gets the subjectAltName extension field from the certificate, if any. 179 // For future extension; currently this only returns those name types that 180 // are required for HTTP certificate name verification - see VerifyHostname. 181 // Returns true if any dNSName or iPAddress SAN was present. If |dns_names| 182 // is non-null, it will be set to all dNSNames present. If |ip_addrs| is 183 // non-null, it will be set to all iPAddresses present. 184 bool GetSubjectAltName(std::vector<std::string>* dns_names, 185 std::vector<std::string>* ip_addrs) const; 186 187 // Convenience method that returns whether this certificate has expired as of 188 // now. 189 bool HasExpired() const; 190 191 // Returns true if this object and |other| represent the same certificate. 192 // Does not consider any associated intermediates. 193 bool EqualsExcludingChain(const X509Certificate* other) const; 194 195 // Returns true if this object and |other| represent the same certificate 196 // and intermediates. 197 bool EqualsIncludingChain(const X509Certificate* other) const; 198 199 // Do any of the given issuer names appear in this cert's chain of trust? 200 // |valid_issuers| is a list of DER-encoded X.509 DistinguishedNames. 201 bool IsIssuedByEncoded(const std::vector<std::string>& valid_issuers) const; 202 203 // Verifies that |hostname| matches this certificate. 204 // Does not verify that the certificate is valid, only that the certificate 205 // matches this host. 206 bool VerifyNameMatch(std::string_view hostname) const; 207 208 // Returns the PEM encoded data from a DER encoded certificate. If the 209 // return value is true, then the PEM encoded certificate is written to 210 // |pem_encoded|. 211 static bool GetPEMEncodedFromDER(std::string_view der_encoded, 212 std::string* pem_encoded); 213 214 // Returns the PEM encoded data from a CRYPTO_BUFFER. If the return value is 215 // true, then the PEM encoded certificate is written to |pem_encoded|. 216 static bool GetPEMEncoded(const CRYPTO_BUFFER* cert_buffer, 217 std::string* pem_encoded); 218 219 // Encodes the entire certificate chain (this certificate and any 220 // intermediate certificates stored in |intermediate_ca_certs_|) as a series 221 // of PEM encoded strings. Returns true if all certificates were encoded, 222 // storing the result in |*pem_encoded|, with this certificate stored as 223 // the first element. 224 bool GetPEMEncodedChain(std::vector<std::string>* pem_encoded) const; 225 226 // Sets |*size_bits| to be the length of the public key in bits, and sets 227 // |*type| to one of the |PublicKeyType| values. In case of 228 // |kPublicKeyTypeUnknown|, |*size_bits| will be set to 0. 229 static void GetPublicKeyInfo(const CRYPTO_BUFFER* cert_buffer, 230 size_t* size_bits, 231 PublicKeyType* type); 232 233 // Returns the bytes in CRYPTO_BUFFER that hold this certificate's DER encoded 234 // data. The data is not guaranteed to be valid DER or to encode a valid 235 // Certificate object. 236 base::span<const uint8_t> cert_span() const; 237 238 // Returns the CRYPTO_BUFFER holding this certificate's DER encoded data. The 239 // data is not guaranteed to be valid DER or to encode a valid Certificate 240 // object. 241 // 242 // To access the CRYPTO_BUFFER's bytes, use `cert_span()` above. cert_buffer()243 CRYPTO_BUFFER* cert_buffer() const { return cert_buffer_.get(); } 244 245 // Returns the associated intermediate certificates that were specified 246 // during creation of this object, if any. The intermediates are not 247 // guaranteed to be valid DER or to encode valid Certificate objects. 248 // Ownership follows the "get" rule: it is the caller's responsibility to 249 // retain the elements of the result. intermediate_buffers()250 const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>>& intermediate_buffers() 251 const { 252 return intermediate_ca_certs_; 253 } 254 255 // Creates all possible CRYPTO_BUFFERs from |data| encoded in a specific 256 // |format|. Returns an empty collection on failure. 257 static std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> CreateCertBuffersFromBytes( 258 base::span<const uint8_t> data, 259 Format format); 260 261 // Calculates the SHA-256 fingerprint of the certificate. Returns an empty 262 // (all zero) fingerprint on failure. 263 static SHA256HashValue CalculateFingerprint256( 264 const CRYPTO_BUFFER* cert_buffer); 265 266 // Calculates the SHA-256 fingerprint for the complete chain, including the 267 // leaf certificate and all intermediate CA certificates. Returns an empty 268 // (all zero) fingerprint on failure. 269 SHA256HashValue CalculateChainFingerprint256() const; 270 271 // Returns true if the certificate is self-signed. 272 static bool IsSelfSigned(CRYPTO_BUFFER* cert_buffer); 273 274 private: 275 friend class base::RefCountedThreadSafe<X509Certificate>; 276 friend class TestRootCerts; // For unit tests 277 278 FRIEND_TEST_ALL_PREFIXES(X509CertificateNameVerifyTest, VerifyHostname); 279 FRIEND_TEST_ALL_PREFIXES(X509CertificateTest, SerialNumbers); 280 281 class ParsedFields { 282 public: 283 ParsedFields(); 284 ParsedFields(const ParsedFields&); 285 ParsedFields(ParsedFields&&); 286 ~ParsedFields(); 287 288 bool Initialize(const CRYPTO_BUFFER* cert_buffer, 289 UnsafeCreateOptions options); 290 291 // The subject of the certificate. 292 CertPrincipal subject_; 293 294 // The issuer of the certificate. 295 CertPrincipal issuer_; 296 297 // This certificate is not valid before |valid_start_| 298 base::Time valid_start_; 299 300 // This certificate is not valid after |valid_expiry_| 301 base::Time valid_expiry_; 302 303 // The serial number of this certificate, DER encoded. 304 std::string serial_number_; 305 }; 306 307 // Construct an X509Certificate from a CRYPTO_BUFFER containing the 308 // DER-encoded representation. 309 X509Certificate(ParsedFields parsed, 310 bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer, 311 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates); 312 313 // Copy |other|, except with a different set of intermediates. 314 X509Certificate(const X509Certificate& other, 315 std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates); 316 317 ~X509Certificate(); 318 319 // Verifies that |hostname| matches one of the certificate names or IP 320 // addresses supplied, based on TLS name matching rules - specifically, 321 // following http://tools.ietf.org/html/rfc6125. 322 // The members of |cert_san_dns_names| and |cert_san_ipaddrs| must be filled 323 // from the dNSName and iPAddress components of the subject alternative name 324 // extension, if present. Note these IP addresses are NOT ascii-encoded: 325 // they must be 4 or 16 bytes of network-ordered data, for IPv4 and IPv6 326 // addresses, respectively. 327 static bool VerifyHostname(std::string_view hostname, 328 const std::vector<std::string>& cert_san_dns_names, 329 const std::vector<std::string>& cert_san_ip_addrs); 330 331 // Fields that were parsed from |cert_buffer_|. 332 const ParsedFields parsed_; 333 334 // A handle to the DER encoded certificate data. 335 const bssl::UniquePtr<CRYPTO_BUFFER> cert_buffer_; 336 337 // Untrusted intermediate certificates associated with this certificate 338 // that may be needed for chain building. 339 const std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediate_ca_certs_; 340 }; 341 342 } // namespace net 343 344 #endif // NET_CERT_X509_CERTIFICATE_H_ 345