• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 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 #include "net/cert/x509_util_nss.h"
6 
7 #include <cert.h>  // Must be included before certdb.h
8 #include <certdb.h>
9 #include <cryptohi.h>
10 #include <dlfcn.h>
11 #include <nss.h>
12 #include <pk11pub.h>
13 #include <prerror.h>
14 #include <seccomon.h>
15 #include <secder.h>
16 #include <sechash.h>
17 #include <secmod.h>
18 #include <secport.h>
19 #include <string.h>
20 
21 #include "base/logging.h"
22 #include "base/strings/stringprintf.h"
23 #include "crypto/nss_util.h"
24 #include "crypto/scoped_nss_types.h"
25 #include "net/cert/x509_util.h"
26 #include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h"
27 #include "third_party/boringssl/src/include/openssl/pool.h"
28 
29 namespace net::x509_util {
30 
31 namespace {
32 
33 // Microsoft User Principal Name: 1.3.6.1.4.1.311.20.2.3
34 const uint8_t kUpnOid[] = {0x2b, 0x6,  0x1,  0x4, 0x1,
35                            0x82, 0x37, 0x14, 0x2, 0x3};
36 
DecodeAVAValue(CERTAVA * ava)37 std::string DecodeAVAValue(CERTAVA* ava) {
38   SECItem* decode_item = CERT_DecodeAVAValue(&ava->value);
39   if (!decode_item)
40     return std::string();
41   std::string value(reinterpret_cast<char*>(decode_item->data),
42                     decode_item->len);
43   SECITEM_FreeItem(decode_item, PR_TRUE);
44   return value;
45 }
46 
47 // Generates a unique nickname for |slot|, returning |nickname| if it is
48 // already unique.
49 //
50 // Note: The nickname returned will NOT include the token name, thus the
51 // token name must be prepended if calling an NSS function that expects
52 // <token>:<nickname>.
53 // TODO(gspencer): Internationalize this: it's wrong to hard-code English.
GetUniqueNicknameForSlot(const std::string & nickname,const SECItem * subject,PK11SlotInfo * slot)54 std::string GetUniqueNicknameForSlot(const std::string& nickname,
55                                      const SECItem* subject,
56                                      PK11SlotInfo* slot) {
57   int index = 2;
58   std::string new_name = nickname;
59   std::string temp_nickname = new_name;
60   std::string token_name;
61 
62   if (!slot)
63     return new_name;
64 
65   if (!PK11_IsInternalKeySlot(slot)) {
66     token_name.assign(PK11_GetTokenName(slot));
67     token_name.append(":");
68 
69     temp_nickname = token_name + new_name;
70   }
71 
72   while (SEC_CertNicknameConflict(temp_nickname.c_str(),
73                                   const_cast<SECItem*>(subject),
74                                   CERT_GetDefaultCertDB())) {
75     base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++);
76     temp_nickname = token_name + new_name;
77   }
78 
79   return new_name;
80 }
81 
82 // The default nickname of the certificate, based on the certificate type
83 // passed in.
GetDefaultNickname(CERTCertificate * nss_cert,CertType type)84 std::string GetDefaultNickname(CERTCertificate* nss_cert, CertType type) {
85   std::string result;
86   if (type == USER_CERT && nss_cert->slot) {
87     // Find the private key for this certificate and see if it has a
88     // nickname.  If there is a private key, and it has a nickname, then
89     // return that nickname.
90     SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert(
91         nss_cert->slot, nss_cert, nullptr /*wincx*/);
92     if (private_key) {
93       char* private_key_nickname = PK11_GetPrivateKeyNickname(private_key);
94       if (private_key_nickname) {
95         result = private_key_nickname;
96         PORT_Free(private_key_nickname);
97         SECKEY_DestroyPrivateKey(private_key);
98         return result;
99       }
100       SECKEY_DestroyPrivateKey(private_key);
101     }
102   }
103 
104   switch (type) {
105     case CA_CERT: {
106       char* nickname = CERT_MakeCANickname(nss_cert);
107       result = nickname;
108       PORT_Free(nickname);
109       break;
110     }
111     case USER_CERT: {
112       std::string subject_name = GetCERTNameDisplayName(&nss_cert->subject);
113       if (subject_name.empty()) {
114         const char* email = CERT_GetFirstEmailAddress(nss_cert);
115         if (email)
116           subject_name = email;
117       }
118       // TODO(gspencer): Internationalize this. It's wrong to assume English
119       // here.
120       result =
121           base::StringPrintf("%s's %s ID", subject_name.c_str(),
122                              GetCERTNameDisplayName(&nss_cert->issuer).c_str());
123       break;
124     }
125     case SERVER_CERT: {
126       result = GetCERTNameDisplayName(&nss_cert->subject);
127       break;
128     }
129     case OTHER_CERT:
130     default:
131       break;
132   }
133   return result;
134 }
135 
136 }  // namespace
137 
IsSameCertificate(CERTCertificate * a,CERTCertificate * b)138 bool IsSameCertificate(CERTCertificate* a, CERTCertificate* b) {
139   DCHECK(a && b);
140   if (a == b)
141     return true;
142   return a->derCert.len == b->derCert.len &&
143          memcmp(a->derCert.data, b->derCert.data, a->derCert.len) == 0;
144 }
145 
IsSameCertificate(CERTCertificate * a,const X509Certificate * b)146 bool IsSameCertificate(CERTCertificate* a, const X509Certificate* b) {
147   return IsSameCertificate(a, b->cert_buffer());
148 }
IsSameCertificate(const X509Certificate * a,CERTCertificate * b)149 bool IsSameCertificate(const X509Certificate* a, CERTCertificate* b) {
150   return IsSameCertificate(b, a->cert_buffer());
151 }
152 
IsSameCertificate(CERTCertificate * a,const CRYPTO_BUFFER * b)153 bool IsSameCertificate(CERTCertificate* a, const CRYPTO_BUFFER* b) {
154   return a->derCert.len == CRYPTO_BUFFER_len(b) &&
155          memcmp(a->derCert.data, CRYPTO_BUFFER_data(b), a->derCert.len) == 0;
156 }
IsSameCertificate(const CRYPTO_BUFFER * a,CERTCertificate * b)157 bool IsSameCertificate(const CRYPTO_BUFFER* a, CERTCertificate* b) {
158   return IsSameCertificate(b, a);
159 }
160 
CreateCERTCertificateFromBytes(const uint8_t * data,size_t length)161 ScopedCERTCertificate CreateCERTCertificateFromBytes(const uint8_t* data,
162                                                      size_t length) {
163   crypto::EnsureNSSInit();
164 
165   if (!NSS_IsInitialized())
166     return nullptr;
167 
168   SECItem der_cert;
169   der_cert.data = const_cast<uint8_t*>(data);
170   der_cert.len = base::checked_cast<unsigned>(length);
171   der_cert.type = siDERCertBuffer;
172 
173   // Parse into a certificate structure.
174   return ScopedCERTCertificate(CERT_NewTempCertificate(
175       CERT_GetDefaultCertDB(), &der_cert, nullptr /* nickname */,
176       PR_FALSE /* is_perm */, PR_TRUE /* copyDER */));
177 }
178 
CreateCERTCertificateFromX509Certificate(const X509Certificate * cert)179 ScopedCERTCertificate CreateCERTCertificateFromX509Certificate(
180     const X509Certificate* cert) {
181   return CreateCERTCertificateFromBytes(CRYPTO_BUFFER_data(cert->cert_buffer()),
182                                         CRYPTO_BUFFER_len(cert->cert_buffer()));
183 }
184 
CreateCERTCertificateListFromX509Certificate(const X509Certificate * cert)185 ScopedCERTCertificateList CreateCERTCertificateListFromX509Certificate(
186     const X509Certificate* cert) {
187   return x509_util::CreateCERTCertificateListFromX509Certificate(
188       cert, InvalidIntermediateBehavior::kFail);
189 }
190 
CreateCERTCertificateListFromX509Certificate(const X509Certificate * cert,InvalidIntermediateBehavior invalid_intermediate_behavior)191 ScopedCERTCertificateList CreateCERTCertificateListFromX509Certificate(
192     const X509Certificate* cert,
193     InvalidIntermediateBehavior invalid_intermediate_behavior) {
194   ScopedCERTCertificateList nss_chain;
195   nss_chain.reserve(1 + cert->intermediate_buffers().size());
196   ScopedCERTCertificate nss_cert =
197       CreateCERTCertificateFromX509Certificate(cert);
198   if (!nss_cert)
199     return {};
200   nss_chain.push_back(std::move(nss_cert));
201   for (const auto& intermediate : cert->intermediate_buffers()) {
202     ScopedCERTCertificate nss_intermediate =
203         CreateCERTCertificateFromBytes(CRYPTO_BUFFER_data(intermediate.get()),
204                                        CRYPTO_BUFFER_len(intermediate.get()));
205     if (!nss_intermediate) {
206       if (invalid_intermediate_behavior == InvalidIntermediateBehavior::kFail)
207         return {};
208       LOG(WARNING) << "error parsing intermediate";
209       continue;
210     }
211     nss_chain.push_back(std::move(nss_intermediate));
212   }
213   return nss_chain;
214 }
215 
CreateCERTCertificateListFromBytes(const char * data,size_t length,int format)216 ScopedCERTCertificateList CreateCERTCertificateListFromBytes(const char* data,
217                                                              size_t length,
218                                                              int format) {
219   CertificateList certs = X509Certificate::CreateCertificateListFromBytes(
220       base::as_bytes(base::make_span(data, length)), format);
221   ScopedCERTCertificateList nss_chain;
222   nss_chain.reserve(certs.size());
223   for (const scoped_refptr<X509Certificate>& cert : certs) {
224     ScopedCERTCertificate nss_cert =
225         CreateCERTCertificateFromX509Certificate(cert.get());
226     if (!nss_cert)
227       return {};
228     nss_chain.push_back(std::move(nss_cert));
229   }
230   return nss_chain;
231 }
232 
DupCERTCertificate(CERTCertificate * cert)233 ScopedCERTCertificate DupCERTCertificate(CERTCertificate* cert) {
234   return ScopedCERTCertificate(CERT_DupCertificate(cert));
235 }
236 
DupCERTCertificateList(const ScopedCERTCertificateList & certs)237 ScopedCERTCertificateList DupCERTCertificateList(
238     const ScopedCERTCertificateList& certs) {
239   ScopedCERTCertificateList result;
240   result.reserve(certs.size());
241   for (const ScopedCERTCertificate& cert : certs)
242     result.push_back(DupCERTCertificate(cert.get()));
243   return result;
244 }
245 
CreateX509CertificateFromCERTCertificate(CERTCertificate * nss_cert,const std::vector<CERTCertificate * > & nss_chain)246 scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
247     CERTCertificate* nss_cert,
248     const std::vector<CERTCertificate*>& nss_chain) {
249   return CreateX509CertificateFromCERTCertificate(nss_cert, nss_chain, {});
250 }
251 
CreateX509CertificateFromCERTCertificate(CERTCertificate * nss_cert,const std::vector<CERTCertificate * > & nss_chain,X509Certificate::UnsafeCreateOptions options)252 scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
253     CERTCertificate* nss_cert,
254     const std::vector<CERTCertificate*>& nss_chain,
255     X509Certificate::UnsafeCreateOptions options) {
256   if (!nss_cert || !nss_cert->derCert.len) {
257     return nullptr;
258   }
259   bssl::UniquePtr<CRYPTO_BUFFER> cert_handle(x509_util::CreateCryptoBuffer(
260       base::make_span(nss_cert->derCert.data, nss_cert->derCert.len)));
261 
262   std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
263   intermediates.reserve(nss_chain.size());
264   for (const CERTCertificate* nss_intermediate : nss_chain) {
265     if (!nss_intermediate || !nss_intermediate->derCert.len) {
266       return nullptr;
267     }
268     intermediates.push_back(x509_util::CreateCryptoBuffer(base::make_span(
269         nss_intermediate->derCert.data, nss_intermediate->derCert.len)));
270   }
271 
272   return X509Certificate::CreateFromBufferUnsafeOptions(
273       std::move(cert_handle), std::move(intermediates), options);
274 }
275 
CreateX509CertificateFromCERTCertificate(CERTCertificate * cert)276 scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
277     CERTCertificate* cert) {
278   return CreateX509CertificateFromCERTCertificate(
279       cert, std::vector<CERTCertificate*>());
280 }
281 
CreateX509CertificateListFromCERTCertificates(const ScopedCERTCertificateList & certs)282 CertificateList CreateX509CertificateListFromCERTCertificates(
283     const ScopedCERTCertificateList& certs) {
284   CertificateList result;
285   result.reserve(certs.size());
286   for (const ScopedCERTCertificate& cert : certs) {
287     scoped_refptr<X509Certificate> x509_cert(
288         CreateX509CertificateFromCERTCertificate(cert.get()));
289     if (!x509_cert)
290       return {};
291     result.push_back(std::move(x509_cert));
292   }
293   return result;
294 }
295 
GetDEREncoded(CERTCertificate * cert,std::string * der_encoded)296 bool GetDEREncoded(CERTCertificate* cert, std::string* der_encoded) {
297   if (!cert || !cert->derCert.len)
298     return false;
299   der_encoded->assign(reinterpret_cast<char*>(cert->derCert.data),
300                       cert->derCert.len);
301   return true;
302 }
303 
GetPEMEncoded(CERTCertificate * cert,std::string * pem_encoded)304 bool GetPEMEncoded(CERTCertificate* cert, std::string* pem_encoded) {
305   if (!cert || !cert->derCert.len)
306     return false;
307   std::string der(reinterpret_cast<char*>(cert->derCert.data),
308                   cert->derCert.len);
309   return X509Certificate::GetPEMEncodedFromDER(der, pem_encoded);
310 }
311 
GetRFC822SubjectAltNames(CERTCertificate * cert_handle,std::vector<std::string> * names)312 void GetRFC822SubjectAltNames(CERTCertificate* cert_handle,
313                               std::vector<std::string>* names) {
314   crypto::ScopedSECItem alt_name(SECITEM_AllocItem(nullptr, nullptr, 0));
315   DCHECK(alt_name.get());
316 
317   names->clear();
318   SECStatus rv = CERT_FindCertExtension(
319       cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
320   if (rv != SECSuccess)
321     return;
322 
323   crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
324   DCHECK(arena.get());
325 
326   CERTGeneralName* alt_name_list;
327   alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
328 
329   CERTGeneralName* name = alt_name_list;
330   while (name) {
331     if (name->type == certRFC822Name) {
332       names->push_back(
333           std::string(reinterpret_cast<char*>(name->name.other.data),
334                       name->name.other.len));
335     }
336     name = CERT_GetNextGeneralName(name);
337     if (name == alt_name_list)
338       break;
339   }
340 }
341 
GetUPNSubjectAltNames(CERTCertificate * cert_handle,std::vector<std::string> * names)342 void GetUPNSubjectAltNames(CERTCertificate* cert_handle,
343                            std::vector<std::string>* names) {
344   crypto::ScopedSECItem alt_name(SECITEM_AllocItem(nullptr, nullptr, 0));
345   DCHECK(alt_name.get());
346 
347   names->clear();
348   SECStatus rv = CERT_FindCertExtension(
349       cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
350   if (rv != SECSuccess)
351     return;
352 
353   crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
354   DCHECK(arena.get());
355 
356   CERTGeneralName* alt_name_list;
357   alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
358 
359   CERTGeneralName* name = alt_name_list;
360   while (name) {
361     if (name->type == certOtherName) {
362       OtherName* on = &name->name.OthName;
363       if (on->oid.len == sizeof(kUpnOid) &&
364           memcmp(on->oid.data, kUpnOid, sizeof(kUpnOid)) == 0) {
365         SECItem decoded;
366         if (SEC_QuickDERDecodeItem(arena.get(), &decoded,
367                                    SEC_ASN1_GET(SEC_UTF8StringTemplate),
368                                    &name->name.OthName.name) == SECSuccess) {
369           names->push_back(
370               std::string(reinterpret_cast<char*>(decoded.data), decoded.len));
371         }
372       }
373     }
374     name = CERT_GetNextGeneralName(name);
375     if (name == alt_name_list)
376       break;
377   }
378 }
379 
GetDefaultUniqueNickname(CERTCertificate * nss_cert,CertType type,PK11SlotInfo * slot)380 std::string GetDefaultUniqueNickname(CERTCertificate* nss_cert,
381                                      CertType type,
382                                      PK11SlotInfo* slot) {
383   return GetUniqueNicknameForSlot(GetDefaultNickname(nss_cert, type),
384                                   &nss_cert->derSubject, slot);
385 }
386 
GetCERTNameDisplayName(CERTName * name)387 std::string GetCERTNameDisplayName(CERTName* name) {
388   // Search for attributes in the Name, in this order: CN, O and OU.
389   CERTAVA* ou_ava = nullptr;
390   CERTAVA* o_ava = nullptr;
391   CERTRDN** rdns = name->rdns;
392   for (size_t rdn = 0; rdns[rdn]; ++rdn) {
393     CERTAVA** avas = rdns[rdn]->avas;
394     for (size_t pair = 0; avas[pair] != nullptr; ++pair) {
395       SECOidTag tag = CERT_GetAVATag(avas[pair]);
396       if (tag == SEC_OID_AVA_COMMON_NAME) {
397         // If CN is found, return immediately.
398         return DecodeAVAValue(avas[pair]);
399       }
400       // If O or OU is found, save the first one of each so that it can be
401       // returned later if no CN attribute is found.
402       if (tag == SEC_OID_AVA_ORGANIZATION_NAME && !o_ava)
403         o_ava = avas[pair];
404       if (tag == SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME && !ou_ava)
405         ou_ava = avas[pair];
406     }
407   }
408   if (o_ava)
409     return DecodeAVAValue(o_ava);
410   if (ou_ava)
411     return DecodeAVAValue(ou_ava);
412   return std::string();
413 }
414 
GetValidityTimes(CERTCertificate * cert,base::Time * not_before,base::Time * not_after)415 bool GetValidityTimes(CERTCertificate* cert,
416                       base::Time* not_before,
417                       base::Time* not_after) {
418   PRTime pr_not_before, pr_not_after;
419   if (CERT_GetCertTimes(cert, &pr_not_before, &pr_not_after) == SECSuccess) {
420     if (not_before)
421       *not_before = crypto::PRTimeToBaseTime(pr_not_before);
422     if (not_after)
423       *not_after = crypto::PRTimeToBaseTime(pr_not_after);
424     return true;
425   }
426   return false;
427 }
428 
CalculateFingerprint256(CERTCertificate * cert)429 SHA256HashValue CalculateFingerprint256(CERTCertificate* cert) {
430   SHA256HashValue sha256;
431   memset(sha256.data, 0, sizeof(sha256.data));
432 
433   DCHECK(cert->derCert.data);
434   DCHECK_NE(0U, cert->derCert.len);
435 
436   SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, sha256.data, cert->derCert.data,
437                               cert->derCert.len);
438   DCHECK_EQ(SECSuccess, rv);
439 
440   return sha256;
441 }
442 
ImportUserCert(CERTCertificate * cert)443 int ImportUserCert(CERTCertificate* cert) {
444   return mozilla_security_manager::ImportUserCert(cert);
445 }
446 
447 }  // namespace net::x509_util
448