attestation_policy_observer_unittest.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
1// Copyright (c) 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 <string>
6
7#include "base/bind.h"
8#include "base/message_loop/message_loop.h"
9#include "base/run_loop.h"
10#include "chrome/browser/chromeos/attestation/attestation_key_payload.pb.h"
11#include "chrome/browser/chromeos/attestation/attestation_policy_observer.h"
12#include "chrome/browser/chromeos/settings/cros_settings.h"
13#include "chrome/browser/chromeos/settings/device_settings_service.h"
14#include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h"
15#include "chrome/browser/policy/cloud/mock_cloud_policy_client.h"
16#include "chromeos/attestation/mock_attestation_flow.h"
17#include "chromeos/dbus/mock_cryptohome_client.h"
18#include "chromeos/settings/cros_settings_names.h"
19#include "content/public/test/test_browser_thread.h"
20#include "crypto/rsa_private_key.h"
21#include "net/cert/x509_certificate.h"
22#include "net/cert/x509_util.h"
23#include "testing/gtest/include/gtest/gtest.h"
24
25using testing::_;
26using testing::Invoke;
27using testing::StrictMock;
28using testing::WithArgs;
29
30namespace chromeos {
31namespace attestation {
32
33namespace {
34
35// A test key encoded as ASN.1 PrivateKeyInfo from PKCS #8.
36const uint8 kTestKeyData[] = {
37    0x30, 0x82, 0x01, 0x55, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a,
38    0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
39    0x01, 0x3f, 0x30, 0x82, 0x01, 0x3b, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00,
40    0xd9, 0xcd, 0xca, 0xcd, 0xc3, 0xea, 0xbe, 0x72, 0x79, 0x1c, 0x29, 0x37,
41    0x39, 0x99, 0x1f, 0xd4, 0xb3, 0x0e, 0xf0, 0x7b, 0x78, 0x77, 0x0e, 0x05,
42    0x3b, 0x65, 0x34, 0x12, 0x62, 0xaf, 0xa6, 0x8d, 0x33, 0xce, 0x78, 0xf8,
43    0x47, 0x05, 0x1d, 0x98, 0xaa, 0x1b, 0x1f, 0x50, 0x05, 0x5b, 0x3c, 0x19,
44    0x3f, 0x80, 0x83, 0x63, 0x63, 0x3a, 0xec, 0xcb, 0x2e, 0x90, 0x4f, 0xf5,
45    0x26, 0x76, 0xf1, 0xd5, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x40, 0x64,
46    0x29, 0xc2, 0xd9, 0x6b, 0xfe, 0xf9, 0x84, 0x75, 0x73, 0xe0, 0xf4, 0x77,
47    0xb5, 0x96, 0xb0, 0xdf, 0x83, 0xc0, 0x4e, 0x57, 0xf1, 0x10, 0x6e, 0x91,
48    0x89, 0x12, 0x30, 0x5e, 0x57, 0xff, 0x14, 0x59, 0x5f, 0x18, 0x86, 0x4e,
49    0x4b, 0x17, 0x56, 0xfc, 0x8d, 0x40, 0xdd, 0x74, 0x65, 0xd3, 0xff, 0x67,
50    0x64, 0xcb, 0x9c, 0xb4, 0x14, 0x8a, 0x06, 0xb7, 0x13, 0x45, 0x94, 0x16,
51    0x7d, 0x3f, 0xe1, 0x02, 0x21, 0x00, 0xf6, 0x0f, 0x31, 0x6d, 0x06, 0xcc,
52    0x3b, 0xa0, 0x44, 0x1f, 0xf5, 0xc2, 0x45, 0x2b, 0x10, 0x6c, 0xf9, 0x6f,
53    0x8f, 0x87, 0x3d, 0xc0, 0x3b, 0x55, 0x13, 0x37, 0x80, 0xcd, 0x9f, 0xe1,
54    0xb7, 0xd9, 0x02, 0x21, 0x00, 0xe2, 0x9a, 0x5f, 0xbf, 0x95, 0x74, 0xb5,
55    0x7a, 0x6a, 0xa6, 0x97, 0xbd, 0x75, 0x8c, 0x97, 0x18, 0x24, 0xd6, 0x09,
56    0xcd, 0xdc, 0xb5, 0x94, 0xbf, 0xe2, 0x78, 0xaa, 0x20, 0x47, 0x9f, 0x68,
57    0x5d, 0x02, 0x21, 0x00, 0xaf, 0x8f, 0x97, 0x8c, 0x5a, 0xd5, 0x4d, 0x95,
58    0xc4, 0x05, 0xa9, 0xab, 0xba, 0xfe, 0x46, 0xf1, 0xf9, 0xe7, 0x07, 0x59,
59    0x4f, 0x4d, 0xe1, 0x07, 0x8a, 0x76, 0x87, 0x88, 0x2f, 0x13, 0x35, 0xc1,
60    0x02, 0x20, 0x24, 0xc3, 0xd9, 0x2f, 0x13, 0x47, 0x99, 0x3e, 0x20, 0x59,
61    0xa1, 0x1a, 0xeb, 0x1c, 0x81, 0x53, 0x38, 0x7e, 0xc5, 0x9e, 0x71, 0xe5,
62    0xc0, 0x19, 0x95, 0xdb, 0xef, 0xf6, 0x46, 0xc8, 0x95, 0x3d, 0x02, 0x21,
63    0x00, 0xaa, 0xb1, 0xff, 0x8a, 0xa2, 0xb2, 0x2b, 0xef, 0x9a, 0x83, 0x3f,
64    0xc5, 0xbc, 0xd4, 0x6a, 0x07, 0xe8, 0xc7, 0x0b, 0x2e, 0xd4, 0x0f, 0xf8,
65    0x98, 0x68, 0xe1, 0x04, 0xa8, 0x92, 0xd0, 0x10, 0xaa,
66};
67
68void DBusCallbackFalse(const BoolDBusMethodCallback& callback) {
69  base::MessageLoop::current()->PostTask(
70      FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS, false));
71}
72
73void DBusCallbackTrue(const BoolDBusMethodCallback& callback) {
74  base::MessageLoop::current()->PostTask(
75      FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS, true));
76}
77
78void DBusCallbackError(const BoolDBusMethodCallback& callback) {
79  base::MessageLoop::current()->PostTask(
80      FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_FAILURE, false));
81}
82
83void CertCallbackSuccess(const AttestationFlow::CertificateCallback& callback) {
84  base::MessageLoop::current()->PostTask(
85      FROM_HERE, base::Bind(callback, true, "fake_cert"));
86}
87
88void StatusCallbackSuccess(
89    const policy::CloudPolicyClient::StatusCallback& callback) {
90  base::MessageLoop::current()->PostTask(
91      FROM_HERE, base::Bind(callback, true));
92}
93
94class FakeDBusData {
95 public:
96  explicit FakeDBusData(const std::string& data) : data_(data) {}
97
98  void operator() (const CryptohomeClient::DataMethodCallback& callback) {
99    base::MessageLoop::current()->PostTask(
100        FROM_HERE,
101        base::Bind(callback, DBUS_METHOD_CALL_SUCCESS, true, data_));
102  }
103
104 private:
105  std::string data_;
106};
107
108}  // namespace
109
110class AttestationPolicyObserverTest : public ::testing::Test {
111 public:
112  AttestationPolicyObserverTest()
113      : message_loop_(base::MessageLoop::TYPE_UI),
114        ui_thread_(content::BrowserThread::UI, &message_loop_) {
115    // Remove the real DeviceSettingsProvider and replace it with a stub.
116    CrosSettings* cros_settings = CrosSettings::Get();
117    device_settings_provider_ =
118        cros_settings->GetProvider(kDeviceAttestationEnabled);
119    cros_settings->RemoveSettingsProvider(device_settings_provider_);
120    cros_settings->AddSettingsProvider(&stub_settings_provider_);
121    cros_settings->SetBoolean(kDeviceAttestationEnabled, true);
122    policy_client_.SetDMToken("fake_dm_token");
123  }
124
125  virtual ~AttestationPolicyObserverTest() {
126    // Restore the real DeviceSettingsProvider.
127    CrosSettings* cros_settings = CrosSettings::Get();
128    cros_settings->RemoveSettingsProvider(&stub_settings_provider_);
129    cros_settings->AddSettingsProvider(device_settings_provider_);
130  }
131
132 protected:
133  enum CertExpiryOptions {
134    CERT_VALID,
135    CERT_EXPIRING_SOON,
136    CERT_EXPIRED
137  };
138
139  enum MockOptions {
140    MOCK_KEY_EXISTS = 1,          // Configure so a certified key exists.
141    MOCK_KEY_UPLOADED = (1 << 1), // Configure so an upload has occurred.
142    MOCK_NEW_KEY = (1 << 2)       // Configure expecting new key generation.
143  };
144
145  // Configures mock expectations according to |mock_options|.  If options
146  // require that a certificate exists, |certificate| will be used.
147  void SetupMocks(int mock_options, const std::string& certificate) {
148    bool key_exists = (mock_options & MOCK_KEY_EXISTS);
149    // Setup expected key / cert queries.
150    if (key_exists) {
151      EXPECT_CALL(cryptohome_client_, TpmAttestationDoesKeyExist(_, _, _))
152          .WillRepeatedly(WithArgs<2>(Invoke(DBusCallbackTrue)));
153      EXPECT_CALL(cryptohome_client_, TpmAttestationGetCertificate(_, _, _))
154          .WillRepeatedly(WithArgs<2>(Invoke(FakeDBusData(certificate))));
155    } else {
156      EXPECT_CALL(cryptohome_client_, TpmAttestationDoesKeyExist(_, _, _))
157          .WillRepeatedly(WithArgs<2>(Invoke(DBusCallbackFalse)));
158    }
159
160    // Setup expected key payload queries.
161    bool key_uploaded = (mock_options & MOCK_KEY_UPLOADED);
162    std::string payload = CreatePayload();
163    EXPECT_CALL(cryptohome_client_, TpmAttestationGetKeyPayload(_, _, _))
164        .WillRepeatedly(WithArgs<2>(Invoke(
165            FakeDBusData(key_uploaded ? payload : ""))));
166
167    // Setup expected key uploads.  Use WillOnce() so StrictMock will trigger an
168    // error if our expectations are not met exactly.  We want to verify that
169    // during a single run through the observer only one upload operation occurs
170    // (because it is costly) and similarly, that the writing of the uploaded
171    // status in the key payload matches the upload operation.
172    bool new_key = (mock_options & MOCK_NEW_KEY);
173    if (new_key || !key_uploaded) {
174      EXPECT_CALL(policy_client_,
175                  UploadCertificate(new_key ? "fake_cert" : certificate, _))
176          .WillOnce(WithArgs<1>(Invoke(StatusCallbackSuccess)));
177      EXPECT_CALL(cryptohome_client_,
178                  TpmAttestationSetKeyPayload(_, _, payload, _))
179          .WillOnce(WithArgs<3>(Invoke(DBusCallbackTrue)));
180    }
181
182    // Setup expected key generations.  Again use WillOnce().  Key generation is
183    // another costly operation and if it gets triggered more than once during
184    // a single pass this indicates a logical problem in the observer.
185    if (new_key) {
186      EXPECT_CALL(attestation_flow_, GetCertificate(_, _, _, _, _))
187          .WillOnce(WithArgs<4>(Invoke(CertCallbackSuccess)));
188    }
189  }
190
191  void Run() {
192    AttestationPolicyObserver observer(&policy_client_,
193                                       &cryptohome_client_,
194                                       &attestation_flow_);
195    observer.set_retry_delay(0);
196    base::RunLoop().RunUntilIdle();
197  }
198
199  std::string CreatePayload() {
200    AttestationKeyPayload proto;
201    proto.set_is_certificate_uploaded(true);
202    std::string serialized;
203    proto.SerializeToString(&serialized);
204    return serialized;
205  }
206
207  bool CreateCertificate(CertExpiryOptions options, std::string* certificate) {
208    base::Time valid_start = base::Time::Now() - base::TimeDelta::FromDays(90);
209    base::Time valid_expiry;
210    switch (options) {
211      case CERT_VALID:
212        valid_expiry = base::Time::Now() + base::TimeDelta::FromDays(90);
213        break;
214      case CERT_EXPIRING_SOON:
215        valid_expiry = base::Time::Now() + base::TimeDelta::FromDays(20);
216        break;
217      case CERT_EXPIRED:
218        valid_expiry = base::Time::Now() - base::TimeDelta::FromDays(20);
219        break;
220      default:
221        NOTREACHED();
222    }
223    scoped_ptr<crypto::RSAPrivateKey> test_key(
224        crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(
225            std::vector<uint8>(&kTestKeyData[0],
226                               &kTestKeyData[arraysize(kTestKeyData)])));
227    if (!test_key.get())
228      return false;
229    return net::x509_util::CreateSelfSignedCert(test_key.get(),
230                                                "CN=subject",
231                                                12345,
232                                                valid_start,
233                                                valid_expiry,
234                                                certificate);
235  }
236
237  base::MessageLoop message_loop_;
238  content::TestBrowserThread ui_thread_;
239  ScopedTestDeviceSettingsService test_device_settings_service_;
240  ScopedTestCrosSettings test_cros_settings_;
241  CrosSettingsProvider* device_settings_provider_;
242  StubCrosSettingsProvider stub_settings_provider_;
243  StrictMock<MockCryptohomeClient> cryptohome_client_;
244  StrictMock<MockAttestationFlow> attestation_flow_;
245  StrictMock<policy::MockCloudPolicyClient> policy_client_;
246};
247
248TEST_F(AttestationPolicyObserverTest, FeatureDisabled) {
249  CrosSettings* cros_settings = CrosSettings::Get();
250  cros_settings->SetBoolean(kDeviceAttestationEnabled, false);
251  Run();
252}
253
254TEST_F(AttestationPolicyObserverTest, UnregisteredPolicyClient) {
255  policy_client_.SetDMToken("");
256  Run();
257}
258
259TEST_F(AttestationPolicyObserverTest, NewCertificate) {
260  SetupMocks(MOCK_NEW_KEY, "");
261  Run();
262}
263
264TEST_F(AttestationPolicyObserverTest, KeyExistsNotUploaded) {
265  std::string certificate;
266  ASSERT_TRUE(CreateCertificate(CERT_VALID, &certificate));
267  SetupMocks(MOCK_KEY_EXISTS, certificate);
268  Run();
269}
270
271TEST_F(AttestationPolicyObserverTest, KeyExistsAlreadyUploaded) {
272  std::string certificate;
273  ASSERT_TRUE(CreateCertificate(CERT_VALID, &certificate));
274  SetupMocks(MOCK_KEY_EXISTS | MOCK_KEY_UPLOADED, certificate);
275  Run();
276}
277
278TEST_F(AttestationPolicyObserverTest, KeyExistsCertExpiringSoon) {
279  std::string certificate;
280  ASSERT_TRUE(CreateCertificate(CERT_EXPIRING_SOON, &certificate));
281  SetupMocks(MOCK_KEY_EXISTS | MOCK_KEY_UPLOADED | MOCK_NEW_KEY, certificate);
282  Run();
283}
284
285TEST_F(AttestationPolicyObserverTest, KeyExistsCertExpired) {
286  std::string certificate;
287  ASSERT_TRUE(CreateCertificate(CERT_EXPIRED, &certificate));
288  SetupMocks(MOCK_KEY_EXISTS | MOCK_KEY_UPLOADED | MOCK_NEW_KEY, certificate);
289  Run();
290}
291
292TEST_F(AttestationPolicyObserverTest, IgnoreUnknownCertFormat) {
293  SetupMocks(MOCK_KEY_EXISTS | MOCK_KEY_UPLOADED, "unsupported");
294  Run();
295}
296
297TEST_F(AttestationPolicyObserverTest, DBusFailureRetry) {
298  SetupMocks(MOCK_NEW_KEY, "");
299  // Simulate a DBus failure.
300  EXPECT_CALL(cryptohome_client_, TpmAttestationDoesKeyExist(_, _, _))
301      .WillOnce(WithArgs<2>(Invoke(DBusCallbackError)))
302      .WillRepeatedly(WithArgs<2>(Invoke(DBusCallbackFalse)));
303  Run();
304}
305
306}  // namespace attestation
307}  // namespace chromeos
308