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_UTIL_MAC_H_
6 #define NET_CERT_X509_UTIL_MAC_H_
7 
8 #include <CoreFoundation/CFArray.h>
9 #include <Security/Security.h>
10 
11 #include <string>
12 
13 #include "base/mac/scoped_cftyperef.h"
14 #include "base/macros.h"
15 #include "base/memory/ref_counted.h"
16 #include "net/base/hash_value.h"
17 #include "net/base/net_export.h"
18 #include "net/cert/x509_certificate.h"
19 
20 namespace net {
21 
22 namespace x509_util {
23 
24 // Tests that a given |cert_handle| is actually a valid X.509 certificate, and
25 // returns true if it is.
26 //
27 // On OS X, SecCertificateCreateFromData() does not return any errors if
28 // called with invalid data, as long as data is present. The actual decoding
29 // of the certificate does not happen until an API that requires a CSSM
30 // handle is called. While SecCertificateGetCLHandle is the most likely
31 // candidate, as it performs the parsing, it does not check whether the
32 // parsing was actually successful. Instead, SecCertificateGetSubject is
33 // used (supported since 10.3), as a means to check that the certificate
34 // parsed as a valid X.509 certificate.
35 NET_EXPORT bool IsValidSecCertificate(SecCertificateRef cert_handle);
36 
37 // Creates a SecCertificate handle from the DER-encoded representation.
38 // Returns NULL on failure.
39 NET_EXPORT base::ScopedCFTypeRef<SecCertificateRef>
40 CreateSecCertificateFromBytes(const uint8_t* data, size_t length);
41 
42 // Returns a SecCertificate representing |cert|, or NULL on failure.
43 NET_EXPORT base::ScopedCFTypeRef<SecCertificateRef>
44 CreateSecCertificateFromX509Certificate(const X509Certificate* cert);
45 
46 // Creates an X509Certificate representing |sec_cert| with intermediates
47 // |sec_chain|.
48 NET_EXPORT scoped_refptr<X509Certificate>
49 CreateX509CertificateFromSecCertificate(
50     SecCertificateRef sec_cert,
51     const std::vector<SecCertificateRef>& sec_chain);
52 
53 // Creates an X509Certificate with non-standard parsing options.
54 // Do not use without consulting //net owners.
55 NET_EXPORT scoped_refptr<X509Certificate>
56 CreateX509CertificateFromSecCertificate(
57     SecCertificateRef sec_cert,
58     const std::vector<SecCertificateRef>& sec_chain,
59     X509Certificate::UnsafeCreateOptions options);
60 
61 // Calculates the SHA-256 fingerprint of the certificate.  Returns an empty
62 // (all zero) fingerprint on failure.
63 NET_EXPORT SHA256HashValue CalculateFingerprint256(SecCertificateRef cert);
64 
65 // Creates a security policy for certificates used as client certificates
66 // in SSL.
67 // If a policy is successfully created, it will be stored in
68 // |*policy| and ownership transferred to the caller.
69 NET_EXPORT OSStatus CreateSSLClientPolicy(SecPolicyRef* policy);
70 
71 // Create an SSL server policy. While certificate name validation will be
72 // performed by SecTrustEvaluate(), it has the following limitations:
73 // - Doesn't support IP addresses in dotted-quad literals (127.0.0.1)
74 // - Doesn't support IPv6 addresses
75 // - Doesn't support the iPAddress subjectAltName
76 // Providing the hostname is necessary in order to locate certain user or
77 // system trust preferences, such as those created by Safari. Preferences
78 // created by Keychain Access do not share this requirement.
79 // On success, stores the resultant policy in |*policy| and returns noErr.
80 NET_EXPORT OSStatus CreateSSLServerPolicy(const std::string& hostname,
81                                           SecPolicyRef* policy);
82 
83 // Creates a security policy for basic X.509 validation. If the policy is
84 // successfully created, it will be stored in |*policy| and ownership
85 // transferred to the caller.
86 NET_EXPORT OSStatus CreateBasicX509Policy(SecPolicyRef* policy);
87 
88 // Creates security policies to control revocation checking (OCSP and CRL).
89 // If |enable_revocation_checking| is true, revocation checking will be
90 // explicitly enabled.
91 // Otherwise, the policies returned will be explicitly prohibited from accessing
92 // the network or the local cache, if possible.
93 // If the policies are successfully created, they will be appended to
94 // |policies|.
95 NET_EXPORT OSStatus CreateRevocationPolicies(bool enable_revocation_checking,
96                                              CFMutableArrayRef policies);
97 
98 // CSSM functions are deprecated as of OSX 10.7, but have no replacement.
99 // https://bugs.chromium.org/p/chromium/issues/detail?id=590914#c1
100 #pragma clang diagnostic push
101 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
102 
103 // Wrapper for a CSSM_DATA_PTR that was obtained via one of the CSSM field
104 // accessors (such as CSSM_CL_CertGet[First/Next]Value or
105 // CSSM_CL_CertGet[First/Next]CachedValue).
106 class CSSMFieldValue {
107  public:
108   CSSMFieldValue();
109   CSSMFieldValue(CSSM_CL_HANDLE cl_handle,
110                  const CSSM_OID* oid,
111                  CSSM_DATA_PTR field);
112   ~CSSMFieldValue();
113 
oid()114   CSSM_OID_PTR oid() const { return oid_; }
field()115   CSSM_DATA_PTR field() const { return field_; }
116 
117   // Returns the field as if it was an arbitrary type - most commonly, by
118   // interpreting the field as a specific CSSM/CDSA parsed type, such as
119   // CSSM_X509_SUBJECT_PUBLIC_KEY_INFO or CSSM_X509_ALGORITHM_IDENTIFIER.
120   // An added check is applied to ensure that the current field is large
121   // enough to actually contain the requested type.
GetAs()122   template <typename T> const T* GetAs() const {
123     if (!field_ || field_->Length < sizeof(T))
124       return NULL;
125     return reinterpret_cast<const T*>(field_->Data);
126   }
127 
128   void Reset(CSSM_CL_HANDLE cl_handle,
129              CSSM_OID_PTR oid,
130              CSSM_DATA_PTR field);
131 
132  private:
133   CSSM_CL_HANDLE cl_handle_;
134   CSSM_OID_PTR oid_;
135   CSSM_DATA_PTR field_;
136 
137   DISALLOW_COPY_AND_ASSIGN(CSSMFieldValue);
138 };
139 
140 // CSSMCachedCertificate is a container class that is used to wrap the
141 // CSSM_CL_CertCache APIs and provide safe and efficient access to
142 // certificate fields in their CSSM form.
143 //
144 // To provide efficient access to certificate/CRL fields, CSSM provides an
145 // API/SPI to "cache" a certificate/CRL. The exact meaning of a cached
146 // certificate is not defined by CSSM, but is documented to generally be some
147 // intermediate or parsed form of the certificate. In the case of Apple's
148 // CSSM CL implementation, the intermediate form is the parsed certificate
149 // stored in an internal format (which happens to be NSS). By caching the
150 // certificate, callers that wish to access multiple fields (such as subject,
151 // issuer, and validity dates) do not need to repeatedly parse the entire
152 // certificate, nor are they forced to convert all fields from their NSS types
153 // to their CSSM equivalents. This latter point is especially helpful when
154 // running on OS X 10.5, as it will fail to convert some fields that reference
155 // unsupported algorithms, such as ECC.
156 class CSSMCachedCertificate {
157  public:
158   CSSMCachedCertificate();
159   ~CSSMCachedCertificate();
160 
161   // Initializes the CSSMCachedCertificate by caching the specified
162   // |os_cert_handle|. On success, returns noErr.
163   // Note: Once initialized, the cached certificate should only be accessed
164   // from a single thread.
165   OSStatus Init(SecCertificateRef os_cert_handle);
166 
167   // Fetches the first value for the field associated with |field_oid|.
168   // If |field_oid| is a valid OID and is present in the current certificate,
169   // returns CSSM_OK and stores the first value in |field|. If additional
170   // values are associated with |field_oid|, they are ignored.
171   OSStatus GetField(const CSSM_OID* field_oid, CSSMFieldValue* field) const;
172 
173  private:
174   CSSM_CL_HANDLE cl_handle_;
175   CSSM_HANDLE cached_cert_handle_;
176 };
177 
178 // Compares two OIDs by value.
CSSMOIDEqual(const CSSM_OID * oid1,const CSSM_OID * oid2)179 inline bool CSSMOIDEqual(const CSSM_OID* oid1, const CSSM_OID* oid2) {
180   return oid1->Length == oid2->Length &&
181          (memcmp(oid1->Data, oid2->Data, oid1->Length) == 0);
182 }
183 
184 #pragma clang diagnostic pop  // "-Wdeprecated-declarations"
185 
186 }  // namespace x509_util
187 
188 }  // namespace net
189 
190 #endif  // NET_CERT_X509_UTIL_MAC_H_
191