Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(833)

Side by Side Diff: chrome/browser/chromeos/network_settings/onc_certificate_importer.cc

Issue 11299236: This moves the ONC parsing code into chromeos/network/onc (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fix unit tests Created 8 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 #include "chrome/browser/chromeos/network_settings/onc_certificate_importer.h"
6
7 #include <cert.h>
8 #include <keyhi.h>
9 #include <pk11pub.h>
10
11 #include "base/base64.h"
12 #include "base/logging.h"
13 #include "chrome/browser/chromeos/cros/onc_constants.h"
14 #include "grit/generated_resources.h"
15 #include "net/base/crypto_module.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/nss_cert_database.h"
18 #include "net/base/pem_tokenizer.h"
19 #include "net/base/x509_certificate.h"
20 #include "ui/base/l10n/l10n_util.h"
21
22 namespace {
23
24 // The PEM block header used for DER certificates
25 const char kCertificateHeader[] = "CERTIFICATE";
26 // This is an older PEM marker for DER certificates.
27 const char kX509CertificateHeader[] = "X509 CERTIFICATE";
28
29 } // namespace
30
31 namespace chromeos {
32 namespace onc {
33
34 CertificateImporter::CertificateImporter(
35 NetworkUIData::ONCSource onc_source,
36 bool allow_web_trust_from_policy)
37 : onc_source_(onc_source),
38 allow_web_trust_from_policy_(allow_web_trust_from_policy) {
39 }
40
41 bool CertificateImporter::ParseAndStoreCertificates(
42 const base::ListValue& certificates, std::string* error) {
43 error_.clear();
44 for (size_t i = 0; i < certificates.GetSize(); ++i) {
45 const base::DictionaryValue* certificate = NULL;
46 if (!certificates.GetDictionary(i, &certificate)) {
47 if (error) {
48 *error = l10n_util::GetStringUTF8(
49 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MALFORMED);
50 }
51 return false;
52 }
53
54 if (VLOG_IS_ON(2))
55 VLOG(2) << "Parsing certificate at index " << i << ": " << *certificate;
56
57 if (ParseAndStoreCertificate(*certificate)) {
58 VLOG(2) << "Successfully imported certificate at index " << i;
59 continue;
60 }
61
62 LOG(WARNING) << "Cannot parse certificate at index " << i << ": " << error_;
63 if (error)
64 *error = error_;
65 return false;
66 }
67 return true;
68 }
69
70 bool CertificateImporter::ParseAndStoreCertificate(
71 const base::DictionaryValue& certificate) {
72
73 // Get out the attributes of the given certificate.
74 std::string guid;
75 if (!certificate.GetString(kGUID, &guid) || guid.empty()) {
76 LOG(WARNING) << "Certificate missing GUID identifier";
77 error_ = l10n_util::GetStringUTF8(
78 IDS_NETWORK_CONFIG_ERROR_CERT_GUID_MISSING);
79 return false;
80 }
81
82 bool remove = false;
83 if (certificate.GetBoolean(kRemove, &remove) && remove) {
84 if (!DeleteCertAndKeyByNickname(guid)) {
85 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_CERT_DELETE);
86 return false;
87 } else {
88 return true;
89 }
90 }
91
92 // Not removing, so let's get the data we need to add this certificate.
93 std::string cert_type;
94 certificate.GetString(certificate::kType, &cert_type);
95 if (cert_type == certificate::kServer || cert_type == certificate::kAuthority)
96 return ParseServerOrCaCertificate(cert_type, guid, certificate);
97
98 if (cert_type == certificate::kClient)
99 return ParseClientCertificate(guid, certificate);
100
101 LOG(WARNING) << "ONC File: certificate of unknown type: " << cert_type;
102 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_CERT_TYPE_MISSING);
103 return false;
104 }
105
106 // static
107 void CertificateImporter::ListCertsWithNickname(const std::string& label,
108 net::CertificateList* result) {
109 net::CertificateList all_certs;
110 net::NSSCertDatabase::GetInstance()->ListCerts(&all_certs);
111 result->clear();
112 for (net::CertificateList::iterator iter = all_certs.begin();
113 iter != all_certs.end(); ++iter) {
114 if (iter->get()->os_cert_handle()->nickname) {
115 // Separate the nickname stored in the certificate at the colon, since
116 // NSS likes to store it as token:nickname.
117 const char* delimiter =
118 ::strchr(iter->get()->os_cert_handle()->nickname, ':');
119 if (delimiter) {
120 ++delimiter; // move past the colon.
121 if (strcmp(delimiter, label.c_str()) == 0) {
122 result->push_back(*iter);
123 continue;
124 }
125 }
126 }
127 // Now we find the private key for this certificate and see if it has a
128 // nickname that matches. If there is a private key, and it matches,
129 // then this is a client cert that we are looking for.
130 SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert(
131 iter->get()->os_cert_handle()->slot,
132 iter->get()->os_cert_handle(),
133 NULL); // wincx
134 if (private_key) {
135 char* private_key_nickname = PK11_GetPrivateKeyNickname(private_key);
136 if (private_key_nickname && std::string(label) == private_key_nickname)
137 result->push_back(*iter);
138 PORT_Free(private_key_nickname);
139 SECKEY_DestroyPrivateKey(private_key);
140 }
141 }
142 }
143
144 // static
145 bool CertificateImporter::DeleteCertAndKeyByNickname(const std::string& label) {
146 net::CertificateList cert_list;
147 ListCertsWithNickname(label, &cert_list);
148 bool result = true;
149 for (net::CertificateList::iterator iter = cert_list.begin();
150 iter != cert_list.end(); ++iter) {
151 // If we fail, we try and delete the rest still.
152 // TODO(gspencer): this isn't very "transactional". If we fail on some, but
153 // not all, then it's possible to leave things in a weird state.
154 // Luckily there should only be one cert with a particular
155 // label, and the cert not being found is one of the few reasons the
156 // delete could fail, but still... The other choice is to return
157 // failure immediately, but that doesn't seem to do what is intended.
158 if (!net::NSSCertDatabase::GetInstance()->DeleteCertAndKey(iter->get()))
159 result = false;
160 }
161 return result;
162 }
163
164 bool CertificateImporter::ParseServerOrCaCertificate(
165 const std::string& cert_type,
166 const std::string& guid,
167 const base::DictionaryValue& certificate) {
168 // Device policy can't import certificates.
169 if (onc_source_ == NetworkUIData::ONC_SOURCE_DEVICE_POLICY) {
170 LOG(WARNING) << "Refusing to import certificate from device policy";
171 // This isn't a parsing error, so just return NULL here.
172 return true;
173 }
174
175 bool web_trust = false;
176 const base::ListValue* trust_list = NULL;
177 if (certificate.GetList(certificate::kTrust, &trust_list)) {
178 for (size_t i = 0; i < trust_list->GetSize(); ++i) {
179 std::string trust_type;
180 if (!trust_list->GetString(i, &trust_type)) {
181 LOG(WARNING) << "ONC File: certificate trust is invalid";
182 error_ = l10n_util::GetStringUTF8(
183 IDS_NETWORK_CONFIG_ERROR_CERT_TRUST_INVALID);
184 return false;
185 }
186 if (trust_type == certificate::kWeb) {
187 // "Web" implies that the certificate is to be trusted for SSL
188 // identification.
189 web_trust = true;
190 } else {
191 LOG(WARNING) << "ONC File: certificate contains unknown "
192 << "trust type: " << trust_type;
193 error_ = l10n_util::GetStringUTF8(
194 IDS_NETWORK_CONFIG_ERROR_CERT_TRUST_UNKNOWN);
195 return false;
196 }
197 }
198 }
199
200 // Web trust is only granted to certificates imported for a managed user
201 // on a managed device.
202 if (onc_source_ == NetworkUIData::ONC_SOURCE_USER_POLICY &&
203 web_trust && !allow_web_trust_from_policy_) {
204 LOG(WARNING) << "Web trust not granted for certificate: " << guid;
205 web_trust = false;
206 }
207
208 std::string x509_data;
209 if (!certificate.GetString(certificate::kX509, &x509_data) ||
210 x509_data.empty()) {
211 LOG(WARNING) << "ONC File: certificate missing appropriate "
212 << "certificate data for type: " << cert_type;
213 error_ = l10n_util::GetStringUTF8(
214 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MISSING);
215 return false;
216 }
217
218 // Parse PEM certificate, and get the decoded data for use in creating
219 // certificate below.
220 std::vector<std::string> pem_headers;
221 pem_headers.push_back(kCertificateHeader);
222 pem_headers.push_back(kX509CertificateHeader);
223
224 net::PEMTokenizer pem_tokenizer(x509_data, pem_headers);
225 std::string decoded_x509;
226 if (!pem_tokenizer.GetNext()) {
227 // If we failed to read the data as a PEM file, then let's just try plain
228 // base64 decode: some versions of Spigots didn't apply the PEM marker
229 // strings. For this to work, there has to be no white space, and it has to
230 // only contain the base64-encoded data.
231 if (!base::Base64Decode(x509_data, &decoded_x509)) {
232 LOG(WARNING) << "Unable to base64 decode X509 data: \""
233 << x509_data << "\".";
234 error_ = l10n_util::GetStringUTF8(
235 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MALFORMED);
236 return false;
237 }
238 } else {
239 decoded_x509 = pem_tokenizer.data();
240 }
241
242 scoped_refptr<net::X509Certificate> x509_cert =
243 net::X509Certificate::CreateFromBytesWithNickname(
244 decoded_x509.data(),
245 decoded_x509.size(),
246 guid.c_str());
247 if (!x509_cert.get()) {
248 LOG(WARNING) << "Unable to create X509 certificate from bytes.";
249 error_ = l10n_util::GetStringUTF8(
250 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MALFORMED);
251 return false;
252 }
253
254 // Due to a mismatch regarding cert identity between NSS (cert identity is
255 // determined by the raw bytes) and ONC (cert identity is determined by
256 // GUIDs), we have to special-case a number of situations here:
257 //
258 // a) The cert bits we're trying to insert are already present in the NSS cert
259 // store. This is indicated by the isperm bit in CERTCertificateStr. Since
260 // we might have to update the nick name, we just delete the existing cert
261 // and reimport the cert bits.
262 // b) NSS gives us an actual temporary certificate. In this case, there is no
263 // identical certificate known to NSS, so we can safely import the
264 // certificate. The GUID being imported may still be on a different
265 // certificate, and we could jump through hoops to reimport the existing
266 // certificate with a different nickname. However, that would mean lots of
267 // effort for a case that's pretty much illegal (reusing GUIDs contradicts
268 // the intention of GUIDs), so we just report an error.
269 //
270 // TODO(mnissler, gspencer): We should probably switch to a mode where we
271 // keep our own database for mapping GUIDs to certs in order to enable several
272 // GUIDs to map to the same cert. See http://crosbug.com/26073.
273 net::NSSCertDatabase* cert_database = net::NSSCertDatabase::GetInstance();
274 if (x509_cert->os_cert_handle()->isperm) {
275 if (!cert_database->DeleteCertAndKey(x509_cert.get())) {
276 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_CERT_DELETE);
277 return false;
278 }
279
280 // Reload the cert here to get an actual temporary cert instance.
281 x509_cert =
282 net::X509Certificate::CreateFromBytesWithNickname(
283 decoded_x509.data(),
284 decoded_x509.size(),
285 guid.c_str());
286 if (!x509_cert.get()) {
287 LOG(WARNING) << "Unable to create X509 certificate from bytes.";
288 error_ = l10n_util::GetStringUTF8(
289 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MALFORMED);
290 return false;
291 }
292 DCHECK(!x509_cert->os_cert_handle()->isperm);
293 DCHECK(x509_cert->os_cert_handle()->istemp);
294 }
295
296 // Make sure the GUID is not already taken. Note that for the reimport case we
297 // have removed the existing cert above.
298 net::CertificateList certs;
299 ListCertsWithNickname(guid, &certs);
300 if (!certs.empty()) {
301 LOG(WARNING) << "Cert GUID is already in use: " << guid;
302 error_ = l10n_util::GetStringUTF8(
303 IDS_NETWORK_CONFIG_ERROR_CERT_GUID_COLLISION);
304 return false;
305 }
306
307 net::CertificateList cert_list;
308 cert_list.push_back(x509_cert);
309 net::NSSCertDatabase::ImportCertFailureList failures;
310 bool success = false;
311 net::NSSCertDatabase::TrustBits trust = web_trust ?
312 net::NSSCertDatabase::TRUSTED_SSL :
313 net::NSSCertDatabase::TRUST_DEFAULT;
314 if (cert_type == certificate::kServer)
315 success = cert_database->ImportServerCert(cert_list, trust, &failures);
316 else // Authority cert
317 success = cert_database->ImportCACerts(cert_list, trust, &failures);
318
319 if (!failures.empty()) {
320 LOG(WARNING) << "ONC File: Error ("
321 << net::ErrorToString(failures[0].net_error)
322 << ") importing " << cert_type << " certificate";
323 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_CERT_IMPORT);
324 return false;
325 }
326 if (!success) {
327 LOG(WARNING) << "ONC File: Unknown error importing " << cert_type
328 << " certificate";
329 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_UNKNOWN);
330 return false;
331 }
332
333 return true;
334 }
335
336 bool CertificateImporter::ParseClientCertificate(
337 const std::string& guid,
338 const base::DictionaryValue& certificate) {
339 std::string pkcs12_data;
340 if (!certificate.GetString(certificate::kPKCS12, &pkcs12_data) ||
341 pkcs12_data.empty()) {
342 LOG(WARNING) << "ONC File: PKCS12 data is missing for Client "
343 << "certificate";
344 error_ = l10n_util::GetStringUTF8(
345 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MISSING);
346 return false;
347 }
348
349 std::string decoded_pkcs12;
350 if (!base::Base64Decode(pkcs12_data, &decoded_pkcs12)) {
351 LOG(WARNING) << "Unable to base64 decode PKCS#12 data: \""
352 << pkcs12_data << "\".";
353 error_ = l10n_util::GetStringUTF8(
354 IDS_NETWORK_CONFIG_ERROR_CERT_DATA_MALFORMED);
355 return false;
356 }
357
358 // Since this has a private key, always use the private module.
359 net::NSSCertDatabase* cert_database = net::NSSCertDatabase::GetInstance();
360 scoped_refptr<net::CryptoModule> module(cert_database->GetPrivateModule());
361 net::CertificateList imported_certs;
362
363 int result = cert_database->ImportFromPKCS12(
364 module.get(), decoded_pkcs12, string16(), false, &imported_certs);
365 if (result != net::OK) {
366 LOG(WARNING) << "ONC File: Unable to import Client certificate"
367 << " (error " << net::ErrorToString(result) << ").";
368 error_ = l10n_util::GetStringUTF8(IDS_NETWORK_CONFIG_ERROR_CERT_IMPORT);
369 return false;
370 }
371
372 if (imported_certs.size() == 0) {
373 LOG(WARNING) << "ONC File: PKCS12 data contains no importable certificates";
374 return true;
375 }
376
377 if (imported_certs.size() != 1) {
378 LOG(WARNING) << "ONC File: PKCS12 data contains more than one certificate."
379 << "Only the first one will be imported.";
380 }
381
382 scoped_refptr<net::X509Certificate> cert_result = imported_certs[0];
383
384 // Find the private key associated with this certificate, and set the
385 // nickname on it.
386 SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert(
387 cert_result->os_cert_handle()->slot,
388 cert_result->os_cert_handle(),
389 NULL); // wincx
390 if (private_key) {
391 PK11_SetPrivateKeyNickname(private_key, const_cast<char*>(guid.c_str()));
392 SECKEY_DestroyPrivateKey(private_key);
393 } else {
394 LOG(WARNING) << "ONC File: Unable to find private key for cert";
395 }
396 return true;
397 }
398
399 } // chromeos
400 } // onc
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698