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 "components/onc/onc_constants.h"
31 #include "dbus/object_path.h"
32 #include "net/cert/x509_certificate.h"
36 // Describes a network |network_path| for which a matching certificate |cert_id|
38 struct ClientCertResolver::NetworkAndMatchingCert
{
39 NetworkAndMatchingCert(const std::string
& network_path
,
40 client_cert::ConfigType config_type
,
41 const std::string
& cert_id
)
42 : service_path(network_path
),
43 cert_config_type(config_type
),
46 std::string service_path
;
47 client_cert::ConfigType cert_config_type
;
48 // The id of the matching certificate.
49 std::string pkcs11_id
;
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 client_cert::ConfigType config_type
,
94 const CertificatePattern
& pattern
)
95 : service_path(network_path
),
96 cert_config_type(config_type
),
97 client_cert_pattern(pattern
) {}
98 std::string service_path
;
99 client_cert::ConfigType cert_config_type
;
100 CertificatePattern client_cert_pattern
;
103 // A unary predicate that returns true if the given CertAndIssuer matches the
104 // certificate pattern of the NetworkAndCertPattern.
105 struct MatchCertWithPattern
{
106 explicit MatchCertWithPattern(const NetworkAndCertPattern
& pattern
)
107 : net_and_pattern(pattern
) {}
109 bool operator()(const CertAndIssuer
& cert_and_issuer
) {
110 const CertificatePattern
& pattern
= net_and_pattern
.client_cert_pattern
;
111 if (!pattern
.issuer().Empty() &&
112 !client_cert::CertPrincipalMatches(pattern
.issuer(),
113 cert_and_issuer
.cert
->issuer())) {
116 if (!pattern
.subject().Empty() &&
117 !client_cert::CertPrincipalMatches(pattern
.subject(),
118 cert_and_issuer
.cert
->subject())) {
122 const std::vector
<std::string
>& issuer_ca_pems
= pattern
.issuer_ca_pems();
123 if (!issuer_ca_pems
.empty() &&
124 !ContainsValue(issuer_ca_pems
, cert_and_issuer
.pem_encoded_issuer
)) {
130 NetworkAndCertPattern net_and_pattern
;
133 // Searches for matches between |networks| and |certs| and writes matches to
134 // |matches|. Because this calls NSS functions and is potentially slow, it must
135 // be run on a worker thread.
136 void FindCertificateMatches(const net::CertificateList
& certs
,
137 std::vector
<NetworkAndCertPattern
>* networks
,
138 NetworkCertMatches
* matches
) {
139 // Filter all client certs and determines each certificate's issuer, which is
140 // required for the pattern matching.
141 std::vector
<CertAndIssuer
> client_certs
;
142 for (net::CertificateList::const_iterator it
= certs
.begin();
143 it
!= certs
.end(); ++it
) {
144 const net::X509Certificate
& cert
= **it
;
145 if (cert
.valid_expiry().is_null() || cert
.HasExpired() ||
146 !HasPrivateKey(cert
)) {
149 net::X509Certificate::OSCertHandle issuer_handle
=
150 CERT_FindCertIssuer(cert
.os_cert_handle(), PR_Now(), certUsageAnyCA
);
151 if (!issuer_handle
) {
152 LOG(ERROR
) << "Couldn't find an issuer.";
155 scoped_refptr
<net::X509Certificate
> issuer
=
156 net::X509Certificate::CreateFromHandle(
158 net::X509Certificate::OSCertHandles() /* no intermediate certs */);
160 LOG(ERROR
) << "Couldn't create issuer cert.";
163 std::string pem_encoded_issuer
;
164 if (!net::X509Certificate::GetPEMEncoded(issuer
->os_cert_handle(),
165 &pem_encoded_issuer
)) {
166 LOG(ERROR
) << "Couldn't PEM-encode certificate.";
169 client_certs
.push_back(CertAndIssuer(*it
, pem_encoded_issuer
));
172 std::sort(client_certs
.begin(), client_certs
.end(), &CompareCertExpiration
);
174 for (std::vector
<NetworkAndCertPattern
>::const_iterator it
=
176 it
!= networks
->end(); ++it
) {
177 std::vector
<CertAndIssuer
>::iterator cert_it
= std::find_if(
178 client_certs
.begin(), client_certs
.end(), MatchCertWithPattern(*it
));
179 if (cert_it
== client_certs
.end()) {
180 LOG(WARNING
) << "Couldn't find a matching client cert for network "
184 std::string pkcs11_id
= CertLoader::GetPkcs11IdForCert(*cert_it
->cert
);
185 if (pkcs11_id
.empty()) {
186 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
189 matches
->push_back(ClientCertResolver::NetworkAndMatchingCert(
190 it
->service_path
, it
->cert_config_type
, pkcs11_id
));
194 // Determines the type of the CertificatePattern configuration, i.e. is it a
195 // pattern within an EAP, IPsec or OpenVPN configuration.
196 client_cert::ConfigType
OncToClientCertConfigurationType(
197 const base::DictionaryValue
& network_config
) {
198 using namespace ::onc
;
200 const base::DictionaryValue
* wifi
= NULL
;
201 network_config
.GetDictionaryWithoutPathExpansion(network_config::kWiFi
,
204 const base::DictionaryValue
* eap
= NULL
;
205 wifi
->GetDictionaryWithoutPathExpansion(wifi::kEAP
, &eap
);
207 return client_cert::CONFIG_TYPE_NONE
;
208 return client_cert::CONFIG_TYPE_EAP
;
211 const base::DictionaryValue
* vpn
= NULL
;
212 network_config
.GetDictionaryWithoutPathExpansion(network_config::kVPN
, &vpn
);
214 const base::DictionaryValue
* openvpn
= NULL
;
215 vpn
->GetDictionaryWithoutPathExpansion(vpn::kOpenVPN
, &openvpn
);
217 return client_cert::CONFIG_TYPE_OPENVPN
;
219 const base::DictionaryValue
* ipsec
= NULL
;
220 vpn
->GetDictionaryWithoutPathExpansion(vpn::kIPsec
, &ipsec
);
222 return client_cert::CONFIG_TYPE_IPSEC
;
224 return client_cert::CONFIG_TYPE_NONE
;
227 const base::DictionaryValue
* ethernet
= NULL
;
228 network_config
.GetDictionaryWithoutPathExpansion(network_config::kEthernet
,
231 const base::DictionaryValue
* eap
= NULL
;
232 ethernet
->GetDictionaryWithoutPathExpansion(wifi::kEAP
, &eap
);
234 return client_cert::CONFIG_TYPE_EAP
;
235 return client_cert::CONFIG_TYPE_NONE
;
238 return client_cert::CONFIG_TYPE_NONE
;
241 void LogError(const std::string
& service_path
,
242 const std::string
& dbus_error_name
,
243 const std::string
& dbus_error_message
) {
244 network_handler::ShillErrorCallbackFunction(
245 "ClientCertResolver.SetProperties failed",
247 network_handler::ErrorCallback(),
252 bool ClientCertificatesLoaded() {
253 if (!CertLoader::Get()->certificates_loaded()) {
254 VLOG(1) << "Certificates not loaded yet.";
257 if (!CertLoader::Get()->IsHardwareBacked()) {
258 VLOG(1) << "TPM is not available.";
266 ClientCertResolver::ClientCertResolver()
267 : network_state_handler_(NULL
),
268 managed_network_config_handler_(NULL
),
269 weak_ptr_factory_(this) {
272 ClientCertResolver::~ClientCertResolver() {
273 if (network_state_handler_
)
274 network_state_handler_
->RemoveObserver(this, FROM_HERE
);
275 if (CertLoader::IsInitialized())
276 CertLoader::Get()->RemoveObserver(this);
277 if (managed_network_config_handler_
)
278 managed_network_config_handler_
->RemoveObserver(this);
281 void ClientCertResolver::Init(
282 NetworkStateHandler
* network_state_handler
,
283 ManagedNetworkConfigurationHandler
* managed_network_config_handler
) {
284 DCHECK(network_state_handler
);
285 network_state_handler_
= network_state_handler
;
286 network_state_handler_
->AddObserver(this, FROM_HERE
);
288 DCHECK(managed_network_config_handler
);
289 managed_network_config_handler_
= managed_network_config_handler
;
290 managed_network_config_handler_
->AddObserver(this);
292 CertLoader::Get()->AddObserver(this);
295 void ClientCertResolver::SetSlowTaskRunnerForTest(
296 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
297 slow_task_runner_for_test_
= task_runner
;
300 void ClientCertResolver::NetworkListChanged() {
301 VLOG(2) << "NetworkListChanged.";
302 if (!ClientCertificatesLoaded())
304 // Configure only networks that were not configured before.
306 // We'll drop networks from |resolved_networks_|, which are not known anymore.
307 std::set
<std::string
> old_resolved_networks
;
308 old_resolved_networks
.swap(resolved_networks_
);
310 FavoriteStateList networks
;
311 network_state_handler_
->GetFavoriteList(&networks
);
313 FavoriteStateList networks_to_check
;
314 for (FavoriteStateList::const_iterator it
= networks
.begin();
315 it
!= networks
.end(); ++it
) {
316 const std::string
& service_path
= (*it
)->path();
317 if (ContainsKey(old_resolved_networks
, service_path
)) {
318 resolved_networks_
.insert(service_path
);
321 networks_to_check
.push_back(*it
);
324 ResolveNetworks(networks_to_check
);
327 void ClientCertResolver::OnCertificatesLoaded(
328 const net::CertificateList
& cert_list
,
330 VLOG(2) << "OnCertificatesLoaded.";
331 if (!ClientCertificatesLoaded())
333 // Compare all networks with all certificates.
334 FavoriteStateList networks
;
335 network_state_handler_
->GetFavoriteList(&networks
);
336 ResolveNetworks(networks
);
339 void ClientCertResolver::PolicyApplied(const std::string
& service_path
) {
340 VLOG(2) << "PolicyApplied " << service_path
;
341 if (!ClientCertificatesLoaded())
343 // Compare this network with all certificates.
344 const FavoriteState
* network
=
345 network_state_handler_
->GetFavoriteState(service_path
);
347 LOG(ERROR
) << "service path '" << service_path
<< "' unknown.";
350 FavoriteStateList networks
;
351 networks
.push_back(network
);
352 ResolveNetworks(networks
);
355 void ClientCertResolver::ResolveNetworks(const FavoriteStateList
& networks
) {
356 scoped_ptr
<std::vector
<NetworkAndCertPattern
> > networks_with_pattern(
357 new std::vector
<NetworkAndCertPattern
>);
359 // Filter networks with ClientCertPattern. As ClientCertPatterns can only be
360 // set by policy, we check there.
361 for (FavoriteStateList::const_iterator it
= networks
.begin();
362 it
!= networks
.end(); ++it
) {
363 const FavoriteState
* network
= *it
;
365 // In any case, don't check this network again in NetworkListChanged.
366 resolved_networks_
.insert(network
->path());
368 // If this network is not managed, it cannot have a ClientCertPattern.
369 if (network
->guid().empty())
372 if (network
->profile_path().empty()) {
373 LOG(ERROR
) << "Network " << network
->path()
374 << " has a GUID but not profile path";
377 const base::DictionaryValue
* policy
=
378 managed_network_config_handler_
->FindPolicyByGuidAndProfile(
379 network
->guid(), network
->profile_path());
382 VLOG(1) << "The policy for network " << network
->path() << " with GUID "
383 << network
->guid() << " is not available yet.";
384 // Skip this network for now. Once the policy is loaded, PolicyApplied()
389 VLOG(2) << "Inspecting network " << network
->path();
390 // TODO(pneubeck): Access the ClientCertPattern without relying on
391 // NetworkUIData, which also parses other things that we don't need here.
392 // The ONCSource is irrelevant here.
393 scoped_ptr
<NetworkUIData
> ui_data(
394 NetworkUIData::CreateFromONC(onc::ONC_SOURCE_NONE
, *policy
));
396 // Skip networks that don't have a ClientCertPattern.
397 if (ui_data
->certificate_type() != CLIENT_CERT_TYPE_PATTERN
)
400 client_cert::ConfigType config_type
=
401 OncToClientCertConfigurationType(*policy
);
402 if (config_type
== client_cert::CONFIG_TYPE_NONE
) {
403 LOG(ERROR
) << "UIData contains a CertificatePattern, but the policy "
404 << "doesn't. Network: " << network
->path();
408 networks_with_pattern
->push_back(NetworkAndCertPattern(
409 network
->path(), config_type
, ui_data
->certificate_pattern()));
411 if (networks_with_pattern
->empty())
414 VLOG(2) << "Start task for resolving client cert patterns.";
415 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
417 task_runner
= base::WorkerPool::GetTaskRunner(true /* task is slow */);
419 NetworkCertMatches
* matches
= new NetworkCertMatches
;
420 task_runner
->PostTaskAndReply(
422 base::Bind(&FindCertificateMatches
,
423 CertLoader::Get()->cert_list(),
424 base::Owned(networks_with_pattern
.release()),
426 base::Bind(&ClientCertResolver::ConfigureCertificates
,
427 weak_ptr_factory_
.GetWeakPtr(),
428 base::Owned(matches
)));
431 void ClientCertResolver::ConfigureCertificates(NetworkCertMatches
* matches
) {
432 for (NetworkCertMatches::const_iterator it
= matches
->begin();
433 it
!= matches
->end(); ++it
) {
434 VLOG(1) << "Configuring certificate of network " << it
->service_path
;
435 CertLoader
* cert_loader
= CertLoader::Get();
436 base::DictionaryValue shill_properties
;
437 client_cert::SetShillProperties(
438 it
->cert_config_type
,
439 base::IntToString(cert_loader
->tpm_token_slot_id()),
440 cert_loader
->tpm_user_pin(),
443 DBusThreadManager::Get()->GetShillServiceClient()->
444 SetProperties(dbus::ObjectPath(it
->service_path
),
446 base::Bind(&base::DoNothing
),
447 base::Bind(&LogError
, it
->service_path
));
448 network_state_handler_
->RequestUpdateForNetwork(it
->service_path
);
452 } // namespace chromeos