Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chromeos / network / client_cert_resolver.cc
1 // Copyright 2013 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 "chromeos/network/client_cert_resolver.h"
6
7 #include <cert.h>
8 #include <certt.h>  // for (SECCertUsageEnum) certUsageAnyCA
9 #include <pk11pub.h>
10
11 #include <algorithm>
12 #include <string>
13
14 #include "base/bind.h"
15 #include "base/location.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/task_runner.h"
19 #include "base/threading/worker_pool.h"
20 #include "base/time/time.h"
21 #include "chromeos/cert_loader.h"
22 #include "chromeos/dbus/dbus_thread_manager.h"
23 #include "chromeos/dbus/shill_service_client.h"
24 #include "chromeos/network/certificate_pattern.h"
25 #include "chromeos/network/client_cert_util.h"
26 #include "chromeos/network/favorite_state.h"
27 #include "chromeos/network/managed_network_configuration_handler.h"
28 #include "chromeos/network/network_state_handler.h"
29 #include "chromeos/network/network_ui_data.h"
30 #include "chromeos/tpm_token_loader.h"
31 #include "components/onc/onc_constants.h"
32 #include "dbus/object_path.h"
33 #include "net/cert/scoped_nss_types.h"
34 #include "net/cert/x509_certificate.h"
35
36 namespace chromeos {
37
38 // Describes a network |network_path| for which a matching certificate |cert_id|
39 // was found.
40 struct ClientCertResolver::NetworkAndMatchingCert {
41   NetworkAndMatchingCert(const std::string& network_path,
42                          client_cert::ConfigType config_type,
43                          const std::string& cert_id)
44       : service_path(network_path),
45         cert_config_type(config_type),
46         pkcs11_id(cert_id) {}
47
48   std::string service_path;
49   client_cert::ConfigType cert_config_type;
50   // The id of the matching certificate.
51   std::string pkcs11_id;
52 };
53
54 typedef std::vector<ClientCertResolver::NetworkAndMatchingCert>
55     NetworkCertMatches;
56
57 namespace {
58
59 // Returns true if |vector| contains |value|.
60 template <class T>
61 bool ContainsValue(const std::vector<T>& vector, const T& value) {
62   return find(vector.begin(), vector.end(), value) != vector.end();
63 }
64
65 // Returns true if a private key for certificate |cert| is installed.
66 bool HasPrivateKey(const net::X509Certificate& cert) {
67   PK11SlotInfo* slot = PK11_KeyForCertExists(cert.os_cert_handle(), NULL, NULL);
68   if (!slot)
69     return false;
70
71   PK11_FreeSlot(slot);
72   return true;
73 }
74
75 // Describes a certificate which is issued by |issuer| (encoded as PEM).
76 struct CertAndIssuer {
77   CertAndIssuer(const scoped_refptr<net::X509Certificate>& certificate,
78                 const std::string& issuer)
79       : cert(certificate),
80         pem_encoded_issuer(issuer) {}
81
82   scoped_refptr<net::X509Certificate> cert;
83   std::string pem_encoded_issuer;
84 };
85
86 bool CompareCertExpiration(const CertAndIssuer& a,
87                            const CertAndIssuer& b) {
88   return (a.cert->valid_expiry() > b.cert->valid_expiry());
89 }
90
91 // Describes a network that is configured with the certificate pattern
92 // |client_cert_pattern|.
93 struct NetworkAndCertPattern {
94   NetworkAndCertPattern(const std::string& network_path,
95                         client_cert::ConfigType config_type,
96                         const CertificatePattern& pattern)
97       : service_path(network_path),
98         cert_config_type(config_type),
99         client_cert_pattern(pattern) {}
100   std::string service_path;
101   client_cert::ConfigType cert_config_type;
102   CertificatePattern client_cert_pattern;
103 };
104
105 // A unary predicate that returns true if the given CertAndIssuer matches the
106 // certificate pattern of the NetworkAndCertPattern.
107 struct MatchCertWithPattern {
108   explicit MatchCertWithPattern(const NetworkAndCertPattern& pattern)
109       : net_and_pattern(pattern) {}
110
111   bool operator()(const CertAndIssuer& cert_and_issuer) {
112     const CertificatePattern& pattern = net_and_pattern.client_cert_pattern;
113     if (!pattern.issuer().Empty() &&
114         !client_cert::CertPrincipalMatches(pattern.issuer(),
115                                            cert_and_issuer.cert->issuer())) {
116       return false;
117     }
118     if (!pattern.subject().Empty() &&
119         !client_cert::CertPrincipalMatches(pattern.subject(),
120                                            cert_and_issuer.cert->subject())) {
121       return false;
122     }
123
124     const std::vector<std::string>& issuer_ca_pems = pattern.issuer_ca_pems();
125     if (!issuer_ca_pems.empty() &&
126         !ContainsValue(issuer_ca_pems, cert_and_issuer.pem_encoded_issuer)) {
127       return false;
128     }
129     return true;
130   }
131
132   NetworkAndCertPattern net_and_pattern;
133 };
134
135 // Searches for matches between |networks| and |certs| and writes matches to
136 // |matches|. Because this calls NSS functions and is potentially slow, it must
137 // be run on a worker thread.
138 void FindCertificateMatches(const net::CertificateList& certs,
139                             std::vector<NetworkAndCertPattern>* networks,
140                             NetworkCertMatches* matches) {
141   // Filter all client certs and determines each certificate's issuer, which is
142   // required for the pattern matching.
143   std::vector<CertAndIssuer> client_certs;
144   for (net::CertificateList::const_iterator it = certs.begin();
145        it != certs.end(); ++it) {
146     const net::X509Certificate& cert = **it;
147     if (cert.valid_expiry().is_null() || cert.HasExpired() ||
148         !HasPrivateKey(cert)) {
149       continue;
150     }
151     net::ScopedCERTCertificate issuer_handle(
152         CERT_FindCertIssuer(cert.os_cert_handle(), PR_Now(), certUsageAnyCA));
153     if (!issuer_handle) {
154       LOG(ERROR) << "Couldn't find an issuer.";
155       continue;
156     }
157     scoped_refptr<net::X509Certificate> issuer =
158         net::X509Certificate::CreateFromHandle(
159             issuer_handle.get(),
160             net::X509Certificate::OSCertHandles() /* no intermediate certs */);
161     if (!issuer) {
162       LOG(ERROR) << "Couldn't create issuer cert.";
163       continue;
164     }
165     std::string pem_encoded_issuer;
166     if (!net::X509Certificate::GetPEMEncoded(issuer->os_cert_handle(),
167                                              &pem_encoded_issuer)) {
168       LOG(ERROR) << "Couldn't PEM-encode certificate.";
169       continue;
170     }
171     client_certs.push_back(CertAndIssuer(*it, pem_encoded_issuer));
172   }
173
174   std::sort(client_certs.begin(), client_certs.end(), &CompareCertExpiration);
175
176   for (std::vector<NetworkAndCertPattern>::const_iterator it =
177            networks->begin();
178        it != networks->end(); ++it) {
179     std::vector<CertAndIssuer>::iterator cert_it = std::find_if(
180         client_certs.begin(), client_certs.end(), MatchCertWithPattern(*it));
181     if (cert_it == client_certs.end()) {
182       LOG(WARNING) << "Couldn't find a matching client cert for network "
183                    << it->service_path;
184       continue;
185     }
186     std::string pkcs11_id = CertLoader::GetPkcs11IdForCert(*cert_it->cert);
187     if (pkcs11_id.empty()) {
188       LOG(ERROR) << "Couldn't determine PKCS#11 ID.";
189       continue;
190     }
191     matches->push_back(ClientCertResolver::NetworkAndMatchingCert(
192         it->service_path, it->cert_config_type, pkcs11_id));
193   }
194 }
195
196 // Determines the type of the CertificatePattern configuration, i.e. is it a
197 // pattern within an EAP, IPsec or OpenVPN configuration.
198 client_cert::ConfigType OncToClientCertConfigurationType(
199     const base::DictionaryValue& network_config) {
200   using namespace ::onc;
201
202   const base::DictionaryValue* wifi = NULL;
203   network_config.GetDictionaryWithoutPathExpansion(network_config::kWiFi,
204                                                    &wifi);
205   if (wifi) {
206     const base::DictionaryValue* eap = NULL;
207     wifi->GetDictionaryWithoutPathExpansion(wifi::kEAP, &eap);
208     if (!eap)
209       return client_cert::CONFIG_TYPE_NONE;
210     return client_cert::CONFIG_TYPE_EAP;
211   }
212
213   const base::DictionaryValue* vpn = NULL;
214   network_config.GetDictionaryWithoutPathExpansion(network_config::kVPN, &vpn);
215   if (vpn) {
216     const base::DictionaryValue* openvpn = NULL;
217     vpn->GetDictionaryWithoutPathExpansion(vpn::kOpenVPN, &openvpn);
218     if (openvpn)
219       return client_cert::CONFIG_TYPE_OPENVPN;
220
221     const base::DictionaryValue* ipsec = NULL;
222     vpn->GetDictionaryWithoutPathExpansion(vpn::kIPsec, &ipsec);
223     if (ipsec)
224       return client_cert::CONFIG_TYPE_IPSEC;
225
226     return client_cert::CONFIG_TYPE_NONE;
227   }
228
229   const base::DictionaryValue* ethernet = NULL;
230   network_config.GetDictionaryWithoutPathExpansion(network_config::kEthernet,
231                                                    &ethernet);
232   if (ethernet) {
233     const base::DictionaryValue* eap = NULL;
234     ethernet->GetDictionaryWithoutPathExpansion(wifi::kEAP, &eap);
235     if (eap)
236       return client_cert::CONFIG_TYPE_EAP;
237     return client_cert::CONFIG_TYPE_NONE;
238   }
239
240   return client_cert::CONFIG_TYPE_NONE;
241 }
242
243 void LogError(const std::string& service_path,
244               const std::string& dbus_error_name,
245               const std::string& dbus_error_message) {
246   network_handler::ShillErrorCallbackFunction(
247       "ClientCertResolver.SetProperties failed",
248       service_path,
249       network_handler::ErrorCallback(),
250       dbus_error_name,
251       dbus_error_message);
252 }
253
254 bool ClientCertificatesLoaded() {
255   if (!CertLoader::Get()->certificates_loaded()) {
256     VLOG(1) << "Certificates not loaded yet.";
257     return false;
258   }
259   if (!CertLoader::Get()->IsHardwareBacked()) {
260     VLOG(1) << "TPM is not available.";
261     return false;
262   }
263   return true;
264 }
265
266 }  // namespace
267
268 ClientCertResolver::ClientCertResolver()
269     : network_state_handler_(NULL),
270       managed_network_config_handler_(NULL),
271       weak_ptr_factory_(this) {
272 }
273
274 ClientCertResolver::~ClientCertResolver() {
275   if (network_state_handler_)
276     network_state_handler_->RemoveObserver(this, FROM_HERE);
277   if (CertLoader::IsInitialized())
278     CertLoader::Get()->RemoveObserver(this);
279   if (managed_network_config_handler_)
280     managed_network_config_handler_->RemoveObserver(this);
281 }
282
283 void ClientCertResolver::Init(
284     NetworkStateHandler* network_state_handler,
285     ManagedNetworkConfigurationHandler* managed_network_config_handler) {
286   DCHECK(network_state_handler);
287   network_state_handler_ = network_state_handler;
288   network_state_handler_->AddObserver(this, FROM_HERE);
289
290   DCHECK(managed_network_config_handler);
291   managed_network_config_handler_ = managed_network_config_handler;
292   managed_network_config_handler_->AddObserver(this);
293
294   CertLoader::Get()->AddObserver(this);
295 }
296
297 void ClientCertResolver::SetSlowTaskRunnerForTest(
298     const scoped_refptr<base::TaskRunner>& task_runner) {
299   slow_task_runner_for_test_ = task_runner;
300 }
301
302 void ClientCertResolver::NetworkListChanged() {
303   VLOG(2) << "NetworkListChanged.";
304   if (!ClientCertificatesLoaded())
305     return;
306   // Configure only networks that were not configured before.
307
308   // We'll drop networks from |resolved_networks_|, which are not known anymore.
309   std::set<std::string> old_resolved_networks;
310   old_resolved_networks.swap(resolved_networks_);
311
312   FavoriteStateList networks;
313   network_state_handler_->GetFavoriteList(&networks);
314
315   FavoriteStateList networks_to_check;
316   for (FavoriteStateList::const_iterator it = networks.begin();
317        it != networks.end(); ++it) {
318     const std::string& service_path = (*it)->path();
319     if (ContainsKey(old_resolved_networks, service_path)) {
320       resolved_networks_.insert(service_path);
321       continue;
322     }
323     networks_to_check.push_back(*it);
324   }
325
326   ResolveNetworks(networks_to_check);
327 }
328
329 void ClientCertResolver::OnCertificatesLoaded(
330     const net::CertificateList& cert_list,
331     bool initial_load) {
332   VLOG(2) << "OnCertificatesLoaded.";
333   if (!ClientCertificatesLoaded())
334     return;
335   // Compare all networks with all certificates.
336   FavoriteStateList networks;
337   network_state_handler_->GetFavoriteList(&networks);
338   ResolveNetworks(networks);
339 }
340
341 void ClientCertResolver::PolicyApplied(const std::string& service_path) {
342   VLOG(2) << "PolicyApplied " << service_path;
343   if (!ClientCertificatesLoaded())
344     return;
345   // Compare this network with all certificates.
346   const FavoriteState* network =
347       network_state_handler_->GetFavoriteState(service_path);
348   if (!network) {
349     LOG(ERROR) << "service path '" << service_path << "' unknown.";
350     return;
351   }
352   FavoriteStateList networks;
353   networks.push_back(network);
354   ResolveNetworks(networks);
355 }
356
357 void ClientCertResolver::ResolveNetworks(const FavoriteStateList& networks) {
358   scoped_ptr<std::vector<NetworkAndCertPattern> > networks_with_pattern(
359       new std::vector<NetworkAndCertPattern>);
360
361   // Filter networks with ClientCertPattern. As ClientCertPatterns can only be
362   // set by policy, we check there.
363   for (FavoriteStateList::const_iterator it = networks.begin();
364        it != networks.end(); ++it) {
365     const FavoriteState* network = *it;
366
367     // In any case, don't check this network again in NetworkListChanged.
368     resolved_networks_.insert(network->path());
369
370     // If this network is not managed, it cannot have a ClientCertPattern.
371     if (network->guid().empty())
372       continue;
373
374     if (network->profile_path().empty()) {
375       LOG(ERROR) << "Network " << network->path()
376                  << " has a GUID but not profile path";
377       continue;
378     }
379     const base::DictionaryValue* policy =
380         managed_network_config_handler_->FindPolicyByGuidAndProfile(
381             network->guid(), network->profile_path());
382
383     if (!policy) {
384       VLOG(1) << "The policy for network " << network->path() << " with GUID "
385               << network->guid() << " is not available yet.";
386       // Skip this network for now. Once the policy is loaded, PolicyApplied()
387       // will retry.
388       continue;
389     }
390
391     VLOG(2) << "Inspecting network " << network->path();
392     // TODO(pneubeck): Access the ClientCertPattern without relying on
393     //   NetworkUIData, which also parses other things that we don't need here.
394     // The ONCSource is irrelevant here.
395     scoped_ptr<NetworkUIData> ui_data(
396         NetworkUIData::CreateFromONC(onc::ONC_SOURCE_NONE, *policy));
397
398     // Skip networks that don't have a ClientCertPattern.
399     if (ui_data->certificate_type() != CLIENT_CERT_TYPE_PATTERN)
400       continue;
401
402     client_cert::ConfigType config_type =
403         OncToClientCertConfigurationType(*policy);
404     if (config_type == client_cert::CONFIG_TYPE_NONE) {
405       LOG(ERROR) << "UIData contains a CertificatePattern, but the policy "
406                  << "doesn't. Network: " << network->path();
407       continue;
408     }
409
410     networks_with_pattern->push_back(NetworkAndCertPattern(
411         network->path(), config_type, ui_data->certificate_pattern()));
412   }
413   if (networks_with_pattern->empty())
414     return;
415
416   VLOG(2) << "Start task for resolving client cert patterns.";
417   base::TaskRunner* task_runner = slow_task_runner_for_test_.get();
418   if (!task_runner)
419     task_runner = base::WorkerPool::GetTaskRunner(true /* task is slow */);
420
421   NetworkCertMatches* matches = new NetworkCertMatches;
422   task_runner->PostTaskAndReply(
423       FROM_HERE,
424       base::Bind(&FindCertificateMatches,
425                  CertLoader::Get()->cert_list(),
426                  base::Owned(networks_with_pattern.release()),
427                  matches),
428       base::Bind(&ClientCertResolver::ConfigureCertificates,
429                  weak_ptr_factory_.GetWeakPtr(),
430                  base::Owned(matches)));
431 }
432
433 void ClientCertResolver::ConfigureCertificates(NetworkCertMatches* matches) {
434   for (NetworkCertMatches::const_iterator it = matches->begin();
435        it != matches->end(); ++it) {
436     VLOG(1) << "Configuring certificate of network " << it->service_path;
437     CertLoader* cert_loader = CertLoader::Get();
438     base::DictionaryValue shill_properties;
439     client_cert::SetShillProperties(
440         it->cert_config_type,
441         base::IntToString(cert_loader->TPMTokenSlotID()),
442         TPMTokenLoader::Get()->tpm_user_pin(),
443         &it->pkcs11_id,
444         &shill_properties);
445     DBusThreadManager::Get()->GetShillServiceClient()->
446         SetProperties(dbus::ObjectPath(it->service_path),
447                         shill_properties,
448                         base::Bind(&base::DoNothing),
449                         base::Bind(&LogError, it->service_path));
450     network_state_handler_->RequestUpdateForNetwork(it->service_path);
451   }
452 }
453
454 }  // namespace chromeos