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.
5 #include "chromeos/network/client_cert_resolver.h"
8 #include <certt.h> // for (SECCertUsageEnum) certUsageAnyCA
14 #include "base/bind.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/stl_util.h"
18 #include "base/task_runner.h"
19 #include "base/threading/worker_pool.h"
20 #include "chromeos/cert_loader.h"
21 #include "chromeos/dbus/dbus_thread_manager.h"
22 #include "chromeos/dbus/shill_service_client.h"
23 #include "chromeos/network/managed_network_configuration_handler.h"
24 #include "chromeos/network/network_state.h"
25 #include "components/onc/onc_constants.h"
26 #include "dbus/object_path.h"
27 #include "net/cert/scoped_nss_types.h"
28 #include "net/cert/x509_certificate.h"
32 // Describes a network |network_path| for which a matching certificate |cert_id|
33 // was found or for which no certificate was found (|cert_id| will be empty).
34 struct ClientCertResolver::NetworkAndMatchingCert
{
35 NetworkAndMatchingCert(const std::string
& network_path
,
36 client_cert::ConfigType config_type
,
37 const std::string
& cert_id
,
39 : service_path(network_path
),
40 cert_config_type(config_type
),
42 key_slot_id(slot_id
) {}
44 std::string service_path
;
45 client_cert::ConfigType cert_config_type
;
47 // The id of the matching certificate or empty if no certificate was found.
48 std::string pkcs11_id
;
50 // The id of the slot containing the certificate and the private key.
54 typedef std::vector
<ClientCertResolver::NetworkAndMatchingCert
>
59 // Returns true if |vector| contains |value|.
61 bool ContainsValue(const std::vector
<T
>& vector
, const T
& value
) {
62 return find(vector
.begin(), vector
.end(), value
) != vector
.end();
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
);
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
)
80 pem_encoded_issuer(issuer
) {}
82 scoped_refptr
<net::X509Certificate
> cert
;
83 std::string pem_encoded_issuer
;
86 bool CompareCertExpiration(const CertAndIssuer
& a
,
87 const CertAndIssuer
& b
) {
88 return (a
.cert
->valid_expiry() > b
.cert
->valid_expiry());
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 const client_cert::ClientCertConfig
& client_cert_config
)
96 : service_path(network_path
),
97 cert_config(client_cert_config
) {}
99 std::string service_path
;
100 client_cert::ClientCertConfig cert_config
;
103 // A unary predicate that returns true if the given CertAndIssuer matches the
104 // given certificate pattern.
105 struct MatchCertWithPattern
{
106 explicit MatchCertWithPattern(const CertificatePattern
& cert_pattern
)
107 : pattern(cert_pattern
) {}
109 bool operator()(const CertAndIssuer
& cert_and_issuer
) {
110 if (!pattern
.issuer().Empty() &&
111 !client_cert::CertPrincipalMatches(pattern
.issuer(),
112 cert_and_issuer
.cert
->issuer())) {
115 if (!pattern
.subject().Empty() &&
116 !client_cert::CertPrincipalMatches(pattern
.subject(),
117 cert_and_issuer
.cert
->subject())) {
121 const std::vector
<std::string
>& issuer_ca_pems
= pattern
.issuer_ca_pems();
122 if (!issuer_ca_pems
.empty() &&
123 !ContainsValue(issuer_ca_pems
, cert_and_issuer
.pem_encoded_issuer
)) {
129 const CertificatePattern pattern
;
132 std::vector
<CertAndIssuer
> CreateSortedCertAndIssuerList(
133 const net::CertificateList
& certs
) {
134 // Filter all client certs and determines each certificate's issuer, which is
135 // required for the pattern matching.
136 std::vector
<CertAndIssuer
> client_certs
;
137 for (net::CertificateList::const_iterator it
= certs
.begin();
138 it
!= certs
.end(); ++it
) {
139 const net::X509Certificate
& cert
= **it
;
140 if (cert
.valid_expiry().is_null() || cert
.HasExpired() ||
141 !HasPrivateKey(cert
) ||
142 !CertLoader::IsCertificateHardwareBacked(&cert
)) {
145 net::ScopedCERTCertificate
issuer_handle(
146 CERT_FindCertIssuer(cert
.os_cert_handle(), PR_Now(), certUsageAnyCA
));
147 if (!issuer_handle
) {
148 LOG(ERROR
) << "Couldn't find an issuer.";
151 scoped_refptr
<net::X509Certificate
> issuer
=
152 net::X509Certificate::CreateFromHandle(
154 net::X509Certificate::OSCertHandles() /* no intermediate certs */);
156 LOG(ERROR
) << "Couldn't create issuer cert.";
159 std::string pem_encoded_issuer
;
160 if (!net::X509Certificate::GetPEMEncoded(issuer
->os_cert_handle(),
161 &pem_encoded_issuer
)) {
162 LOG(ERROR
) << "Couldn't PEM-encode certificate.";
165 client_certs
.push_back(CertAndIssuer(*it
, pem_encoded_issuer
));
168 std::sort(client_certs
.begin(), client_certs
.end(), &CompareCertExpiration
);
172 // Searches for matches between |networks| and |certs| and writes matches to
173 // |matches|. Because this calls NSS functions and is potentially slow, it must
174 // be run on a worker thread.
175 void FindCertificateMatches(const net::CertificateList
& certs
,
176 std::vector
<NetworkAndCertPattern
>* networks
,
177 NetworkCertMatches
* matches
) {
178 std::vector
<CertAndIssuer
> client_certs(CreateSortedCertAndIssuerList(certs
));
180 for (std::vector
<NetworkAndCertPattern
>::const_iterator it
=
182 it
!= networks
->end(); ++it
) {
183 std::vector
<CertAndIssuer
>::iterator cert_it
=
184 std::find_if(client_certs
.begin(),
186 MatchCertWithPattern(it
->cert_config
.pattern
));
187 std::string pkcs11_id
;
189 if (cert_it
== client_certs
.end()) {
190 VLOG(1) << "Couldn't find a matching client cert for network "
192 // Leave |pkcs11_id| empty to indicate that no cert was found for this
196 CertLoader::GetPkcs11IdAndSlotForCert(*cert_it
->cert
, &slot_id
);
197 if (pkcs11_id
.empty()) {
198 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
199 // So far this error is not expected to happen. We can just continue, in
200 // the worst case the user can remove the problematic cert.
204 matches
->push_back(ClientCertResolver::NetworkAndMatchingCert(
205 it
->service_path
, it
->cert_config
.location
, pkcs11_id
, slot_id
));
209 void LogError(const std::string
& service_path
,
210 const std::string
& dbus_error_name
,
211 const std::string
& dbus_error_message
) {
212 network_handler::ShillErrorCallbackFunction(
213 "ClientCertResolver.SetProperties failed",
215 network_handler::ErrorCallback(),
220 bool ClientCertificatesLoaded() {
221 if (!CertLoader::Get()->certificates_loaded()) {
222 VLOG(1) << "Certificates not loaded yet.";
230 ClientCertResolver::ClientCertResolver()
231 : resolve_task_running_(false),
232 network_properties_changed_(false),
233 network_state_handler_(NULL
),
234 managed_network_config_handler_(NULL
),
235 weak_ptr_factory_(this) {
238 ClientCertResolver::~ClientCertResolver() {
239 if (network_state_handler_
)
240 network_state_handler_
->RemoveObserver(this, FROM_HERE
);
241 if (CertLoader::IsInitialized())
242 CertLoader::Get()->RemoveObserver(this);
243 if (managed_network_config_handler_
)
244 managed_network_config_handler_
->RemoveObserver(this);
247 void ClientCertResolver::Init(
248 NetworkStateHandler
* network_state_handler
,
249 ManagedNetworkConfigurationHandler
* managed_network_config_handler
) {
250 DCHECK(network_state_handler
);
251 network_state_handler_
= network_state_handler
;
252 network_state_handler_
->AddObserver(this, FROM_HERE
);
254 DCHECK(managed_network_config_handler
);
255 managed_network_config_handler_
= managed_network_config_handler
;
256 managed_network_config_handler_
->AddObserver(this);
258 CertLoader::Get()->AddObserver(this);
261 void ClientCertResolver::SetSlowTaskRunnerForTest(
262 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
263 slow_task_runner_for_test_
= task_runner
;
266 void ClientCertResolver::AddObserver(Observer
* observer
) {
267 observers_
.AddObserver(observer
);
270 void ClientCertResolver::RemoveObserver(Observer
* observer
) {
271 observers_
.RemoveObserver(observer
);
274 bool ClientCertResolver::IsAnyResolveTaskRunning() const {
275 return resolve_task_running_
;
279 bool ClientCertResolver::ResolveCertificatePatternSync(
280 const client_cert::ConfigType client_cert_type
,
281 const CertificatePattern
& pattern
,
282 base::DictionaryValue
* shill_properties
) {
283 // Prepare and sort the list of known client certs.
284 std::vector
<CertAndIssuer
> client_certs(
285 CreateSortedCertAndIssuerList(CertLoader::Get()->cert_list()));
287 // Search for a certificate matching the pattern.
288 std::vector
<CertAndIssuer
>::iterator cert_it
= std::find_if(
289 client_certs
.begin(), client_certs
.end(), MatchCertWithPattern(pattern
));
291 if (cert_it
== client_certs
.end()) {
292 VLOG(1) << "Couldn't find a matching client cert";
293 client_cert::SetEmptyShillProperties(client_cert_type
, shill_properties
);
298 std::string pkcs11_id
=
299 CertLoader::GetPkcs11IdAndSlotForCert(*cert_it
->cert
, &slot_id
);
300 if (pkcs11_id
.empty()) {
301 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
302 // So far this error is not expected to happen. We can just continue, in
303 // the worst case the user can remove the problematic cert.
306 client_cert::SetShillProperties(
307 client_cert_type
, slot_id
, pkcs11_id
, shill_properties
);
311 void ClientCertResolver::NetworkListChanged() {
312 VLOG(2) << "NetworkListChanged.";
313 if (!ClientCertificatesLoaded())
315 // Configure only networks that were not configured before.
317 // We'll drop networks from |resolved_networks_|, which are not known anymore.
318 std::set
<std::string
> old_resolved_networks
;
319 old_resolved_networks
.swap(resolved_networks_
);
321 NetworkStateHandler::NetworkStateList networks
;
322 network_state_handler_
->GetNetworkListByType(
323 NetworkTypePattern::Default(),
324 true /* configured_only */,
325 false /* visible_only */,
329 NetworkStateHandler::NetworkStateList networks_to_check
;
330 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
331 networks
.begin(); it
!= networks
.end(); ++it
) {
332 const std::string
& service_path
= (*it
)->path();
333 if (ContainsKey(old_resolved_networks
, service_path
)) {
334 resolved_networks_
.insert(service_path
);
337 networks_to_check
.push_back(*it
);
340 ResolveNetworks(networks_to_check
);
343 void ClientCertResolver::OnCertificatesLoaded(
344 const net::CertificateList
& cert_list
,
346 VLOG(2) << "OnCertificatesLoaded.";
347 if (!ClientCertificatesLoaded())
349 // Compare all networks with all certificates.
350 NetworkStateHandler::NetworkStateList networks
;
351 network_state_handler_
->GetNetworkListByType(
352 NetworkTypePattern::Default(),
353 true /* configured_only */,
354 false /* visible_only */,
357 ResolveNetworks(networks
);
360 void ClientCertResolver::PolicyAppliedToNetwork(
361 const std::string
& service_path
) {
362 VLOG(2) << "PolicyAppliedToNetwork " << service_path
;
363 if (!ClientCertificatesLoaded())
365 // Compare this network with all certificates.
366 const NetworkState
* network
=
367 network_state_handler_
->GetNetworkStateFromServicePath(
368 service_path
, true /* configured_only */);
370 LOG(ERROR
) << "service path '" << service_path
<< "' unknown.";
373 NetworkStateHandler::NetworkStateList networks
;
374 networks
.push_back(network
);
375 ResolveNetworks(networks
);
378 void ClientCertResolver::ResolveNetworks(
379 const NetworkStateHandler::NetworkStateList
& networks
) {
380 scoped_ptr
<std::vector
<NetworkAndCertPattern
>> networks_to_resolve(
381 new std::vector
<NetworkAndCertPattern
>);
383 // Filter networks with ClientCertPattern. As ClientCertPatterns can only be
384 // set by policy, we check there.
385 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
386 networks
.begin(); it
!= networks
.end(); ++it
) {
387 const NetworkState
* network
= *it
;
389 // In any case, don't check this network again in NetworkListChanged.
390 resolved_networks_
.insert(network
->path());
392 // If this network is not configured, it cannot have a ClientCertPattern.
393 if (network
->profile_path().empty())
396 const base::DictionaryValue
* policy
=
397 managed_network_config_handler_
->FindPolicyByGuidAndProfile(
398 network
->guid(), network
->profile_path());
401 VLOG(1) << "The policy for network " << network
->path() << " with GUID "
402 << network
->guid() << " is not available yet.";
403 // Skip this network for now. Once the policy is loaded, PolicyApplied()
408 VLOG(2) << "Inspecting network " << network
->path();
409 client_cert::ClientCertConfig cert_config
;
410 OncToClientCertConfig(*policy
, &cert_config
);
412 // Skip networks that don't have a ClientCertPattern.
413 if (cert_config
.client_cert_type
!= ::onc::client_cert::kPattern
)
416 networks_to_resolve
->push_back(
417 NetworkAndCertPattern(network
->path(), cert_config
));
420 if (networks_to_resolve
->empty()) {
421 VLOG(1) << "No networks to resolve.";
422 NotifyResolveRequestCompleted();
426 if (resolve_task_running_
) {
427 VLOG(1) << "A resolve task is already running. Queue this request.";
428 for (const NetworkAndCertPattern
& network_and_pattern
:
429 *networks_to_resolve
) {
430 queued_networks_to_resolve_
.insert(network_and_pattern
.service_path
);
435 VLOG(2) << "Start task for resolving client cert patterns.";
436 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
439 base::WorkerPool::GetTaskRunner(true /* task is slow */).get();
441 resolve_task_running_
= true;
442 NetworkCertMatches
* matches
= new NetworkCertMatches
;
443 task_runner
->PostTaskAndReply(
445 base::Bind(&FindCertificateMatches
,
446 CertLoader::Get()->cert_list(),
447 base::Owned(networks_to_resolve
.release()),
449 base::Bind(&ClientCertResolver::ConfigureCertificates
,
450 weak_ptr_factory_
.GetWeakPtr(),
451 base::Owned(matches
)));
454 void ClientCertResolver::ResolvePendingNetworks() {
455 NetworkStateHandler::NetworkStateList networks
;
456 network_state_handler_
->GetNetworkListByType(NetworkTypePattern::Default(),
457 true /* configured_only */,
458 false /* visible_only */,
462 NetworkStateHandler::NetworkStateList networks_to_resolve
;
463 for (const NetworkState
* network
: networks
) {
464 if (queued_networks_to_resolve_
.count(network
->path()) > 0)
465 networks_to_resolve
.push_back(network
);
467 VLOG(1) << "Resolve pending " << networks_to_resolve
.size() << " networks.";
468 queued_networks_to_resolve_
.clear();
469 ResolveNetworks(networks_to_resolve
);
472 void ClientCertResolver::ConfigureCertificates(NetworkCertMatches
* matches
) {
473 for (NetworkCertMatches::const_iterator it
= matches
->begin();
474 it
!= matches
->end(); ++it
) {
475 VLOG(1) << "Configuring certificate of network " << it
->service_path
;
476 base::DictionaryValue shill_properties
;
477 if (it
->pkcs11_id
.empty()) {
478 client_cert::SetEmptyShillProperties(it
->cert_config_type
,
481 client_cert::SetShillProperties(it
->cert_config_type
,
486 network_properties_changed_
= true;
487 DBusThreadManager::Get()->GetShillServiceClient()->
488 SetProperties(dbus::ObjectPath(it
->service_path
),
490 base::Bind(&base::DoNothing
),
491 base::Bind(&LogError
, it
->service_path
));
492 network_state_handler_
->RequestUpdateForNetwork(it
->service_path
);
494 if (queued_networks_to_resolve_
.empty())
495 NotifyResolveRequestCompleted();
497 ResolvePendingNetworks();
500 void ClientCertResolver::NotifyResolveRequestCompleted() {
501 VLOG(2) << "Notify observers: " << (network_properties_changed_
? "" : "no ")
502 << "networks changed.";
503 resolve_task_running_
= false;
504 const bool changed
= network_properties_changed_
;
505 network_properties_changed_
= false;
506 FOR_EACH_OBSERVER(Observer
, observers_
, ResolveRequestCompleted(changed
));
509 } // namespace chromeos