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
13 #include "base/bind.h"
14 #include "base/location.h"
15 #include "base/logging.h"
16 #include "base/stl_util.h"
17 #include "base/task_runner.h"
18 #include "base/threading/worker_pool.h"
19 #include "chromeos/dbus/dbus_thread_manager.h"
20 #include "chromeos/dbus/shill_service_client.h"
21 #include "chromeos/network/managed_network_configuration_handler.h"
22 #include "chromeos/network/network_state.h"
23 #include "components/onc/onc_constants.h"
24 #include "dbus/object_path.h"
25 #include "net/cert/scoped_nss_types.h"
26 #include "net/cert/x509_certificate.h"
30 // Describes a network |network_path| for which a matching certificate |cert_id|
31 // was found or for which no certificate was found (|cert_id| will be empty).
32 struct ClientCertResolver::NetworkAndMatchingCert
{
33 NetworkAndMatchingCert(const std::string
& network_path
,
34 client_cert::ConfigType config_type
,
35 const std::string
& cert_id
,
37 : service_path(network_path
),
38 cert_config_type(config_type
),
40 key_slot_id(slot_id
) {}
42 std::string service_path
;
43 client_cert::ConfigType cert_config_type
;
45 // The id of the matching certificate or empty if no certificate was found.
46 std::string pkcs11_id
;
48 // The id of the slot containing the certificate and the private key.
52 typedef std::vector
<ClientCertResolver::NetworkAndMatchingCert
>
57 // Returns true if |vector| contains |value|.
59 bool ContainsValue(const std::vector
<T
>& vector
, const T
& value
) {
60 return find(vector
.begin(), vector
.end(), value
) != vector
.end();
63 // Returns true if a private key for certificate |cert| is installed.
64 bool HasPrivateKey(const net::X509Certificate
& cert
) {
65 PK11SlotInfo
* slot
= PK11_KeyForCertExists(cert
.os_cert_handle(), NULL
, NULL
);
73 // Describes a certificate which is issued by |issuer| (encoded as PEM).
74 struct CertAndIssuer
{
75 CertAndIssuer(const scoped_refptr
<net::X509Certificate
>& certificate
,
76 const std::string
& issuer
)
78 pem_encoded_issuer(issuer
) {}
80 scoped_refptr
<net::X509Certificate
> cert
;
81 std::string pem_encoded_issuer
;
84 bool CompareCertExpiration(const CertAndIssuer
& a
,
85 const CertAndIssuer
& b
) {
86 return (a
.cert
->valid_expiry() > b
.cert
->valid_expiry());
89 // Describes a network that is configured with the certificate pattern
90 // |client_cert_pattern|.
91 struct NetworkAndCertPattern
{
92 NetworkAndCertPattern(const std::string
& network_path
,
93 const client_cert::ClientCertConfig
& client_cert_config
)
94 : service_path(network_path
),
95 cert_config(client_cert_config
) {}
97 std::string service_path
;
98 client_cert::ClientCertConfig cert_config
;
101 // A unary predicate that returns true if the given CertAndIssuer matches the
102 // given certificate pattern.
103 struct MatchCertWithPattern
{
104 explicit MatchCertWithPattern(const CertificatePattern
& cert_pattern
)
105 : pattern(cert_pattern
) {}
107 bool operator()(const CertAndIssuer
& cert_and_issuer
) {
108 if (!pattern
.issuer().Empty() &&
109 !client_cert::CertPrincipalMatches(pattern
.issuer(),
110 cert_and_issuer
.cert
->issuer())) {
113 if (!pattern
.subject().Empty() &&
114 !client_cert::CertPrincipalMatches(pattern
.subject(),
115 cert_and_issuer
.cert
->subject())) {
119 const std::vector
<std::string
>& issuer_ca_pems
= pattern
.issuer_ca_pems();
120 if (!issuer_ca_pems
.empty() &&
121 !ContainsValue(issuer_ca_pems
, cert_and_issuer
.pem_encoded_issuer
)) {
127 const CertificatePattern pattern
;
130 std::vector
<CertAndIssuer
> CreateSortedCertAndIssuerList(
131 const net::CertificateList
& certs
) {
132 // Filter all client certs and determines each certificate's issuer, which is
133 // required for the pattern matching.
134 std::vector
<CertAndIssuer
> client_certs
;
135 for (net::CertificateList::const_iterator it
= certs
.begin();
136 it
!= certs
.end(); ++it
) {
137 const net::X509Certificate
& cert
= **it
;
138 if (cert
.valid_expiry().is_null() || cert
.HasExpired() ||
139 !HasPrivateKey(cert
) ||
140 !CertLoader::IsCertificateHardwareBacked(&cert
)) {
143 net::ScopedCERTCertificate
issuer_handle(
144 CERT_FindCertIssuer(cert
.os_cert_handle(), PR_Now(), certUsageAnyCA
));
145 if (!issuer_handle
) {
146 LOG(ERROR
) << "Couldn't find an issuer.";
149 scoped_refptr
<net::X509Certificate
> issuer
=
150 net::X509Certificate::CreateFromHandle(
152 net::X509Certificate::OSCertHandles() /* no intermediate certs */);
154 LOG(ERROR
) << "Couldn't create issuer cert.";
157 std::string pem_encoded_issuer
;
158 if (!net::X509Certificate::GetPEMEncoded(issuer
->os_cert_handle(),
159 &pem_encoded_issuer
)) {
160 LOG(ERROR
) << "Couldn't PEM-encode certificate.";
163 client_certs
.push_back(CertAndIssuer(*it
, pem_encoded_issuer
));
166 std::sort(client_certs
.begin(), client_certs
.end(), &CompareCertExpiration
);
170 // Searches for matches between |networks| and |certs| and writes matches to
171 // |matches|. Because this calls NSS functions and is potentially slow, it must
172 // be run on a worker thread.
173 void FindCertificateMatches(const net::CertificateList
& certs
,
174 std::vector
<NetworkAndCertPattern
>* networks
,
175 NetworkCertMatches
* matches
) {
176 std::vector
<CertAndIssuer
> client_certs(CreateSortedCertAndIssuerList(certs
));
178 for (std::vector
<NetworkAndCertPattern
>::const_iterator it
=
180 it
!= networks
->end(); ++it
) {
181 std::vector
<CertAndIssuer
>::iterator cert_it
=
182 std::find_if(client_certs
.begin(),
184 MatchCertWithPattern(it
->cert_config
.pattern
));
185 std::string pkcs11_id
;
187 if (cert_it
== client_certs
.end()) {
188 VLOG(1) << "Couldn't find a matching client cert for network "
190 // Leave |pkcs11_id| empty to indicate that no cert was found for this
194 CertLoader::GetPkcs11IdAndSlotForCert(*cert_it
->cert
, &slot_id
);
195 if (pkcs11_id
.empty()) {
196 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
197 // So far this error is not expected to happen. We can just continue, in
198 // the worst case the user can remove the problematic cert.
202 matches
->push_back(ClientCertResolver::NetworkAndMatchingCert(
203 it
->service_path
, it
->cert_config
.location
, pkcs11_id
, slot_id
));
207 void LogError(const std::string
& service_path
,
208 const std::string
& dbus_error_name
,
209 const std::string
& dbus_error_message
) {
210 network_handler::ShillErrorCallbackFunction(
211 "ClientCertResolver.SetProperties failed",
213 network_handler::ErrorCallback(),
218 bool ClientCertificatesLoaded() {
219 if (!CertLoader::Get()->certificates_loaded()) {
220 VLOG(1) << "Certificates not loaded yet.";
228 ClientCertResolver::ClientCertResolver()
229 : resolve_task_running_(false),
230 network_properties_changed_(false),
231 network_state_handler_(NULL
),
232 managed_network_config_handler_(NULL
),
233 weak_ptr_factory_(this) {
236 ClientCertResolver::~ClientCertResolver() {
237 if (network_state_handler_
)
238 network_state_handler_
->RemoveObserver(this, FROM_HERE
);
239 if (CertLoader::IsInitialized())
240 CertLoader::Get()->RemoveObserver(this);
241 if (managed_network_config_handler_
)
242 managed_network_config_handler_
->RemoveObserver(this);
245 void ClientCertResolver::Init(
246 NetworkStateHandler
* network_state_handler
,
247 ManagedNetworkConfigurationHandler
* managed_network_config_handler
) {
248 DCHECK(network_state_handler
);
249 network_state_handler_
= network_state_handler
;
250 network_state_handler_
->AddObserver(this, FROM_HERE
);
252 DCHECK(managed_network_config_handler
);
253 managed_network_config_handler_
= managed_network_config_handler
;
254 managed_network_config_handler_
->AddObserver(this);
256 CertLoader::Get()->AddObserver(this);
259 void ClientCertResolver::SetSlowTaskRunnerForTest(
260 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
261 slow_task_runner_for_test_
= task_runner
;
264 void ClientCertResolver::AddObserver(Observer
* observer
) {
265 observers_
.AddObserver(observer
);
268 void ClientCertResolver::RemoveObserver(Observer
* observer
) {
269 observers_
.RemoveObserver(observer
);
272 bool ClientCertResolver::IsAnyResolveTaskRunning() const {
273 return resolve_task_running_
;
277 bool ClientCertResolver::ResolveCertificatePatternSync(
278 const client_cert::ConfigType client_cert_type
,
279 const CertificatePattern
& pattern
,
280 base::DictionaryValue
* shill_properties
) {
281 // Prepare and sort the list of known client certs.
282 std::vector
<CertAndIssuer
> client_certs(
283 CreateSortedCertAndIssuerList(CertLoader::Get()->cert_list()));
285 // Search for a certificate matching the pattern.
286 std::vector
<CertAndIssuer
>::iterator cert_it
= std::find_if(
287 client_certs
.begin(), client_certs
.end(), MatchCertWithPattern(pattern
));
289 if (cert_it
== client_certs
.end()) {
290 VLOG(1) << "Couldn't find a matching client cert";
291 client_cert::SetEmptyShillProperties(client_cert_type
, shill_properties
);
296 std::string pkcs11_id
=
297 CertLoader::GetPkcs11IdAndSlotForCert(*cert_it
->cert
, &slot_id
);
298 if (pkcs11_id
.empty()) {
299 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
300 // So far this error is not expected to happen. We can just continue, in
301 // the worst case the user can remove the problematic cert.
304 client_cert::SetShillProperties(
305 client_cert_type
, slot_id
, pkcs11_id
, shill_properties
);
309 void ClientCertResolver::NetworkListChanged() {
310 VLOG(2) << "NetworkListChanged.";
311 if (!ClientCertificatesLoaded())
313 // Configure only networks that were not configured before.
315 // We'll drop networks from |resolved_networks_|, which are not known anymore.
316 std::set
<std::string
> old_resolved_networks
;
317 old_resolved_networks
.swap(resolved_networks_
);
319 NetworkStateHandler::NetworkStateList networks
;
320 network_state_handler_
->GetNetworkListByType(
321 NetworkTypePattern::Default(),
322 true /* configured_only */,
323 false /* visible_only */,
327 NetworkStateHandler::NetworkStateList networks_to_check
;
328 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
329 networks
.begin(); it
!= networks
.end(); ++it
) {
330 const std::string
& service_path
= (*it
)->path();
331 if (ContainsKey(old_resolved_networks
, service_path
)) {
332 resolved_networks_
.insert(service_path
);
335 networks_to_check
.push_back(*it
);
338 ResolveNetworks(networks_to_check
);
341 void ClientCertResolver::OnCertificatesLoaded(
342 const net::CertificateList
& cert_list
,
344 VLOG(2) << "OnCertificatesLoaded.";
345 if (!ClientCertificatesLoaded())
347 // Compare all networks with all certificates.
348 NetworkStateHandler::NetworkStateList networks
;
349 network_state_handler_
->GetNetworkListByType(
350 NetworkTypePattern::Default(),
351 true /* configured_only */,
352 false /* visible_only */,
355 ResolveNetworks(networks
);
358 void ClientCertResolver::PolicyAppliedToNetwork(
359 const std::string
& service_path
) {
360 VLOG(2) << "PolicyAppliedToNetwork " << service_path
;
361 if (!ClientCertificatesLoaded())
363 // Compare this network with all certificates.
364 const NetworkState
* network
=
365 network_state_handler_
->GetNetworkStateFromServicePath(
366 service_path
, true /* configured_only */);
368 LOG(ERROR
) << "service path '" << service_path
<< "' unknown.";
371 NetworkStateHandler::NetworkStateList networks
;
372 networks
.push_back(network
);
373 ResolveNetworks(networks
);
376 void ClientCertResolver::ResolveNetworks(
377 const NetworkStateHandler::NetworkStateList
& networks
) {
378 scoped_ptr
<std::vector
<NetworkAndCertPattern
>> networks_to_resolve(
379 new std::vector
<NetworkAndCertPattern
>);
381 // Filter networks with ClientCertPattern. As ClientCertPatterns can only be
382 // set by policy, we check there.
383 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
384 networks
.begin(); it
!= networks
.end(); ++it
) {
385 const NetworkState
* network
= *it
;
387 // In any case, don't check this network again in NetworkListChanged.
388 resolved_networks_
.insert(network
->path());
390 // If this network is not configured, it cannot have a ClientCertPattern.
391 if (network
->profile_path().empty())
394 const base::DictionaryValue
* policy
=
395 managed_network_config_handler_
->FindPolicyByGuidAndProfile(
396 network
->guid(), network
->profile_path());
399 VLOG(1) << "The policy for network " << network
->path() << " with GUID "
400 << network
->guid() << " is not available yet.";
401 // Skip this network for now. Once the policy is loaded, PolicyApplied()
406 VLOG(2) << "Inspecting network " << network
->path();
407 client_cert::ClientCertConfig cert_config
;
408 OncToClientCertConfig(*policy
, &cert_config
);
410 // Skip networks that don't have a ClientCertPattern.
411 if (cert_config
.client_cert_type
!= ::onc::client_cert::kPattern
)
414 networks_to_resolve
->push_back(
415 NetworkAndCertPattern(network
->path(), cert_config
));
418 if (networks_to_resolve
->empty()) {
419 VLOG(1) << "No networks to resolve.";
420 NotifyResolveRequestCompleted();
424 if (resolve_task_running_
) {
425 VLOG(1) << "A resolve task is already running. Queue this request.";
426 for (const NetworkAndCertPattern
& network_and_pattern
:
427 *networks_to_resolve
) {
428 queued_networks_to_resolve_
.insert(network_and_pattern
.service_path
);
433 VLOG(2) << "Start task for resolving client cert patterns.";
434 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
437 base::WorkerPool::GetTaskRunner(true /* task is slow */).get();
439 resolve_task_running_
= true;
440 NetworkCertMatches
* matches
= new NetworkCertMatches
;
441 task_runner
->PostTaskAndReply(
443 base::Bind(&FindCertificateMatches
,
444 CertLoader::Get()->cert_list(),
445 base::Owned(networks_to_resolve
.release()),
447 base::Bind(&ClientCertResolver::ConfigureCertificates
,
448 weak_ptr_factory_
.GetWeakPtr(),
449 base::Owned(matches
)));
452 void ClientCertResolver::ResolvePendingNetworks() {
453 NetworkStateHandler::NetworkStateList networks
;
454 network_state_handler_
->GetNetworkListByType(NetworkTypePattern::Default(),
455 true /* configured_only */,
456 false /* visible_only */,
460 NetworkStateHandler::NetworkStateList networks_to_resolve
;
461 for (const NetworkState
* network
: networks
) {
462 if (queued_networks_to_resolve_
.count(network
->path()) > 0)
463 networks_to_resolve
.push_back(network
);
465 VLOG(1) << "Resolve pending " << networks_to_resolve
.size() << " networks.";
466 queued_networks_to_resolve_
.clear();
467 ResolveNetworks(networks_to_resolve
);
470 void ClientCertResolver::ConfigureCertificates(NetworkCertMatches
* matches
) {
471 for (NetworkCertMatches::const_iterator it
= matches
->begin();
472 it
!= matches
->end(); ++it
) {
473 VLOG(1) << "Configuring certificate of network " << it
->service_path
;
474 base::DictionaryValue shill_properties
;
475 if (it
->pkcs11_id
.empty()) {
476 client_cert::SetEmptyShillProperties(it
->cert_config_type
,
479 client_cert::SetShillProperties(it
->cert_config_type
,
484 network_properties_changed_
= true;
485 DBusThreadManager::Get()->GetShillServiceClient()->
486 SetProperties(dbus::ObjectPath(it
->service_path
),
488 base::Bind(&base::DoNothing
),
489 base::Bind(&LogError
, it
->service_path
));
490 network_state_handler_
->RequestUpdateForNetwork(it
->service_path
);
492 if (queued_networks_to_resolve_
.empty())
493 NotifyResolveRequestCompleted();
495 ResolvePendingNetworks();
498 void ClientCertResolver::NotifyResolveRequestCompleted() {
499 VLOG(2) << "Notify observers: " << (network_properties_changed_
? "" : "no ")
500 << "networks changed.";
501 resolve_task_running_
= false;
502 const bool changed
= network_properties_changed_
;
503 network_properties_changed_
= false;
504 FOR_EACH_OBSERVER(Observer
, observers_
, ResolveRequestCompleted(changed
));
507 } // namespace chromeos