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/managed_network_configuration_handler.h"
27 #include "chromeos/network/network_state.h"
28 #include "chromeos/tpm_token_loader.h"
29 #include "components/onc/onc_constants.h"
30 #include "dbus/object_path.h"
31 #include "net/cert/scoped_nss_types.h"
32 #include "net/cert/x509_certificate.h"
36 // Describes a network |network_path| for which a matching certificate |cert_id|
37 // was found or for which no certificate was found (|cert_id| will be empty).
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
;
49 // The id of the matching certificate or empty if no certificate was found.
50 std::string pkcs11_id
;
53 typedef std::vector
<ClientCertResolver::NetworkAndMatchingCert
>
58 // Returns true if |vector| contains |value|.
60 bool ContainsValue(const std::vector
<T
>& vector
, const T
& value
) {
61 return find(vector
.begin(), vector
.end(), value
) != vector
.end();
64 // Returns true if a private key for certificate |cert| is installed.
65 bool HasPrivateKey(const net::X509Certificate
& cert
) {
66 PK11SlotInfo
* slot
= PK11_KeyForCertExists(cert
.os_cert_handle(), NULL
, NULL
);
74 // Describes a certificate which is issued by |issuer| (encoded as PEM).
75 struct CertAndIssuer
{
76 CertAndIssuer(const scoped_refptr
<net::X509Certificate
>& certificate
,
77 const std::string
& issuer
)
79 pem_encoded_issuer(issuer
) {}
81 scoped_refptr
<net::X509Certificate
> cert
;
82 std::string pem_encoded_issuer
;
85 bool CompareCertExpiration(const CertAndIssuer
& a
,
86 const CertAndIssuer
& b
) {
87 return (a
.cert
->valid_expiry() > b
.cert
->valid_expiry());
90 // Describes a network that is configured with the certificate pattern
91 // |client_cert_pattern|.
92 struct NetworkAndCertPattern
{
93 NetworkAndCertPattern(const std::string
& network_path
,
94 const client_cert::ClientCertConfig
& client_cert_config
)
95 : service_path(network_path
),
96 cert_config(client_cert_config
) {}
98 std::string service_path
;
99 client_cert::ClientCertConfig cert_config
;
102 // A unary predicate that returns true if the given CertAndIssuer matches the
103 // certificate pattern of the NetworkAndCertPattern.
104 struct MatchCertWithPattern
{
105 explicit MatchCertWithPattern(const NetworkAndCertPattern
& pattern
)
106 : net_and_pattern(pattern
) {}
108 bool operator()(const CertAndIssuer
& cert_and_issuer
) {
109 const CertificatePattern
& pattern
= net_and_pattern
.cert_config
.pattern
;
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 NetworkAndCertPattern net_and_pattern
;
132 // Searches for matches between |networks| and |certs| and writes matches to
133 // |matches|. Because this calls NSS functions and is potentially slow, it must
134 // be run on a worker thread.
135 void FindCertificateMatches(const net::CertificateList
& certs
,
136 std::vector
<NetworkAndCertPattern
>* networks
,
137 NetworkCertMatches
* matches
) {
138 // Filter all client certs and determines each certificate's issuer, which is
139 // required for the pattern matching.
140 std::vector
<CertAndIssuer
> client_certs
;
141 for (net::CertificateList::const_iterator it
= certs
.begin();
142 it
!= certs
.end(); ++it
) {
143 const net::X509Certificate
& cert
= **it
;
144 if (cert
.valid_expiry().is_null() || cert
.HasExpired() ||
145 !HasPrivateKey(cert
)) {
148 net::ScopedCERTCertificate
issuer_handle(
149 CERT_FindCertIssuer(cert
.os_cert_handle(), PR_Now(), certUsageAnyCA
));
150 if (!issuer_handle
) {
151 LOG(ERROR
) << "Couldn't find an issuer.";
154 scoped_refptr
<net::X509Certificate
> issuer
=
155 net::X509Certificate::CreateFromHandle(
157 net::X509Certificate::OSCertHandles() /* no intermediate certs */);
159 LOG(ERROR
) << "Couldn't create issuer cert.";
162 std::string pem_encoded_issuer
;
163 if (!net::X509Certificate::GetPEMEncoded(issuer
->os_cert_handle(),
164 &pem_encoded_issuer
)) {
165 LOG(ERROR
) << "Couldn't PEM-encode certificate.";
168 client_certs
.push_back(CertAndIssuer(*it
, pem_encoded_issuer
));
171 std::sort(client_certs
.begin(), client_certs
.end(), &CompareCertExpiration
);
173 for (std::vector
<NetworkAndCertPattern
>::const_iterator it
=
175 it
!= networks
->end(); ++it
) {
176 std::vector
<CertAndIssuer
>::iterator cert_it
= std::find_if(
177 client_certs
.begin(), client_certs
.end(), MatchCertWithPattern(*it
));
178 std::string pkcs11_id
;
179 if (cert_it
== client_certs
.end()) {
180 VLOG(1) << "Couldn't find a matching client cert for network "
182 // Leave |pkcs11_id empty| to indicate that no cert was found for this
185 pkcs11_id
= CertLoader::GetPkcs11IdForCert(*cert_it
->cert
);
186 if (pkcs11_id
.empty()) {
187 LOG(ERROR
) << "Couldn't determine PKCS#11 ID.";
188 // So far this error is not expected to happen. We can just continue, in
189 // the worst case the user can remove the problematic cert.
193 matches
->push_back(ClientCertResolver::NetworkAndMatchingCert(
194 it
->service_path
, it
->cert_config
.location
, pkcs11_id
));
198 void LogError(const std::string
& service_path
,
199 const std::string
& dbus_error_name
,
200 const std::string
& dbus_error_message
) {
201 network_handler::ShillErrorCallbackFunction(
202 "ClientCertResolver.SetProperties failed",
204 network_handler::ErrorCallback(),
209 bool ClientCertificatesLoaded() {
210 if (!CertLoader::Get()->certificates_loaded()) {
211 VLOG(1) << "Certificates not loaded yet.";
214 if (!CertLoader::Get()->IsHardwareBacked()) {
215 VLOG(1) << "TPM is not available.";
223 ClientCertResolver::ClientCertResolver()
224 : network_state_handler_(NULL
),
225 managed_network_config_handler_(NULL
),
226 weak_ptr_factory_(this) {
229 ClientCertResolver::~ClientCertResolver() {
230 if (network_state_handler_
)
231 network_state_handler_
->RemoveObserver(this, FROM_HERE
);
232 if (CertLoader::IsInitialized())
233 CertLoader::Get()->RemoveObserver(this);
234 if (managed_network_config_handler_
)
235 managed_network_config_handler_
->RemoveObserver(this);
238 void ClientCertResolver::Init(
239 NetworkStateHandler
* network_state_handler
,
240 ManagedNetworkConfigurationHandler
* managed_network_config_handler
) {
241 DCHECK(network_state_handler
);
242 network_state_handler_
= network_state_handler
;
243 network_state_handler_
->AddObserver(this, FROM_HERE
);
245 DCHECK(managed_network_config_handler
);
246 managed_network_config_handler_
= managed_network_config_handler
;
247 managed_network_config_handler_
->AddObserver(this);
249 CertLoader::Get()->AddObserver(this);
252 void ClientCertResolver::SetSlowTaskRunnerForTest(
253 const scoped_refptr
<base::TaskRunner
>& task_runner
) {
254 slow_task_runner_for_test_
= task_runner
;
257 void ClientCertResolver::NetworkListChanged() {
258 VLOG(2) << "NetworkListChanged.";
259 if (!ClientCertificatesLoaded())
261 // Configure only networks that were not configured before.
263 // We'll drop networks from |resolved_networks_|, which are not known anymore.
264 std::set
<std::string
> old_resolved_networks
;
265 old_resolved_networks
.swap(resolved_networks_
);
267 NetworkStateHandler::NetworkStateList networks
;
268 network_state_handler_
->GetNetworkListByType(
269 NetworkTypePattern::Default(),
270 true /* configured_only */,
271 false /* visible_only */,
275 NetworkStateHandler::NetworkStateList networks_to_check
;
276 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
277 networks
.begin(); it
!= networks
.end(); ++it
) {
278 const std::string
& service_path
= (*it
)->path();
279 if (ContainsKey(old_resolved_networks
, service_path
)) {
280 resolved_networks_
.insert(service_path
);
283 networks_to_check
.push_back(*it
);
286 ResolveNetworks(networks_to_check
);
289 void ClientCertResolver::OnCertificatesLoaded(
290 const net::CertificateList
& cert_list
,
292 VLOG(2) << "OnCertificatesLoaded.";
293 if (!ClientCertificatesLoaded())
295 // Compare all networks with all certificates.
296 NetworkStateHandler::NetworkStateList networks
;
297 network_state_handler_
->GetNetworkListByType(
298 NetworkTypePattern::Default(),
299 true /* configured_only */,
300 false /* visible_only */,
303 ResolveNetworks(networks
);
306 void ClientCertResolver::PolicyApplied(const std::string
& service_path
) {
307 VLOG(2) << "PolicyApplied " << service_path
;
308 if (!ClientCertificatesLoaded())
310 // Compare this network with all certificates.
311 const NetworkState
* network
=
312 network_state_handler_
->GetNetworkStateFromServicePath(
313 service_path
, true /* configured_only */);
315 LOG(ERROR
) << "service path '" << service_path
<< "' unknown.";
318 NetworkStateHandler::NetworkStateList networks
;
319 networks
.push_back(network
);
320 ResolveNetworks(networks
);
323 void ClientCertResolver::ResolveNetworks(
324 const NetworkStateHandler::NetworkStateList
& networks
) {
325 scoped_ptr
<std::vector
<NetworkAndCertPattern
> > networks_with_pattern(
326 new std::vector
<NetworkAndCertPattern
>);
328 // Filter networks with ClientCertPattern. As ClientCertPatterns can only be
329 // set by policy, we check there.
330 for (NetworkStateHandler::NetworkStateList::const_iterator it
=
331 networks
.begin(); it
!= networks
.end(); ++it
) {
332 const NetworkState
* network
= *it
;
334 // In any case, don't check this network again in NetworkListChanged.
335 resolved_networks_
.insert(network
->path());
337 // If this network is not managed, it cannot have a ClientCertPattern.
338 if (network
->guid().empty())
341 if (network
->profile_path().empty()) {
342 LOG(ERROR
) << "Network " << network
->path()
343 << " has a GUID but not profile path";
346 const base::DictionaryValue
* policy
=
347 managed_network_config_handler_
->FindPolicyByGuidAndProfile(
348 network
->guid(), network
->profile_path());
351 VLOG(1) << "The policy for network " << network
->path() << " with GUID "
352 << network
->guid() << " is not available yet.";
353 // Skip this network for now. Once the policy is loaded, PolicyApplied()
358 VLOG(2) << "Inspecting network " << network
->path();
359 client_cert::ClientCertConfig cert_config
;
360 OncToClientCertConfig(*policy
, &cert_config
);
362 // Skip networks that don't have a ClientCertPattern.
363 if (cert_config
.client_cert_type
!= ::onc::client_cert::kPattern
)
366 networks_with_pattern
->push_back(
367 NetworkAndCertPattern(network
->path(), cert_config
));
369 if (networks_with_pattern
->empty())
372 VLOG(2) << "Start task for resolving client cert patterns.";
373 base::TaskRunner
* task_runner
= slow_task_runner_for_test_
.get();
375 task_runner
= base::WorkerPool::GetTaskRunner(true /* task is slow */);
377 NetworkCertMatches
* matches
= new NetworkCertMatches
;
378 task_runner
->PostTaskAndReply(
380 base::Bind(&FindCertificateMatches
,
381 CertLoader::Get()->cert_list(),
382 base::Owned(networks_with_pattern
.release()),
384 base::Bind(&ClientCertResolver::ConfigureCertificates
,
385 weak_ptr_factory_
.GetWeakPtr(),
386 base::Owned(matches
)));
389 void ClientCertResolver::ConfigureCertificates(NetworkCertMatches
* matches
) {
390 for (NetworkCertMatches::const_iterator it
= matches
->begin();
391 it
!= matches
->end(); ++it
) {
392 VLOG(1) << "Configuring certificate of network " << it
->service_path
;
393 CertLoader
* cert_loader
= CertLoader::Get();
394 base::DictionaryValue shill_properties
;
395 // If pkcs11_id is empty, this will clear the key/cert properties of this
397 client_cert::SetShillProperties(
398 it
->cert_config_type
,
399 base::IntToString(cert_loader
->TPMTokenSlotID()),
400 TPMTokenLoader::Get()->tpm_user_pin(),
403 DBusThreadManager::Get()->GetShillServiceClient()->
404 SetProperties(dbus::ObjectPath(it
->service_path
),
406 base::Bind(&base::DoNothing
),
407 base::Bind(&LogError
, it
->service_path
));
408 network_state_handler_
->RequestUpdateForNetwork(it
->service_path
);
412 } // namespace chromeos