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