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/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"
38 // Describes a network |network_path| for which a matching certificate |cert_id|
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
),
48 std::string service_path
;
49 client_cert::ConfigType cert_config_type
;
50 // The id of the matching certificate.
51 std::string pkcs11_id
;
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 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
;
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
) {}
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())) {
118 if (!pattern
.subject().Empty() &&
119 !client_cert::CertPrincipalMatches(pattern
.subject(),
120 cert_and_issuer
.cert
->subject())) {
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
)) {
132 NetworkAndCertPattern net_and_pattern
;
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
)) {
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.";
157 scoped_refptr
<net::X509Certificate
> issuer
=
158 net::X509Certificate::CreateFromHandle(
160 net::X509Certificate::OSCertHandles() /* no intermediate certs */);
162 LOG(ERROR
) << "Couldn't create issuer cert.";
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.";
171 client_certs
.push_back(CertAndIssuer(*it
, pem_encoded_issuer
));
174 std::sort(client_certs
.begin(), client_certs
.end(), &CompareCertExpiration
);
176 for (std::vector
<NetworkAndCertPattern
>::const_iterator it
=
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 "
186 std::string pkcs11_id
= CertLoader::GetPkcs11IdForCert(*cert_it
->cert
);
187 if (pkcs11_id
.empty()) {
188 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
191 matches
->push_back(ClientCertResolver::NetworkAndMatchingCert(
192 it
->service_path
, it
->cert_config_type
, pkcs11_id
));
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
;
202 const base::DictionaryValue
* wifi
= NULL
;
203 network_config
.GetDictionaryWithoutPathExpansion(network_config::kWiFi
,
206 const base::DictionaryValue
* eap
= NULL
;
207 wifi
->GetDictionaryWithoutPathExpansion(wifi::kEAP
, &eap
);
209 return client_cert::CONFIG_TYPE_NONE
;
210 return client_cert::CONFIG_TYPE_EAP
;
213 const base::DictionaryValue
* vpn
= NULL
;
214 network_config
.GetDictionaryWithoutPathExpansion(network_config::kVPN
, &vpn
);
216 const base::DictionaryValue
* openvpn
= NULL
;
217 vpn
->GetDictionaryWithoutPathExpansion(vpn::kOpenVPN
, &openvpn
);
219 return client_cert::CONFIG_TYPE_OPENVPN
;
221 const base::DictionaryValue
* ipsec
= NULL
;
222 vpn
->GetDictionaryWithoutPathExpansion(vpn::kIPsec
, &ipsec
);
224 return client_cert::CONFIG_TYPE_IPSEC
;
226 return client_cert::CONFIG_TYPE_NONE
;
229 const base::DictionaryValue
* ethernet
= NULL
;
230 network_config
.GetDictionaryWithoutPathExpansion(network_config::kEthernet
,
233 const base::DictionaryValue
* eap
= NULL
;
234 ethernet
->GetDictionaryWithoutPathExpansion(wifi::kEAP
, &eap
);
236 return client_cert::CONFIG_TYPE_EAP
;
237 return client_cert::CONFIG_TYPE_NONE
;
240 return client_cert::CONFIG_TYPE_NONE
;
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",
249 network_handler::ErrorCallback(),
254 bool ClientCertificatesLoaded() {
255 if (!CertLoader::Get()->certificates_loaded()) {
256 VLOG(1) << "Certificates not loaded yet.";
259 if (!CertLoader::Get()->IsHardwareBacked()) {
260 VLOG(1) << "TPM is not available.";
268 ClientCertResolver::ClientCertResolver()
269 : network_state_handler_(NULL
),
270 managed_network_config_handler_(NULL
),
271 weak_ptr_factory_(this) {
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);
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
);
290 DCHECK(managed_network_config_handler
);
291 managed_network_config_handler_
= managed_network_config_handler
;
292 managed_network_config_handler_
->AddObserver(this);
294 CertLoader::Get()->AddObserver(this);
297 void ClientCertResolver::SetSlowTaskRunnerForTest(
298 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
299 slow_task_runner_for_test_
= task_runner
;
302 void ClientCertResolver::NetworkListChanged() {
303 VLOG(2) << "NetworkListChanged.";
304 if (!ClientCertificatesLoaded())
306 // Configure only networks that were not configured before.
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_
);
312 FavoriteStateList networks
;
313 network_state_handler_
->GetFavoriteList(&networks
);
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
);
323 networks_to_check
.push_back(*it
);
326 ResolveNetworks(networks_to_check
);
329 void ClientCertResolver::OnCertificatesLoaded(
330 const net::CertificateList
& cert_list
,
332 VLOG(2) << "OnCertificatesLoaded.";
333 if (!ClientCertificatesLoaded())
335 // Compare all networks with all certificates.
336 FavoriteStateList networks
;
337 network_state_handler_
->GetFavoriteList(&networks
);
338 ResolveNetworks(networks
);
341 void ClientCertResolver::PolicyApplied(const std::string
& service_path
) {
342 VLOG(2) << "PolicyApplied " << service_path
;
343 if (!ClientCertificatesLoaded())
345 // Compare this network with all certificates.
346 const FavoriteState
* network
=
347 network_state_handler_
->GetFavoriteState(service_path
);
349 LOG(ERROR
) << "service path '" << service_path
<< "' unknown.";
352 FavoriteStateList networks
;
353 networks
.push_back(network
);
354 ResolveNetworks(networks
);
357 void ClientCertResolver::ResolveNetworks(const FavoriteStateList
& networks
) {
358 scoped_ptr
<std::vector
<NetworkAndCertPattern
> > networks_with_pattern(
359 new std::vector
<NetworkAndCertPattern
>);
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
;
367 // In any case, don't check this network again in NetworkListChanged.
368 resolved_networks_
.insert(network
->path());
370 // If this network is not managed, it cannot have a ClientCertPattern.
371 if (network
->guid().empty())
374 if (network
->profile_path().empty()) {
375 LOG(ERROR
) << "Network " << network
->path()
376 << " has a GUID but not profile path";
379 const base::DictionaryValue
* policy
=
380 managed_network_config_handler_
->FindPolicyByGuidAndProfile(
381 network
->guid(), network
->profile_path());
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()
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
));
398 // Skip networks that don't have a ClientCertPattern.
399 if (ui_data
->certificate_type() != CLIENT_CERT_TYPE_PATTERN
)
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();
410 networks_with_pattern
->push_back(NetworkAndCertPattern(
411 network
->path(), config_type
, ui_data
->certificate_pattern()));
413 if (networks_with_pattern
->empty())
416 VLOG(2) << "Start task for resolving client cert patterns.";
417 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
419 task_runner
= base::WorkerPool::GetTaskRunner(true /* task is slow */);
421 NetworkCertMatches
* matches
= new NetworkCertMatches
;
422 task_runner
->PostTaskAndReply(
424 base::Bind(&FindCertificateMatches
,
425 CertLoader::Get()->cert_list(),
426 base::Owned(networks_with_pattern
.release()),
428 base::Bind(&ClientCertResolver::ConfigureCertificates
,
429 weak_ptr_factory_
.GetWeakPtr(),
430 base::Owned(matches
)));
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(),
445 DBusThreadManager::Get()->GetShillServiceClient()->
446 SetProperties(dbus::ObjectPath(it
->service_path
),
448 base::Bind(&base::DoNothing
),
449 base::Bind(&LogError
, it
->service_path
));
450 network_state_handler_
->RequestUpdateForNetwork(it
->service_path
);
454 } // namespace chromeos