File: extension_key_permissions_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (372 lines) | stat: -rw-r--r-- 13,638 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/platform_keys/extension_key_permissions_service.h"

#include <stdint.h>

#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>

#include "base/base64.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/ash/crosapi/keystore_service_ash.h"
#include "chrome/browser/ash/crosapi/keystore_service_factory_ash.h"
#include "chrome/browser/ash/platform_keys/key_permissions/key_permissions_service_impl.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/policy_constants.h"
#include "extensions/browser/state_store.h"

namespace chromeos::platform_keys {

namespace {
const char kStateStoreSPKI[] = "SPKI";
const char kStateStoreSignOnce[] = "signOnce";
const char kStateStoreSignUnlimited[] = "signUnlimited";

const char kPolicyAllowCorporateKeyUsage[] = "allowCorporateKeyUsage";

bool ContainsTag(uint64_t tags, crosapi::mojom::KeyTag value) {
  return tags & static_cast<uint64_t>(value);
}

const base::Value::Dict* GetKeyPermissionsMap(
    policy::PolicyService* const profile_policies) {
  if (!profile_policies) {
    return nullptr;
  }

  const policy::PolicyMap& policies = profile_policies->GetPolicies(
      policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string()));
  const base::Value* policy_value =
      policies.GetValue(policy::key::kKeyPermissions, base::Value::Type::DICT);
  if (!policy_value) {
    DVLOG(1) << "KeyPermissions policy is not set";
    return nullptr;
  }
  return policy_value->GetIfDict();
}

bool GetCorporateKeyUsageFromPref(
    const base::Value::Dict* key_permissions_for_ext) {
  if (!key_permissions_for_ext) {
    return false;
  }

  const base::Value* allow_corporate_key_usage =
      key_permissions_for_ext->Find(kPolicyAllowCorporateKeyUsage);
  if (!allow_corporate_key_usage || !allow_corporate_key_usage->is_bool()) {
    return false;
  }
  return allow_corporate_key_usage->GetBool();
}

// Returns true if the extension with id |extension_id| is allowed to use
// corporate usage keys by policy in |profile_policies|.
bool PolicyAllowsCorporateKeyUsageForExtension(
    const std::string& extension_id,
    policy::PolicyService* const profile_policies) {
  if (!profile_policies) {
    return false;
  }

  const base::Value::Dict* key_permissions_map =
      GetKeyPermissionsMap(profile_policies);
  if (!key_permissions_map) {
    return false;
  }

  const base::Value::Dict* key_permissions_for_ext =
      key_permissions_map->FindDict(extension_id);
  if (!key_permissions_for_ext) {
    return false;
  }

  bool allow_corporate_key_usage =
      GetCorporateKeyUsageFromPref(key_permissions_for_ext);

  VLOG_IF(2, allow_corporate_key_usage)
      << "Policy allows usage of corporate keys by extension " << extension_id;
  return allow_corporate_key_usage;
}

// Returns appropriate KeystoreService for |browser_context|.
//
// KeystoreService is expected to always outlive ExtensionKeyPermissionsService
// because ExtensionKeyPermissionsService instances are owned by
// ExtensionPlatformKeysService and the factory can return:
// * an instance owned by CrosapiManager (that is created before profiles and
// should outlive ExtensionPlatformKeysService)
// * or an appropriate keyed service that will always exist during
// ExtensionPlatformKeysService lifetime (because of KeyedService dependencies).
crosapi::mojom::KeystoreService* GetKeystoreService(
    content::BrowserContext* browser_context) {
  return crosapi::KeystoreServiceFactoryAsh::GetForBrowserContext(
      browser_context);
}

}  // namespace

ExtensionKeyPermissionsService::ExtensionKeyPermissionsService(
    const std::string& extension_id,
    extensions::StateStore* extensions_state_store,
    base::Value::List state_store_value,
    policy::PolicyService* profile_policies,
    content::BrowserContext* browser_context)
    : extension_id_(extension_id),
      extensions_state_store_(extensions_state_store),
      profile_policies_(profile_policies),
      keystore_service_(GetKeystoreService(browser_context)) {
  DCHECK(extensions_state_store_);
  DCHECK(profile_policies_);
  DCHECK(keystore_service_);
  KeyEntriesFromState(state_store_value);
}

ExtensionKeyPermissionsService::~ExtensionKeyPermissionsService() = default;

ExtensionKeyPermissionsService::KeyEntry*
ExtensionKeyPermissionsService::GetStateStoreEntry(
    const std::string& public_key_spki_der_b64) {
  for (KeyEntry& entry : state_store_entries_) {
    // For every ASN.1 value there is exactly one DER encoding, so it is fine to
    // compare the DER (or its base64 encoding).
    if (entry.spki_b64 == public_key_spki_der_b64) {
      return &entry;
    }
  }

  state_store_entries_.emplace_back(public_key_spki_der_b64);
  return &state_store_entries_.back();
}

void ExtensionKeyPermissionsService::CanUseKey(
    const std::vector<uint8_t>& public_key_spki_der,
    bool is_sign_operation,
    ExtensionKeyPermissionQueryCallback callback) {
  KeyEntry* matching_entry =
      GetStateStoreEntry(base::Base64Encode(public_key_spki_der));

  // In any case, we allow the generating extension to use the generated key a
  // single time for signing arbitrary data. The reason is that the extension
  // usually has to sign a certification request containing the public key in
  // order to obtain a certificate for the key.
  // That means, once a certificate authority generated a certificate for the
  // key, the generating extension doesn't have access to the key anymore,
  // except if explicitly permitted by the administrator.
  // Note: Semantically, `sign_once` can only be set for asymmetric keys used to
  // sign data. Any other key type should have that corresponding field unset
  // (which defaults to false).
  if (is_sign_operation && matching_entry->sign_once) {
    std::move(callback).Run(/*allowed=*/true);
    return;
  }

  auto bound_callback =
      base::BindOnce(&ExtensionKeyPermissionsService::CanUseKeyWithFlags,
                     weak_factory_.GetWeakPtr(), std::move(callback),
                     is_sign_operation, matching_entry->sign_unlimited);
  keystore_service_->GetKeyTags(public_key_spki_der, std::move(bound_callback));
}

void ExtensionKeyPermissionsService::CanUseKeyWithFlags(
    ExtensionKeyPermissionQueryCallback callback,
    bool is_sign_operation,
    bool sign_unlimited_allowed,
    crosapi::mojom::GetKeyTagsResultPtr key_tags) {
  if (key_tags->is_error()) {
    LOG(ERROR) << "Failed to check if the key is corporate: "
               << KeystoreErrorToString(key_tags->get_error());
    std::move(callback).Run(/*allowed=*/false);
    return;
  }

  // Usage of corporate keys is solely determined by policy. The user must not
  // circumvent this decision.
  if (ContainsTag(key_tags->get_tags(), crosapi::mojom::KeyTag::kCorporate)) {
    std::move(callback).Run(/*allowed=*/PolicyAllowsCorporateKeyUsage());
    return;
  }

  // Only signing permissions for keys that are not designated for corporate
  // usage are determined by user decisions.
  // Note: Similarly to `sign_once`, `sign_unlimited` can only be set for
  // asymmetric keys used to sign data. Any other key type should have that
  // corresponding field unset (which defaults to false).
  std::move(callback).Run(is_sign_operation && sign_unlimited_allowed);
}

void ExtensionKeyPermissionsService::SetKeyUsedForSigning(
    const std::vector<uint8_t>& public_key_spki_der,
    ExtensionKeyPermissionOperationCallback callback) {
  KeyEntry* matching_entry =
      GetStateStoreEntry(base::Base64Encode(public_key_spki_der));
  matching_entry->sign_once = false;
  WriteToStateStore();

  // Return success.
  std::move(callback).Run(/*is_error=*/false,
                          /*error=*/crosapi::mojom::KeystoreError::kUnknown);
}

void ExtensionKeyPermissionsService::RegisterKeyForCorporateUsage(
    const std::vector<uint8_t>& public_key_spki_der,
    ExtensionKeyPermissionOperationCallback callback) {
  keystore_service_->AddKeyTags(
      public_key_spki_der,
      static_cast<uint64_t>(crosapi::mojom::KeyTag::kCorporate),
      std::move(callback));
}

void ExtensionKeyPermissionsService::RegisterOneTimeSigningPermissionForKey(
    const std::vector<uint8_t>& public_key_spki_der) {
  KeyEntry* matching_entry =
      GetStateStoreEntry(base::Base64Encode(public_key_spki_der));

  matching_entry->sign_once = true;
  WriteToStateStore();
}

void ExtensionKeyPermissionsService::SetUserGrantedSigningPermission(
    const std::vector<uint8_t>& public_key_spki_der,
    ExtensionKeyPermissionOperationCallback callback) {
  keystore_service_->CanUserGrantPermissionForKey(
      public_key_spki_der,
      base::BindOnce(&ExtensionKeyPermissionsService::
                         SetUserGrantedSigningPermissionWithFlag,
                     weak_factory_.GetWeakPtr(), public_key_spki_der,
                     std::move(callback)));
}

void ExtensionKeyPermissionsService::SetUserGrantedSigningPermissionWithFlag(
    const std::vector<uint8_t>& public_key_spki_der,
    ExtensionKeyPermissionOperationCallback callback,
    bool can_user_grant_permission) {
  if (!can_user_grant_permission) {
    std::move(callback).Run(
        /*is_error=*/true,
        crosapi::mojom::KeystoreError::kGrantKeyPermissionForExtension);
    return;
  }

  KeyEntry* matching_entry =
      GetStateStoreEntry(base::Base64Encode(public_key_spki_der));

  if (matching_entry->sign_unlimited) {
    VLOG(1) << "Key is already allowed for signing, skipping.";
    // Return success.
    std::move(callback).Run(/*is_error=*/false,
                            /*error=*/crosapi::mojom::KeystoreError::kUnknown);
    return;
  }

  matching_entry->sign_unlimited = true;
  WriteToStateStore();
  // Return success.
  std::move(callback).Run(/*is_error=*/false,
                          /*error=*/crosapi::mojom::KeystoreError::kUnknown);
}

bool ExtensionKeyPermissionsService::PolicyAllowsCorporateKeyUsage() const {
  return PolicyAllowsCorporateKeyUsageForExtension(extension_id_,
                                                   profile_policies_);
}

void ExtensionKeyPermissionsService::WriteToStateStore() {
  extensions_state_store_->SetExtensionValue(
      extension_id_, kStateStorePlatformKeys, base::Value(KeyEntriesToState()));
}

void ExtensionKeyPermissionsService::KeyEntriesFromState(
    const base::Value::List& state) {
  state_store_entries_.clear();

  for (const auto& entry : state) {
    std::string spki_b64;
    if (entry.is_string()) {
      spki_b64 = entry.GetString();
      // This handles the case that the store contained a plain list of base64
      // and DER-encoded SPKIs from an older version of ChromeOS.
      KeyEntry new_entry(spki_b64);
      new_entry.sign_once = true;
      state_store_entries_.push_back(new_entry);
    } else if (entry.is_dict()) {
      const base::Value::Dict& dict_entry = entry.GetDict();
      const std::string* spki_b64_str = dict_entry.FindString(kStateStoreSPKI);
      if (spki_b64_str) {
        spki_b64 = *spki_b64_str;
      }
      KeyEntry new_entry(spki_b64);
      new_entry.sign_once = dict_entry.FindBool(kStateStoreSignOnce)
                                .value_or(new_entry.sign_once);
      new_entry.sign_unlimited = dict_entry.FindBool(kStateStoreSignUnlimited)
                                     .value_or(new_entry.sign_unlimited);
      state_store_entries_.push_back(new_entry);
    } else {
      LOG(ERROR) << "Found invalid entry of type " << entry.type()
                 << " in PlatformKeys state store.";
      continue;
    }
  }
}

base::Value::List ExtensionKeyPermissionsService::KeyEntriesToState() {
  base::Value::List new_state;
  for (const KeyEntry& entry : state_store_entries_) {
    // Drop entries that the extension doesn't have any permissions for anymore.
    if (!entry.sign_once && !entry.sign_unlimited) {
      continue;
    }

    base::Value::Dict new_entry;
    new_entry.Set(kStateStoreSPKI, entry.spki_b64);
    // Omit writing default values, namely |false|.
    if (entry.sign_once) {
      new_entry.Set(kStateStoreSignOnce, entry.sign_once);
    }
    if (entry.sign_unlimited) {
      new_entry.Set(kStateStoreSignUnlimited, entry.sign_unlimited);
    }
    new_state.Append(std::move(new_entry));
  }
  return new_state;
}

// static
std::vector<std::string>
ExtensionKeyPermissionsService::GetCorporateKeyUsageAllowedAppIds(
    policy::PolicyService* const profile_policies) {
  std::vector<std::string> permissions;

  const base::Value::Dict* key_permissions_service_map =
      GetKeyPermissionsMap(profile_policies);
  if (!key_permissions_service_map) {
    return permissions;
  }

  for (const auto item : *key_permissions_service_map) {
    const auto& app_id = item.first;
    const base::Value::Dict* key_permissions_service_for_app =
        item.second.GetIfDict();
    if (!key_permissions_service_for_app) {
      continue;
    }
    if (GetCorporateKeyUsageFromPref(key_permissions_service_for_app)) {
      permissions.push_back(app_id);
    }
  }
  return permissions;
}

}  // namespace chromeos::platform_keys