1// Copyright (c) 2012 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 "net/cert/x509_util.h"
6
7#include "base/time/time.h"
8#include "net/cert/x509_certificate.h"
9
10namespace net {
11
12namespace x509_util {
13
14ClientCertSorter::ClientCertSorter() : now_(base::Time::Now()) {}
15
16bool ClientCertSorter::operator()(
17    const scoped_refptr<X509Certificate>& a,
18    const scoped_refptr<X509Certificate>& b) const {
19  // Certificates that are null are sorted last.
20  if (!a.get() || !b.get())
21    return a.get() && !b.get();
22
23  // Certificates that are expired/not-yet-valid are sorted last.
24  bool a_is_valid = now_ >= a->valid_start() && now_ <= a->valid_expiry();
25  bool b_is_valid = now_ >= b->valid_start() && now_ <= b->valid_expiry();
26  if (a_is_valid != b_is_valid)
27    return a_is_valid && !b_is_valid;
28
29  // Certificates with longer expirations appear as higher priority (less
30  // than) certificates with shorter expirations.
31  if (a->valid_expiry() != b->valid_expiry())
32    return a->valid_expiry() > b->valid_expiry();
33
34  // If the expiration dates are equivalent, certificates that were issued
35  // more recently should be prioritized over older certificates.
36  if (a->valid_start() != b->valid_start())
37    return a->valid_start() > b->valid_start();
38
39  // Otherwise, prefer client certificates with shorter chains.
40  const X509Certificate::OSCertHandles& a_intermediates =
41      a->GetIntermediateCertificates();
42  const X509Certificate::OSCertHandles& b_intermediates =
43      b->GetIntermediateCertificates();
44  return a_intermediates.size() < b_intermediates.size();
45}
46
47}  // namespace x509_util
48
49}  // namespace net
50