client_cert_resolver.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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.
4
5#include "chromeos/network/client_cert_resolver.h"
6
7#include <cert.h>
8#include <certt.h>  // for (SECCertUsageEnum) certUsageAnyCA
9#include <pk11pub.h>
10
11#include <algorithm>
12#include <string>
13
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"
33
34namespace chromeos {
35
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).
38struct 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),
44        pkcs11_id(cert_id) {}
45
46  std::string service_path;
47  client_cert::ConfigType cert_config_type;
48
49  // The id of the matching certificate or empty if no certificate was found.
50  std::string pkcs11_id;
51};
52
53typedef std::vector<ClientCertResolver::NetworkAndMatchingCert>
54    NetworkCertMatches;
55
56namespace {
57
58// Returns true if |vector| contains |value|.
59template <class T>
60bool ContainsValue(const std::vector<T>& vector, const T& value) {
61  return find(vector.begin(), vector.end(), value) != vector.end();
62}
63
64// Returns true if a private key for certificate |cert| is installed.
65bool HasPrivateKey(const net::X509Certificate& cert) {
66  PK11SlotInfo* slot = PK11_KeyForCertExists(cert.os_cert_handle(), NULL, NULL);
67  if (!slot)
68    return false;
69
70  PK11_FreeSlot(slot);
71  return true;
72}
73
74// Describes a certificate which is issued by |issuer| (encoded as PEM).
75struct CertAndIssuer {
76  CertAndIssuer(const scoped_refptr<net::X509Certificate>& certificate,
77                const std::string& issuer)
78      : cert(certificate),
79        pem_encoded_issuer(issuer) {}
80
81  scoped_refptr<net::X509Certificate> cert;
82  std::string pem_encoded_issuer;
83};
84
85bool CompareCertExpiration(const CertAndIssuer& a,
86                           const CertAndIssuer& b) {
87  return (a.cert->valid_expiry() > b.cert->valid_expiry());
88}
89
90// Describes a network that is configured with the certificate pattern
91// |client_cert_pattern|.
92struct 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) {}
97
98  std::string service_path;
99  client_cert::ClientCertConfig cert_config;
100};
101
102// A unary predicate that returns true if the given CertAndIssuer matches the
103// certificate pattern of the NetworkAndCertPattern.
104struct MatchCertWithPattern {
105  explicit MatchCertWithPattern(const NetworkAndCertPattern& pattern)
106      : net_and_pattern(pattern) {}
107
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())) {
113      return false;
114    }
115    if (!pattern.subject().Empty() &&
116        !client_cert::CertPrincipalMatches(pattern.subject(),
117                                           cert_and_issuer.cert->subject())) {
118      return false;
119    }
120
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)) {
124      return false;
125    }
126    return true;
127  }
128
129  NetworkAndCertPattern net_and_pattern;
130};
131
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.
135void 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)) {
146      continue;
147    }
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.";
152      continue;
153    }
154    scoped_refptr<net::X509Certificate> issuer =
155        net::X509Certificate::CreateFromHandle(
156            issuer_handle.get(),
157            net::X509Certificate::OSCertHandles() /* no intermediate certs */);
158    if (!issuer) {
159      LOG(ERROR) << "Couldn't create issuer cert.";
160      continue;
161    }
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.";
166      continue;
167    }
168    client_certs.push_back(CertAndIssuer(*it, pem_encoded_issuer));
169  }
170
171  std::sort(client_certs.begin(), client_certs.end(), &CompareCertExpiration);
172
173  for (std::vector<NetworkAndCertPattern>::const_iterator it =
174           networks->begin();
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 "
181              << it->service_path;
182      // Leave |pkcs11_id empty| to indicate that no cert was found for this
183      // network.
184    } else {
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.
190        continue;
191      }
192    }
193    matches->push_back(ClientCertResolver::NetworkAndMatchingCert(
194        it->service_path, it->cert_config.location, pkcs11_id));
195  }
196}
197
198void 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",
203      service_path,
204      network_handler::ErrorCallback(),
205      dbus_error_name,
206      dbus_error_message);
207}
208
209bool ClientCertificatesLoaded() {
210  if (!CertLoader::Get()->certificates_loaded()) {
211    VLOG(1) << "Certificates not loaded yet.";
212    return false;
213  }
214  if (!CertLoader::Get()->IsHardwareBacked()) {
215    VLOG(1) << "TPM is not available.";
216    return false;
217  }
218  return true;
219}
220
221}  // namespace
222
223ClientCertResolver::ClientCertResolver()
224    : network_state_handler_(NULL),
225      managed_network_config_handler_(NULL),
226      weak_ptr_factory_(this) {
227}
228
229ClientCertResolver::~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);
236}
237
238void 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);
244
245  DCHECK(managed_network_config_handler);
246  managed_network_config_handler_ = managed_network_config_handler;
247  managed_network_config_handler_->AddObserver(this);
248
249  CertLoader::Get()->AddObserver(this);
250}
251
252void ClientCertResolver::SetSlowTaskRunnerForTest(
253    const scoped_refptr<base::TaskRunner>& task_runner) {
254  slow_task_runner_for_test_ = task_runner;
255}
256
257void ClientCertResolver::NetworkListChanged() {
258  VLOG(2) << "NetworkListChanged.";
259  if (!ClientCertificatesLoaded())
260    return;
261  // Configure only networks that were not configured before.
262
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_);
266
267  NetworkStateHandler::NetworkStateList networks;
268  network_state_handler_->GetNetworkListByType(
269      NetworkTypePattern::Default(),
270      true /* configured_only */,
271      false /* visible_only */,
272      0 /* no limit */,
273      &networks);
274
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);
281      continue;
282    }
283    networks_to_check.push_back(*it);
284  }
285
286  ResolveNetworks(networks_to_check);
287}
288
289void ClientCertResolver::OnCertificatesLoaded(
290    const net::CertificateList& cert_list,
291    bool initial_load) {
292  VLOG(2) << "OnCertificatesLoaded.";
293  if (!ClientCertificatesLoaded())
294    return;
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 */,
301      0 /* no limit */,
302      &networks);
303  ResolveNetworks(networks);
304}
305
306void ClientCertResolver::PolicyApplied(const std::string& service_path) {
307  VLOG(2) << "PolicyApplied " << service_path;
308  if (!ClientCertificatesLoaded())
309    return;
310  // Compare this network with all certificates.
311  const NetworkState* network =
312      network_state_handler_->GetNetworkStateFromServicePath(
313          service_path, true /* configured_only */);
314  if (!network) {
315    LOG(ERROR) << "service path '" << service_path << "' unknown.";
316    return;
317  }
318  NetworkStateHandler::NetworkStateList networks;
319  networks.push_back(network);
320  ResolveNetworks(networks);
321}
322
323void ClientCertResolver::ResolveNetworks(
324    const NetworkStateHandler::NetworkStateList& networks) {
325  scoped_ptr<std::vector<NetworkAndCertPattern> > networks_with_pattern(
326      new std::vector<NetworkAndCertPattern>);
327
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;
333
334    // In any case, don't check this network again in NetworkListChanged.
335    resolved_networks_.insert(network->path());
336
337    // If this network is not configured, it cannot have a ClientCertPattern.
338    if (network->profile_path().empty())
339      continue;
340
341    const base::DictionaryValue* policy =
342        managed_network_config_handler_->FindPolicyByGuidAndProfile(
343            network->guid(), network->profile_path());
344
345    if (!policy) {
346      VLOG(1) << "The policy for network " << network->path() << " with GUID "
347              << network->guid() << " is not available yet.";
348      // Skip this network for now. Once the policy is loaded, PolicyApplied()
349      // will retry.
350      continue;
351    }
352
353    VLOG(2) << "Inspecting network " << network->path();
354    client_cert::ClientCertConfig cert_config;
355    OncToClientCertConfig(*policy, &cert_config);
356
357    // Skip networks that don't have a ClientCertPattern.
358    if (cert_config.client_cert_type != ::onc::client_cert::kPattern)
359      continue;
360
361    networks_with_pattern->push_back(
362        NetworkAndCertPattern(network->path(), cert_config));
363  }
364  if (networks_with_pattern->empty())
365    return;
366
367  VLOG(2) << "Start task for resolving client cert patterns.";
368  base::TaskRunner* task_runner = slow_task_runner_for_test_.get();
369  if (!task_runner)
370    task_runner = base::WorkerPool::GetTaskRunner(true /* task is slow */);
371
372  NetworkCertMatches* matches = new NetworkCertMatches;
373  task_runner->PostTaskAndReply(
374      FROM_HERE,
375      base::Bind(&FindCertificateMatches,
376                 CertLoader::Get()->cert_list(),
377                 base::Owned(networks_with_pattern.release()),
378                 matches),
379      base::Bind(&ClientCertResolver::ConfigureCertificates,
380                 weak_ptr_factory_.GetWeakPtr(),
381                 base::Owned(matches)));
382}
383
384void ClientCertResolver::ConfigureCertificates(NetworkCertMatches* matches) {
385  for (NetworkCertMatches::const_iterator it = matches->begin();
386       it != matches->end(); ++it) {
387    VLOG(1) << "Configuring certificate of network " << it->service_path;
388    CertLoader* cert_loader = CertLoader::Get();
389    base::DictionaryValue shill_properties;
390    // If pkcs11_id is empty, this will clear the key/cert properties of this
391    // network.
392    client_cert::SetShillProperties(
393        it->cert_config_type,
394        base::IntToString(cert_loader->TPMTokenSlotID()),
395        TPMTokenLoader::Get()->tpm_user_pin(),
396        &it->pkcs11_id,
397        &shill_properties);
398    DBusThreadManager::Get()->GetShillServiceClient()->
399        SetProperties(dbus::ObjectPath(it->service_path),
400                        shill_properties,
401                        base::Bind(&base::DoNothing),
402                        base::Bind(&LogError, it->service_path));
403    network_state_handler_->RequestUpdateForNetwork(it->service_path);
404  }
405}
406
407}  // namespace chromeos
408