-
Notifications
You must be signed in to change notification settings - Fork 7
/
homedirs.cc
1861 lines (1644 loc) · 66 KB
/
homedirs.cc
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cryptohome/homedirs.h"
#include <algorithm>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include <base/bind.h>
#include <base/bind_helpers.h>
#include <base/files/file_path.h>
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/stringprintf.h>
#include <base/timer/elapsed_timer.h>
#include <brillo/cryptohome.h>
#include <brillo/secure_blob.h>
#include <chromeos/constants/cryptohome.h>
#include "cryptohome/credentials.h"
#include "cryptohome/crypto.h"
#include "cryptohome/crypto_error.h"
#include "cryptohome/cryptohome_metrics.h"
#include "cryptohome/cryptolib.h"
#include "cryptohome/dircrypto_util.h"
#include "cryptohome/mount.h"
#include "cryptohome/mount_helper.h"
#include "cryptohome/obfuscated_username.h"
#include "cryptohome/platform.h"
#include "cryptohome/user_oldest_activity_timestamp_cache.h"
#include "cryptohome/vault_keyset.h"
#include "key.pb.h" // NOLINT(build/include)
#include "signed_secret.pb.h" // NOLINT(build/include)
using base::FilePath;
using brillo::SecureBlob;
namespace cryptohome {
const char *kShadowRoot = "/home/.shadow";
const char *kEmptyOwner = "";
// xattr used for ARC++ M. No longer used since end of 2017, should be removed.
const char kAndroidCacheFilesAttribute[] = "user.AndroidCache";
// Each xattr is set to Android app internal data directory, contains
// 8-byte inode number of cache subdirectory. Used in ARC++ N, see
// frameworks/base/core/java/android/app/ContextImpl.java
const char kAndroidCacheInodeAttribute[] = "user.inode_cache";
const char kAndroidCodeCacheInodeAttribute[] = "user.inode_code_cache";
const char kTrackedDirectoryNameAttribute[] = "user.TrackedDirectoryName";
const char kRemovableFileAttribute[] = "user.GCacheRemovable";
// Name of the vault directory which is used with eCryptfs cryptohome.
const char kEcryptfsVaultDir[] = "vault";
// Name of the mount directory.
const char kMountDir[] = "mount";
namespace {
// Returns label of the given serialized vault keyset. The label is normally
// specified in the keyset itself, but for a legacy keyset it has to be
// automatically generated.
std::string GetSerializedKeysetLabel(const SerializedVaultKeyset& serialized,
int key_index) {
if (!serialized.has_key_data()) {
// Fallback for legacy keys, for which the label has to be inferred from the
// index number.
return base::StringPrintf("%s%d", kKeyLegacyPrefix, key_index);
}
return serialized.key_data().label();
}
void RemoveAllRemovableFiles(Platform* platform, const FilePath& dir) {
std::unique_ptr<FileEnumerator> file_enumerator(
platform->GetFileEnumerator(dir, true, base::FileEnumerator::FILES));
for (FilePath file = file_enumerator->Next(); !file.empty();
file = file_enumerator->Next()) {
if (platform->HasNoDumpFileAttribute(file)
|| platform->HasExtendedFileAttribute(file, kRemovableFileAttribute) ) {
if (!platform->DeleteFile(file, false)) {
PLOG(WARNING) << "DeleteFile: " << file.value();
}
}
}
}
} // namespace
HomeDirs::HomeDirs()
: default_platform_(new Platform()),
platform_(default_platform_.get()),
shadow_root_(FilePath(kShadowRoot)),
timestamp_cache_(NULL),
enterprise_owned_(false),
default_policy_provider_(new policy::PolicyProvider()),
policy_provider_(default_policy_provider_.get()),
crypto_(NULL),
default_mount_factory_(new MountFactory()),
mount_factory_(default_mount_factory_.get()),
default_vault_keyset_factory_(new VaultKeysetFactory()),
vault_keyset_factory_(default_vault_keyset_factory_.get()) { }
HomeDirs::~HomeDirs() { }
// static
FilePath HomeDirs::GetEcryptfsUserVaultPath(
const FilePath& shadow_root, const std::string& obfuscated_username) {
return shadow_root.Append(obfuscated_username).Append(kEcryptfsVaultDir);
}
// static
FilePath HomeDirs::GetUserMountDirectory(
const FilePath& shadow_root, const std::string& obfuscated_username) {
return shadow_root.Append(obfuscated_username).Append(kMountDir);
}
bool HomeDirs::Init(Platform* platform, Crypto* crypto,
UserOldestActivityTimestampCache *cache) {
platform_ = platform;
crypto_ = crypto;
timestamp_cache_ = cache;
LoadDevicePolicy();
if (!platform_->DirectoryExists(shadow_root_))
platform_->CreateDirectory(shadow_root_);
return GetSystemSalt(NULL);
}
bool HomeDirs::IsFreableDiskSpaceAvaible() {
if (!enterprise_owned_)
return false;
const auto homedirs = GetHomeDirs();
int unmounted_cryptohomes =
std::count_if(homedirs.begin(), homedirs.end(),
[](auto& dir) { return !dir.is_mounted; });
return unmounted_cryptohomes > 0;
}
void HomeDirs::FreeDiskSpace() {
auto free_space = AmountOfFreeDiskSpace();
switch (GetFreeDiskSpaceState(free_space)) {
case HomeDirs::FreeSpaceState::kAboveTarget:
case HomeDirs::FreeSpaceState::kAboveThreshold:
// Already have enough space. No need to clean up.
return;
case HomeDirs::FreeSpaceState::kNeedNormalCleanup:
case HomeDirs::FreeSpaceState::kNeedAggressiveCleanup:
// trigger cleanup
break;
case HomeDirs::FreeSpaceState::kError:
LOG(ERROR) << "Failed to get the amount of free disk space";
return;
default:
LOG(ERROR) << "Unhandled free disk state";
return;
}
auto now = platform_->GetCurrentTime();
if (last_free_disk_space_) {
auto diff = now - *last_free_disk_space_;
ReportTimeBetweenFreeDiskSpace(diff.InSeconds());
}
last_free_disk_space_ = now;
base::ElapsedTimer total_timer;
FreeDiskSpaceInternal();
ReportFreeDiskSpaceTotalTime(total_timer.Elapsed().InMilliseconds());
auto after_cleanup = AmountOfFreeDiskSpace();
if (!after_cleanup) {
LOG(ERROR) << "Failed to get the amount of free disk space";
return;
}
ReportFreeDiskSpaceTotalFreedInMb(
MAX(0, after_cleanup.value() - free_space.value()) / 1024 / 1024);
LOG(INFO) << "Disk cleanup complete.";
}
void HomeDirs::FreeDiskSpaceInternal() {
auto homedirs = GetHomeDirs();
auto unmounted_homedirs = homedirs;
FilterMountedHomedirs(&unmounted_homedirs);
// If ephemeral users are enabled, remove all cryptohomes except those
// currently mounted or belonging to the owner.
// |AreEphemeralUsers| will reload the policy to guarantee freshness.
if (AreEphemeralUsersEnabled()) {
RemoveNonOwnerCryptohomesInternal(homedirs);
ReportDiskCleanupProgress(
DiskCleanupProgress::kEphemeralUserProfilesCleaned);
return;
}
// Clean Cache directories for every user (except current one).
for (const auto& dir : unmounted_homedirs) {
HomeDirs::DeleteCacheCallback(dir.shadow);
}
auto freeDiskSpace = AmountOfFreeDiskSpace();
if (!freeDiskSpace) {
LOG(ERROR) << "Failed to get the amount of free space";
return;
}
if (GetFreeDiskSpaceState(freeDiskSpace)
== HomeDirs::FreeSpaceState::kAboveTarget) {
ReportDiskCleanupProgress(
DiskCleanupProgress::kBrowserCacheCleanedAboveTarget);
return;
}
// Clean GCache directories for every user (except current one).
for (const auto& dir : unmounted_homedirs) {
HomeDirs::DeleteGCacheTmpCallback(dir.shadow);
}
const auto old_free_disk_space = freeDiskSpace;
freeDiskSpace = AmountOfFreeDiskSpace();
if (!freeDiskSpace) {
LOG(ERROR) << "Failed to get the amount of free space";
return;
}
const int64_t freed_gcache_space = freeDiskSpace.value() -
old_free_disk_space.value();
// Report only if something was deleted.
if (freed_gcache_space > 0) {
ReportFreedGCacheDiskSpaceInMb(freed_gcache_space / 1024 / 1024);
}
switch (GetFreeDiskSpaceState(freeDiskSpace)) {
case HomeDirs::FreeSpaceState::kAboveTarget:
ReportDiskCleanupProgress(
DiskCleanupProgress::kGoogleDriveCacheCleanedAboveTarget);
return;
case HomeDirs::FreeSpaceState::kAboveThreshold:
case HomeDirs::FreeSpaceState::kNeedNormalCleanup:
ReportDiskCleanupProgress(
DiskCleanupProgress::kGoogleDriveCacheCleanedAboveMinimum);
return;
case HomeDirs::FreeSpaceState::kNeedAggressiveCleanup:
// continue cleanup
break;
case HomeDirs::FreeSpaceState::kError:
LOG(ERROR) << "Failed to get the amount of free space";
return;
default:
LOG(ERROR) << "Unhandled free disk state";
return;
}
// Clean Android cache directories for every user (except current one).
for (const auto& dir : unmounted_homedirs) {
HomeDirs::DeleteAndroidCacheCallback(dir.shadow);
}
switch (GetFreeDiskSpaceState()) {
case HomeDirs::FreeSpaceState::kAboveTarget:
ReportDiskCleanupProgress(
DiskCleanupProgress::kAndroidCacheCleanedAboveTarget);
return;
case HomeDirs::FreeSpaceState::kAboveThreshold:
case HomeDirs::FreeSpaceState::kNeedNormalCleanup:
ReportDiskCleanupProgress(
DiskCleanupProgress::kAndroidCacheCleanedAboveMinimum);
return;
case HomeDirs::FreeSpaceState::kNeedAggressiveCleanup:
// continue cleanup
break;
case HomeDirs::FreeSpaceState::kError:
LOG(ERROR) << "Failed to get the amount of free space";
return;
default:
LOG(ERROR) << "Unhandled free disk state";
return;
}
const int deleted_users_count = DeleteUserProfiles(homedirs);
if (deleted_users_count > 0) {
ReportDeletedUserProfiles(deleted_users_count);
}
// We had a chance to delete a user only if any unmounted homes existed.
if (unmounted_homedirs.size() > 0) {
ReportDiskCleanupProgress(
HasTargetFreeSpace()
? DiskCleanupProgress::kWholeUserProfilesCleanedAboveTarget
: DiskCleanupProgress::kWholeUserProfilesCleaned);
} else {
ReportDiskCleanupProgress(DiskCleanupProgress::kNoUnmountedCryptohomes);
}
}
int HomeDirs::DeleteUserProfiles(const std::vector<HomeDir>& homedirs) {
int deleted_users_count = 0;
// Initialize user timestamp cache if it has not been yet. This reads the
// last-activity time from each homedir's SerializedVaultKeyset. This value
// is only updated in the value keyset on unmount and every 24 hrs, so a
// currently logged in user probably doesn't have an up to date value. This
// is okay, since we don't delete currently logged in homedirs anyway. (See
// Mount::UpdateCurrentUserActivityTimestamp()).
if (!timestamp_cache_->initialized()) {
timestamp_cache_->Initialize();
for (const auto& dir : homedirs) {
HomeDirs::AddUserTimestampToCacheCallback(dir.shadow);
}
}
// Delete old users using timestamp_cache_, the oldest first.
// Don't delete anyone if we don't know who the owner is.
// For consumer devices, don't delete the device owner. Enterprise-enrolled
// devices have no owner, so don't delete the last user.
std::string owner;
if (enterprise_owned_ || GetOwner(&owner)) {
int mounted_cryptohomes =
std::count_if(homedirs.begin(), homedirs.end(),
[](auto& dir) { return dir.is_mounted; });
while (!timestamp_cache_->empty()) {
base::Time deleted_timestamp = timestamp_cache_->oldest_known_timestamp();
FilePath deleted_user_dir = timestamp_cache_->RemoveOldestUser();
std::string obfuscated = deleted_user_dir.BaseName().value();
if (enterprise_owned_) {
// If mounted_cryptohomes== 0, then there were no mounted cryptohomes
// and hence no logged in users. Thus we want to skip the last user in
// our list, since they were the most-recent user on the device.
if (timestamp_cache_->empty() && mounted_cryptohomes == 0) {
// Put this user back in the cache, since they shouldn't be
// permanently skipped; they may not be most-recent the next
// time we run, and then they should be a candidate for deletion.
timestamp_cache_->AddExistingUser(deleted_user_dir,
deleted_timestamp);
LOG(INFO) << "Skipped deletion of the most recent device user.";
break;
}
} else {
if (obfuscated == owner) {
// We should never delete the device owner, so we permanently skip
// them by not adding them back to the cache.
LOG(INFO) << "Skipped deletion of the device owner.";
continue;
}
}
if (platform_->IsDirectoryMounted(
brillo::cryptohome::home::GetHashedUserPath(obfuscated))) {
LOG(INFO) << "Attempt to delete currently logged in user. Skipped...";
} else {
LOG(INFO) << "Freeing disk space by deleting user "
<< deleted_user_dir.value();
RemoveLECredentials(deleted_user_dir.BaseName().value());
platform_->DeleteFile(deleted_user_dir, true);
++deleted_users_count;
if (HasTargetFreeSpace())
break;
}
}
}
return deleted_users_count;
}
base::Optional<int64_t> HomeDirs::AmountOfFreeDiskSpace() const {
int64_t free_space = platform_->AmountOfFreeDiskSpace(shadow_root_);
if (free_space < 0) {
return base::nullopt;
} else {
return free_space;
}
}
HomeDirs::FreeSpaceState HomeDirs::GetFreeDiskSpaceState() const {
return GetFreeDiskSpaceState(AmountOfFreeDiskSpace());
}
HomeDirs::FreeSpaceState HomeDirs::GetFreeDiskSpaceState(
base::Optional<int64_t> free_disk_space) const {
if (!free_disk_space) {
return HomeDirs::FreeSpaceState::kError;
}
int64_t value = free_disk_space.value();
if (value >= kTargetFreeSpaceAfterCleanup) {
return HomeDirs::FreeSpaceState::kAboveTarget;
} else if (value >= kFreeSpaceThresholdToTriggerCleanup) {
return HomeDirs::FreeSpaceState::kAboveThreshold;
} else if (value >= kFreeSpaceThresholdToTriggerAggressiveCleanup) {
return HomeDirs::FreeSpaceState::kNeedNormalCleanup;
} else {
return HomeDirs::FreeSpaceState::kNeedAggressiveCleanup;
}
}
bool HomeDirs::HasTargetFreeSpace() const {
return GetFreeDiskSpaceState() == HomeDirs::FreeSpaceState::kAboveTarget;
}
void HomeDirs::LoadDevicePolicy() {
policy_provider_->Reload();
}
bool HomeDirs::AreEphemeralUsersEnabled() {
LoadDevicePolicy();
// If the policy cannot be loaded, default to non-ephemeral users.
bool ephemeral_users_enabled = false;
if (policy_provider_->device_policy_is_loaded())
policy_provider_->GetDevicePolicy().GetEphemeralUsersEnabled(
&ephemeral_users_enabled);
return ephemeral_users_enabled;
}
bool HomeDirs::AreCredentialsValid(const Credentials& creds) {
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
return GetValidKeyset(creds, vk.get(), nullptr /* key_index */,
nullptr /* error */);
}
bool HomeDirs::GetValidKeyset(const Credentials& creds,
VaultKeyset* vk,
int* key_index,
MountError* error) {
if (error)
*error = MOUNT_ERROR_NONE;
if (!vk) {
if (error)
*error = MOUNT_ERROR_FATAL;
return false;
}
std::string owner;
std::string obfuscated = creds.GetObfuscatedUsername(system_salt_);
// |AreEphemeralUsers| will reload the policy to guarantee freshness.
if (AreEphemeralUsersEnabled() && GetOwner(&owner) && obfuscated != owner) {
if (error)
*error = MOUNT_ERROR_FATAL;
return false;
}
std::vector<int> key_indices;
if (!GetVaultKeysets(obfuscated, &key_indices)) {
LOG(WARNING) << "No valid keysets on disk for " << obfuscated;
if (error)
*error = MOUNT_ERROR_FATAL;
return false;
}
SecureBlob passkey;
creds.GetPasskey(&passkey);
bool any_keyset_exists = false;
CryptoError last_crypto_error = CryptoError::CE_NONE;
for (int index : key_indices) {
if (!vk->Load(GetVaultKeysetPath(obfuscated, index)))
continue;
any_keyset_exists = true;
// Skip decrypt attempts if the label doesn't match.
// Treat an empty creds label as a wildcard.
if (!creds.key_data().label().empty() &&
creds.key_data().label() !=
GetSerializedKeysetLabel(vk->serialized(), index))
continue;
// Skip LE Credentials if not explicitly identified by a label, since we
// don't want unnecessary wrong attempts.
if (creds.key_data().label().empty() &&
(vk->serialized().flags() & SerializedVaultKeyset::LE_CREDENTIAL))
continue;
bool is_pcr_extended =
platform_->FileExists(base::FilePath(kLockedToSingleUserFile));
if (vk->Decrypt(passkey, is_pcr_extended, &last_crypto_error)) {
if (key_index)
*key_index = index;
return true;
}
}
MountError local_error = MOUNT_ERROR_NONE;
if (!any_keyset_exists) {
LOG(ERROR) << "No parsable keysets found for " << obfuscated;
local_error = MOUNT_ERROR_FATAL;
} else if (last_crypto_error == CryptoError::CE_NONE) {
// If we're searching by label, don't let a no-key-found become
// MOUNT_ERROR_FATAL. In the past, no parseable key was a fatal
// error. Just treat it like an invalid key. This allows for
// multiple per-label requests then a wildcard, worst case, before
// the Cryptohome is removed.
if (!creds.key_data().label().empty()) {
LOG(ERROR) << "Failed to find the specified keyset for " << obfuscated;
local_error = MOUNT_ERROR_KEY_FAILURE;
} else {
LOG(ERROR) << "Failed to find any suitable keyset for " << obfuscated;
local_error = MOUNT_ERROR_FATAL;
}
} else {
switch (last_crypto_error) {
case CryptoError::CE_TPM_FATAL:
case CryptoError::CE_OTHER_FATAL:
local_error = MOUNT_ERROR_FATAL;
break;
case CryptoError::CE_TPM_COMM_ERROR:
local_error = MOUNT_ERROR_TPM_COMM_ERROR;
break;
case CryptoError::CE_TPM_DEFEND_LOCK:
local_error = MOUNT_ERROR_TPM_DEFEND_LOCK;
break;
case CryptoError::CE_TPM_REBOOT:
local_error = MOUNT_ERROR_TPM_NEEDS_REBOOT;
break;
default:
local_error = MOUNT_ERROR_KEY_FAILURE;
break;
}
LOG(ERROR) << "Failed to decrypt any keysets for " << obfuscated
<< ": mount error " << local_error << ", crypto error "
<< last_crypto_error;
}
if (error)
*error = local_error;
return false;
}
bool HomeDirs::SetLockedToSingleUser() const {
return platform_->TouchFileDurable(base::FilePath(kLockedToSingleUserFile));
}
bool HomeDirs::Exists(const std::string& obfuscated_username) const {
FilePath user_dir = shadow_root_.Append(obfuscated_username);
return platform_->DirectoryExists(user_dir);
}
bool HomeDirs::CryptohomeExists(const std::string& obfuscated_username) const {
return EcryptfsCryptohomeExists(obfuscated_username) ||
DircryptoCryptohomeExists(obfuscated_username);
}
bool HomeDirs::EcryptfsCryptohomeExists(
const std::string& obfuscated_username) const {
// Check for the presence of a vault directory for ecryptfs.
return platform_->DirectoryExists(
GetEcryptfsUserVaultPath(obfuscated_username));
}
bool HomeDirs::DircryptoCryptohomeExists(
const std::string& obfuscated_username) const {
// Check for the presence of an encrypted mount directory for dircrypto.
FilePath mount_path = GetUserMountDirectory(obfuscated_username);
return platform_->DirectoryExists(mount_path) &&
platform_->GetDirCryptoKeyState(mount_path) ==
dircrypto::KeyState::ENCRYPTED;
}
FilePath HomeDirs::GetEcryptfsUserVaultPath(
const std::string& obfuscated_username) const {
return GetEcryptfsUserVaultPath(shadow_root_, obfuscated_username);
}
FilePath HomeDirs::GetUserMountDirectory(
const std::string& obfuscated_username) const {
return GetUserMountDirectory(shadow_root_, obfuscated_username);
}
VaultKeyset* HomeDirs::GetVaultKeyset(const std::string& obfuscated_username,
const std::string& key_label) const {
if (key_label.empty())
return NULL;
// Walk all indices to find a match.
// We should move to label-derived suffixes to be efficient.
std::vector<int> key_indices;
if (!GetVaultKeysets(obfuscated_username, &key_indices))
return NULL;
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
for (int index : key_indices) {
if (!LoadVaultKeysetForUser(obfuscated_username, index, vk.get())) {
continue;
}
if (GetSerializedKeysetLabel(vk->serialized(), index) == key_label) {
vk->set_legacy_index(index);
return vk.release();
}
}
return NULL;
}
// TODO(wad) Figure out how this might fit in with vault_keyset.cc
bool HomeDirs::GetVaultKeysets(const std::string& obfuscated,
std::vector<int>* keysets) const {
CHECK(keysets);
FilePath user_dir = shadow_root_.Append(obfuscated);
std::unique_ptr<FileEnumerator> file_enumerator(
platform_->GetFileEnumerator(user_dir, false,
base::FileEnumerator::FILES));
FilePath next_path;
while (!(next_path = file_enumerator->Next()).empty()) {
FilePath file_name = next_path.BaseName();
// Scan for "master." files.
if (file_name.RemoveFinalExtension().value() != kKeyFile) {
continue;
}
std::string index_str = file_name.FinalExtension();
int index;
if (!base::StringToInt(&index_str[1], &index)) {
continue;
}
// The test below will catch all strtol(3) error conditions.
if (index < 0 || index >= kKeyFileMax) {
LOG(ERROR) << "Invalid key file range: " << index;
continue;
}
keysets->push_back(static_cast<int>(index));
}
// Ensure it is sorted numerically and not lexigraphically.
std::sort(keysets->begin(), keysets->end());
return keysets->size() != 0;
}
bool HomeDirs::GetVaultKeysetLabels(const std::string& obfuscated_username,
std::vector<std::string>* labels) const {
CHECK(labels);
FilePath user_dir = shadow_root_.Append(obfuscated_username);
std::unique_ptr<FileEnumerator> file_enumerator(
platform_->GetFileEnumerator(user_dir, false /* Not recursive. */,
base::FileEnumerator::FILES));
FilePath next_path;
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
while (!(next_path = file_enumerator->Next()).empty()) {
FilePath file_name = next_path.BaseName();
// Scan for "master." files.
if (file_name.RemoveFinalExtension().value() != kKeyFile) {
continue;
}
int index = 0;
std::string index_str = file_name.FinalExtension();
// StringToInt will only return true for a perfect conversion.
if (!base::StringToInt(&index_str[1], &index)) {
continue;
}
if (index < 0 || index >= kKeyFileMax) {
LOG(ERROR) << "Invalid key file range: " << index;
continue;
}
// Now parse the keyset to get its label or skip it.
if (!LoadVaultKeysetForUser(obfuscated_username, index, vk.get())) {
continue;
}
labels->push_back(GetSerializedKeysetLabel(vk->serialized(), index));
}
return (labels->size() > 0);
}
bool HomeDirs::CheckAuthorizationSignature(const KeyData& existing_key_data,
const Key& new_key,
const std::string& signature) {
// If the existing key doesn't require authorization, then there's no
// work to be done.
//
// Note, only the first authorizaton_data is honored at present.
if (!existing_key_data.authorization_data_size() ||
!existing_key_data.authorization_data(0).has_type())
return true;
if (!new_key.data().has_revision()) {
LOG(INFO) << "CheckAuthorizationSignature called with no revision";
return false;
}
const KeyAuthorizationData* existing_auth_data =
&existing_key_data.authorization_data(0);
const KeyAuthorizationSecret* secret;
switch (existing_auth_data->type()) {
// The data is passed in the clear but authenticated with a shared
// symmetric secret.
case KeyAuthorizationData::KEY_AUTHORIZATION_TYPE_HMACSHA256:
// Ensure there is an accessible signing key. Only a single
// secret is allowed until there is a reason to support more.
secret = NULL;
for (int secret_i = 0;
secret_i < existing_auth_data->secrets_size();
++secret_i) {
secret = &existing_auth_data->secrets(secret_i);
if (secret->usage().sign() && !secret->wrapped())
break;
secret = NULL; // Clear if the candidate doesn't match.
}
if (!secret) {
LOG(ERROR) << "Could not find a valid signing key for HMACSHA256";
return false;
}
break;
// The data is passed encrypted and authenticated with dedicated
// encrypting and signing symmetric keys.
case KeyAuthorizationData::KEY_AUTHORIZATION_TYPE_AES256CBC_HMACSHA256:
LOG(ERROR) << "KEY_AUTHORIZATION_TYPE_AES256CBC_HMACSHA256 not supported";
return false;
default:
LOG(ERROR) << "Unknown KeyAuthorizationType seen";
return false;
}
// Now we're only handling HMACSHA256.
// Specifically, HMACSHA256 is meant for interoperating with a server-side
// signed password change operation which only specifies the revision and
// new passphrase. That means that change fields must be filtered to limit
// silent updates to fields. At present, this is done after this call. If
// the signed fields vary by KeyAuthorizationType in the future, it should
// be done here.
std::string changes_str;
ac::chrome::managedaccounts::account::Secret new_secret;
new_secret.set_revision(new_key.data().revision());
new_secret.set_secret(new_key.secret());
if (!new_secret.SerializeToString(&changes_str)) {
LOG(ERROR) << "Failed to serialized the new key";
return false;
}
// Compute the HMAC
brillo::SecureBlob hmac_key(secret->symmetric_key());
brillo::SecureBlob data(changes_str.begin(), changes_str.end());
SecureBlob hmac = CryptoLib::HmacSha256(hmac_key, data);
// Check the HMAC
if (signature.length() != hmac.size() ||
brillo::SecureMemcmp(signature.data(), hmac.data(),
std::min(signature.size(), hmac.size()))) {
LOG(ERROR) << "Supplied authorization signature was invalid.";
return false;
}
if (existing_key_data.has_revision() &&
existing_key_data.revision() >= new_key.data().revision()) {
LOG(ERROR) << "The supplied key revision was too old.";
return false;
}
return true;
}
CryptohomeErrorCode HomeDirs::UpdateKeyset(
const Credentials& credentials,
const Key* key_changes,
const std::string& authorization_signature) {
const std::string obfuscated_username =
credentials.GetObfuscatedUsername(system_salt_);
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
if (!GetValidKeyset(credentials, vk.get(), nullptr /* key_index */,
nullptr /* error */)) {
// Differentiate between failure and non-existent.
if (!credentials.key_data().label().empty()) {
vk.reset(
GetVaultKeyset(obfuscated_username, credentials.key_data().label()));
if (!vk.get()) {
LOG(WARNING) << "UpdateKeyset: key not found";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_NOT_FOUND;
}
}
LOG(WARNING) << "UpdateKeyset: invalid authentication provided";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_FAILED;
}
SerializedVaultKeyset *key = vk->mutable_serialized();
// Check the privileges to ensure Update is allowed.
// [In practice, Add/Remove could be used to override if present.]
bool authorized_update = false;
if (key->has_key_data()) {
authorized_update = key->key_data().privileges().authorized_update();
if (!key->key_data().privileges().update() && !authorized_update) {
LOG(WARNING) << "UpdateKeyset: no update() privilege";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_DENIED;
}
}
// Check the signature first so the rest of the function is untouched.
if (authorized_update) {
if (authorization_signature.empty() ||
!CheckAuthorizationSignature(key->key_data(),
*key_changes,
authorization_signature)) {
LOG(INFO) << "Unauthorized update attempted";
return CRYPTOHOME_ERROR_UPDATE_SIGNATURE_INVALID;
}
}
// Walk through each field and update the value.
KeyData* merged_data = key->mutable_key_data();
// Note! Revisions aren't tracked in general.
if (key_changes->data().has_revision()) {
merged_data->set_revision(key_changes->data().revision());
}
// TODO(wad,dkrahn): Add privilege dropping.
SecureBlob passkey;
credentials.GetPasskey(&passkey);
if (key_changes->has_secret()) {
SecureBlob new_passkey(key_changes->secret().begin(),
key_changes->secret().end());
passkey.swap(new_passkey);
}
// Only merge additional KeyData if the update is not restricted.
if (!authorized_update) {
if (key_changes->data().has_type()) {
merged_data->set_type(key_changes->data().type());
}
if (key_changes->data().has_label()) {
merged_data->set_label(key_changes->data().label());
}
// Do not allow authorized_updates to change their keys unless we add
// a new signature type. This can be done in the future by adding
// the authorization_data() to the new key_data, and changing the
// CheckAuthorizationSignature() to check for a compatible "upgrade".
if (key_changes->data().authorization_data_size() > 0) {
// Only the first will be merged for now.
*(merged_data->add_authorization_data()) =
key_changes->data().authorization_data(0);
}
}
if (!vk->Encrypt(passkey, obfuscated_username) ||
!vk->Save(vk->source_file())) {
LOG(ERROR) << "Failed to encrypt and write the updated keyset";
return CRYPTOHOME_ERROR_BACKING_STORE_FAILURE;
}
return CRYPTOHOME_ERROR_NOT_SET;
}
CryptohomeErrorCode HomeDirs::AddKeyset(
const Credentials& existing_credentials,
const SecureBlob& new_passkey,
const KeyData* new_data, // NULLable
bool clobber,
int* index) {
// TODO(wad) Determine how to best bubble up the failures MOUNT_ERROR
// encapsulate wrt the TPM behavior.
std::string obfuscated = existing_credentials.GetObfuscatedUsername(
system_salt_);
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
if (!GetValidKeyset(existing_credentials, vk.get(), nullptr /* key_index */,
nullptr /* error */)) {
// Differentiate between failure and non-existent.
if (!existing_credentials.key_data().label().empty()) {
vk.reset(
GetVaultKeyset(obfuscated, existing_credentials.key_data().label()));
if (!vk.get()) {
LOG(WARNING) << "AddKeyset: key not found";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_NOT_FOUND;
}
}
LOG(WARNING) << "AddKeyset: invalid authentication provided";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_FAILED;
}
// Check the privileges to ensure Add is allowed.
// Keys without extended data are considered fully privileged.
if (vk->serialized().has_key_data() &&
!vk->serialized().key_data().privileges().add()) {
// TODO(wad) Ensure this error can be returned as a KEY_DENIED error
// for AddKeyEx.
LOG(WARNING) << "AddKeyset: no add() privilege";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_DENIED;
}
// If the VaultKeyset doesn't have a reset seed, simply generate
// one and re-encrypt before proceeding.
if (!vk->serialized().has_wrapped_reset_seed()) {
LOG(INFO) << "Keyset lacks reset_seed; generating one.";
vk->CreateRandomResetSeed();
brillo::SecureBlob passkey;
existing_credentials.GetPasskey(&passkey);
if (!vk->Encrypt(passkey, obfuscated) || !vk->Save(vk->source_file())) {
LOG(WARNING) << "Failed to re-encrypt the old keyset";
return CRYPTOHOME_ERROR_BACKING_STORE_FAILURE;
}
}
// Walk the namespace looking for the first free spot.
// Optimizations can come later.
// Note, nothing is stopping simultaenous access to these files
// or enforcing mandatory locking.
int new_index = 0;
FILE* vk_file = NULL;
FilePath vk_path;
for ( ; new_index < kKeyFileMax; ++new_index) {
vk_path = GetVaultKeysetPath(obfuscated, new_index);
// Rely on fopen()'s O_EXCL|O_CREAT behavior to fail
// repeatedly until there is an opening.
// TODO(wad) Add a clean-up-0-byte-keysets helper to c-home startup
vk_file = platform_->OpenFile(vk_path, "wx");
if (vk_file) // got one
break;
}
if (!vk_file) {
LOG(WARNING) << "Failed to find an available keyset slot";
return CRYPTOHOME_ERROR_KEY_QUOTA_EXCEEDED;
}
// Once the file has been claimed, we can release the handle.
platform_->CloseFile(vk_file);
// Before persisting, check, in a racy-way, if there is
// an existing labeled credential.
if (new_data) {
std::unique_ptr<VaultKeyset> match(
GetVaultKeyset(obfuscated, new_data->label()));
if (match.get()) {
LOG(INFO) << "Label already exists.";
platform_->DeleteFile(vk_path, false);
if (!clobber) {
return CRYPTOHOME_ERROR_KEY_LABEL_EXISTS;
}
new_index = match->legacy_index();
vk_path = match->source_file();
}
}
// Since we're reusing the authorizing VaultKeyset, be careful with the
// metadata.
vk->mutable_serialized()->clear_key_data();
if (new_data) {
*(vk->mutable_serialized()->mutable_key_data()) = *new_data;
}
// Repersist the VK with the new creds.
CryptohomeErrorCode added = CRYPTOHOME_ERROR_NOT_SET;
if (!vk->Encrypt(new_passkey, obfuscated) || !vk->Save(vk_path)) {
LOG(WARNING) << "Failed to encrypt or write the new keyset";
added = CRYPTOHOME_ERROR_BACKING_STORE_FAILURE;
// If we're clobbering, don't delete on error.
if (!clobber) {
platform_->DeleteFile(vk_path, false);
}
} else {
*index = new_index;
}
return added;
}
CryptohomeErrorCode HomeDirs::RemoveKeyset(
const Credentials& credentials,
const KeyData& key_data) {
// This error condition should be caught by the caller.
if (key_data.label().empty())
return CRYPTOHOME_ERROR_KEY_NOT_FOUND;
const std::string obfuscated =
credentials.GetObfuscatedUsername(system_salt_);
std::unique_ptr<VaultKeyset> remove_vk(
GetVaultKeyset(obfuscated, key_data.label()));
if (!remove_vk.get()) {
LOG(WARNING) << "RemoveKeyset: key to remove not found";
return CRYPTOHOME_ERROR_KEY_NOT_FOUND;
}
std::unique_ptr<VaultKeyset> vk(vault_keyset_factory()->New(
platform_, crypto_));
if (!GetValidKeyset(credentials, vk.get(), nullptr /* key_index */,
nullptr /* error */)) {
// Differentiate between failure and non-existent.
if (!credentials.key_data().label().empty()) {
vk.reset(GetVaultKeyset(obfuscated, credentials.key_data().label()));
if (!vk.get()) {
LOG(WARNING) << "RemoveKeyset: key not found";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_NOT_FOUND;
}
}
LOG(WARNING) << "RemoveKeyset: invalid authentication provided";
return CRYPTOHOME_ERROR_AUTHORIZATION_KEY_FAILED;
}