-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtpm_utility_impl.cc
2847 lines (2644 loc) · 102 KB
/
tpm_utility_impl.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 2014 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 "trunks/tpm_utility_impl.h"
#include <cstdint>
#include <memory>
#include <base/logging.h>
#include <base/sha1.h>
#include <base/stl_util.h>
#include <base/strings/string_number_conversions.h>
#include <base/sys_byteorder.h>
#include <crypto/libcrypto-compat.h>
#include <crypto/openssl_util.h>
#include <crypto/scoped_openssl_types.h>
#include <crypto/secure_hash.h>
#include <crypto/sha2.h>
#include <openssl/aes.h>
#include <openssl/ecdsa.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include "trunks/authorization_delegate.h"
#include "trunks/blob_parser.h"
#include "trunks/command_transceiver.h"
#include "trunks/error_codes.h"
#include "trunks/hmac_authorization_delegate.h"
#include "trunks/hmac_session.h"
#include "trunks/policy_session.h"
#include "trunks/tpm_constants.h"
#include "trunks/tpm_pinweaver.h"
#include "trunks/tpm_state.h"
#include "trunks/trunks_factory.h"
namespace {
const char kPlatformPassword[] = "cros-platform";
const size_t kMaxPasswordLength = 32;
// The below maximum is defined in TPM 2.0 Library Spec Part 2 Section 13.1
const uint32_t kMaxNVSpaceIndex = (1 << 24) - 1;
// Cr50 Vendor ID ("CROS").
const uint32_t kVendorIdCr50 = 0x43524f53;
// Command code for Cr50 vendor-specific commands,
const uint32_t kCr50VendorCC = 0x20000000 | 0; /* Vendor Bit Set + 0 */
// Vendor-specific subcommand codes.
const uint16_t kCr50SubcmdInvalidateInactiveRW = 20;
const uint16_t kCr50GetRmaChallenge = 30;
const uint16_t kCr50SubcmdManageCCDPwd = 33;
const uint16_t kCr50SubcmdGetAlertsData = 35;
const uint16_t kCr50SubcmdPinWeaver = 37;
// Auth policy used in RSA and ECC templates for EK keys generation.
// From TCG Credential Profile EK 2.0. Section 2.1.5.
const std::string kEKTemplateAuthPolicy(
"\x83\x71\x97\x67\x44\x84\xB3\xF8\x1A\x90\xCC\x8D\x46\xA5\xD7\x24"
"\xFD\x52\xD7\x6E\x06\x52\x0B\x64\xF2\xA1\xDA\x1B\x33\x14\x69\xAA");
// Salt used exclusively for the Remote Server Unlock process due to the privacy reasons.
const char kRsuSalt[] = "Wu8oGt0uu0H8uSGxfo75uSDrGcRk2BXh";
// Returns a serialized representation of the unmodified handle. This is useful
// for predefined handle values, like TPM_RH_OWNER. For details on what types of
// handles use this name formula see Table 3 in the TPM 2.0 Library Spec Part 1
// (Section 16 - Names).
std::string NameFromHandle(trunks::TPM_HANDLE handle) {
std::string name;
trunks::Serialize_TPM_HANDLE(handle, &name);
return name;
}
std::string HashString(const std::string& plaintext,
trunks::TPM_ALG_ID hash_alg) {
switch (hash_alg) {
case trunks::TPM_ALG_SHA1:
return base::SHA1HashString(plaintext);
case trunks::TPM_ALG_SHA256:
return crypto::SHA256HashString(plaintext);
}
NOTREACHED();
return std::string();
}
} // namespace
namespace trunks {
TpmUtilityImpl::TpmUtilityImpl(const TrunksFactory& factory)
: factory_(factory),
vendor_id_(0) {
crypto::EnsureOpenSSLInit();
}
TpmUtilityImpl::~TpmUtilityImpl() {}
TPM_RC TpmUtilityImpl::Startup() {
TPM_RC result = TPM_RC_SUCCESS;
Tpm* tpm = factory_.GetTpm();
result = tpm->StartupSync(TPM_SU_CLEAR, nullptr);
// Ignore TPM_RC_INITIALIZE, that means it was already started.
if (result && result != TPM_RC_INITIALIZE) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
result = tpm->SelfTestSync(YES /* Full test. */, nullptr);
if (result) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::Clear() {
TPM_RC result = TPM_RC_SUCCESS;
std::unique_ptr<AuthorizationDelegate> password_delegate(
factory_.GetPasswordAuthorization(""));
result = factory_.GetTpm()->ClearSync(TPM_RH_PLATFORM,
NameFromHandle(TPM_RH_PLATFORM),
password_delegate.get());
// If there was an error in the initialization, platform auth is in a bad
// state.
if (result == TPM_RC_AUTH_MISSING) {
std::unique_ptr<AuthorizationDelegate> authorization(
factory_.GetPasswordAuthorization(kPlatformPassword));
result = factory_.GetTpm()->ClearSync(
TPM_RH_PLATFORM, NameFromHandle(TPM_RH_PLATFORM), authorization.get());
}
if (GetFormatOneError(result) == TPM_RC_BAD_AUTH) {
LOG(INFO) << __func__
<< ": Clear failed because of BAD_AUTH. This probably means "
<< "that the TPM was already initialized.";
return result;
}
if (result) {
LOG(ERROR) << __func__
<< ": Failed to clear the TPM: " << GetErrorString(result);
}
return result;
}
void TpmUtilityImpl::Shutdown() {
TPM_RC return_code = factory_.GetTpm()->ShutdownSync(TPM_SU_CLEAR, nullptr);
if (return_code && return_code != TPM_RC_INITIALIZE) {
// This should not happen, but if it does, there is nothing we can do.
LOG(ERROR) << __func__
<< ": Error shutting down: " << GetErrorString(return_code);
}
}
TPM_RC TpmUtilityImpl::TpmBasicInit(std::unique_ptr<TpmState>* tpm_state) {
TPM_RC result = TPM_RC_SUCCESS;
*tpm_state = factory_.GetTpmState();
result = (*tpm_state)->Initialize();
if (result) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
// Warn about various unexpected conditions.
if (!(*tpm_state)->WasShutdownOrderly()) {
LOG(WARNING) << __func__
<< ": WARNING: The last TPM shutdown was not orderly.";
}
if ((*tpm_state)->IsInLockout()) {
LOG(WARNING) << __func__ << ": WARNING: The TPM is currently in lockout.";
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::CheckState() {
TPM_RC result;
std::unique_ptr<TpmState> tpm_state;
result = TpmBasicInit(&tpm_state);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
if (tpm_state->IsPlatformHierarchyEnabled())
LOG(WARNING) << __func__ << ": Platform Hierarchy Enabled!";
if (!tpm_state->IsStorageHierarchyEnabled())
LOG(WARNING) << __func__ << ": Storage Hierarchy Disabled!";
if (!tpm_state->IsEndorsementHierarchyEnabled())
LOG(WARNING) << __func__ << ": Endorsement Hierarchy Disabled!";
LOG(INFO) << __func__ << ": TPM State verified.";
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::InitializeTpm() {
TPM_RC result;
std::unique_ptr<TpmState> tpm_state;
result = TpmBasicInit(&tpm_state);
if (result) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
// We expect the firmware has already locked down the platform hierarchy. If
// it hasn't, do it now.
if (tpm_state->IsPlatformHierarchyEnabled()) {
std::unique_ptr<AuthorizationDelegate> empty_password(
factory_.GetPasswordAuthorization(""));
result = SetHierarchyAuthorization(TPM_RH_PLATFORM, kPlatformPassword,
empty_password.get());
if (GetFormatOneError(result) == TPM_RC_BAD_AUTH) {
// Most likely the platform password has already been set.
result = TPM_RC_SUCCESS;
}
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
result = AllocatePCR(kPlatformPassword);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
std::unique_ptr<AuthorizationDelegate> authorization(
factory_.GetPasswordAuthorization(kPlatformPassword));
result = DisablePlatformHierarchy(authorization.get());
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::AllocatePCR(const std::string& platform_password) {
TPM_RC result;
TPMI_YES_NO more_data = YES;
TPMS_CAPABILITY_DATA capability_data;
result = factory_.GetTpm()->GetCapabilitySync(
TPM_CAP_PCRS, 0 /*property (not used)*/, 1 /*property_count*/, &more_data,
&capability_data, nullptr /*authorization_delegate*/);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__
<< ": Error querying PCRs: " << GetErrorString(result);
return result;
}
TPML_PCR_SELECTION& existing_pcrs = capability_data.data.assigned_pcr;
bool sha256_needed = true;
std::vector<TPMI_ALG_HASH> pcr_banks_to_remove;
for (uint32_t i = 0; i < existing_pcrs.count; ++i) {
if (existing_pcrs.pcr_selections[i].hash == TPM_ALG_SHA256) {
sha256_needed = false;
} else {
pcr_banks_to_remove.push_back(existing_pcrs.pcr_selections[i].hash);
}
}
if (!sha256_needed && pcr_banks_to_remove.empty()) {
return TPM_RC_SUCCESS;
}
TPML_PCR_SELECTION pcr_allocation;
memset(&pcr_allocation, 0, sizeof(pcr_allocation));
if (sha256_needed) {
pcr_allocation.pcr_selections[pcr_allocation.count].hash = TPM_ALG_SHA256;
pcr_allocation.pcr_selections[pcr_allocation.count].sizeof_select =
PCR_SELECT_MIN;
for (int i = 0; i < PCR_SELECT_MIN; ++i) {
pcr_allocation.pcr_selections[pcr_allocation.count].pcr_select[i] = 0xff;
}
++pcr_allocation.count;
}
for (auto pcr_type : pcr_banks_to_remove) {
pcr_allocation.pcr_selections[pcr_allocation.count].hash = pcr_type;
pcr_allocation.pcr_selections[pcr_allocation.count].sizeof_select =
PCR_SELECT_MAX;
++pcr_allocation.count;
}
std::unique_ptr<AuthorizationDelegate> platform_delegate(
factory_.GetPasswordAuthorization(platform_password));
TPMI_YES_NO allocation_success;
uint32_t max_pcr;
uint32_t size_needed;
uint32_t size_available;
result = factory_.GetTpm()->PCR_AllocateSync(
TPM_RH_PLATFORM, NameFromHandle(TPM_RH_PLATFORM), pcr_allocation,
&allocation_success, &max_pcr, &size_needed, &size_available,
platform_delegate.get());
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__
<< ": Error allocating PCRs: " << GetErrorString(result);
return result;
}
if (allocation_success != YES) {
LOG(ERROR) << __func__ << ": PCR allocation unsuccessful.";
return TPM_RC_FAILURE;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::PrepareForOwnership() {
std::unique_ptr<TpmState> tpm_state(factory_.GetTpmState());
TPM_RC result = tpm_state->Initialize();
if (result) {
LOG(ERROR) << __func__ << ": Error initializing state: "
<< GetErrorString(result);
return result;
}
if (tpm_state->IsOwnerPasswordSet()) {
VLOG(1) << __func__ << ": Nothing to do. Owner password is already set.";
return TPM_RC_SUCCESS;
}
result = CreateStorageAndSaltingKeys();
LOG_IF(INFO, result == TPM_RC_SUCCESS) << __func__ << ": done.";
return result;
}
TPM_RC TpmUtilityImpl::CreateStorageAndSaltingKeys() {
// First we set the storage hierarchy authorization to the well know default
// password.
TPM_RC result = SetKnownOwnerPassword(kWellKnownPassword);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error injecting known password: "
<< GetErrorString(result);
return result;
}
result = CreateStorageRootKeys(kWellKnownPassword);
if (result) {
LOG(ERROR) << __func__
<< ": Error creating SRKs: " << GetErrorString(result);
return result;
}
result = CreateSaltingKey(kWellKnownPassword);
if (result) {
LOG(ERROR) << __func__
<< ": Error creating salting key: " << GetErrorString(result);
return result;
}
return result;
}
TPM_RC TpmUtilityImpl::TakeOwnership(const std::string& owner_password,
const std::string& endorsement_password,
const std::string& lockout_password) {
TPM_RC result = CreateStorageAndSaltingKeys();
if (result != TPM_RC_SUCCESS) {
return result;
}
std::unique_ptr<HmacSession> session = factory_.GetHmacSession();
result = session->StartUnboundSession(true, true);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error initializing AuthorizationSession: "
<< GetErrorString(result);
return result;
}
std::unique_ptr<TpmState> tpm_state(factory_.GetTpmState());
result = tpm_state->Initialize();
session->SetEntityAuthorizationValue("");
if (!tpm_state->IsEndorsementPasswordSet()) {
session->SetFutureAuthorizationValue(endorsement_password);
result = SetHierarchyAuthorization(TPM_RH_ENDORSEMENT, endorsement_password,
session->GetDelegate());
if (result) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
}
if (!tpm_state->IsLockoutPasswordSet()) {
session->SetFutureAuthorizationValue(lockout_password);
result = SetHierarchyAuthorization(TPM_RH_LOCKOUT, lockout_password,
session->GetDelegate());
if (result) {
LOG(ERROR) << __func__ << ": " << GetErrorString(result);
return result;
}
}
// We take ownership of owner hierarchy last.
session->SetEntityAuthorizationValue(kWellKnownPassword);
session->SetFutureAuthorizationValue(owner_password);
result = SetHierarchyAuthorization(TPM_RH_OWNER, owner_password,
session->GetDelegate());
if ((GetFormatOneError(result) == TPM_RC_BAD_AUTH) &&
tpm_state->IsOwnerPasswordSet()) {
LOG(WARNING) << __func__
<< ": Error changing owner password. This probably because "
<< "ownership is already taken.";
return TPM_RC_SUCCESS;
} else if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error changing owner authorization: "
<< GetErrorString(result);
return result;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::StirRandom(const std::string& entropy_data,
AuthorizationDelegate* delegate) {
std::string digest = crypto::SHA256HashString(entropy_data);
TPM2B_SENSITIVE_DATA random_bytes = Make_TPM2B_SENSITIVE_DATA(digest);
return factory_.GetTpm()->StirRandomSync(random_bytes, delegate);
}
TPM_RC TpmUtilityImpl::GenerateRandom(size_t num_bytes,
AuthorizationDelegate* delegate,
std::string* random_data) {
CHECK(random_data);
size_t bytes_left = num_bytes;
random_data->clear();
TPM_RC rc;
TPM2B_DIGEST digest;
while (bytes_left > 0) {
rc = factory_.GetTpm()->GetRandomSync(bytes_left, &digest, delegate);
if (rc) {
LOG(ERROR) << __func__ << ": Error getting random data from tpm.";
return rc;
}
random_data->append(StringFrom_TPM2B_DIGEST(digest));
bytes_left -= digest.size;
}
CHECK_EQ(random_data->size(), num_bytes);
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::ExtendPCR(int pcr_index,
const std::string& extend_data,
AuthorizationDelegate* delegate) {
if (pcr_index < 0 || pcr_index >= IMPLEMENTATION_PCR) {
LOG(ERROR) << __func__ << ": Using a PCR index that isn't implemented.";
return TPM_RC_FAILURE;
}
TPM_HANDLE pcr_handle = HR_PCR + pcr_index;
std::string pcr_name = NameFromHandle(pcr_handle);
TPML_DIGEST_VALUES digests;
digests.count = 1;
digests.digests[0].hash_alg = TPM_ALG_SHA256;
crypto::SHA256HashString(extend_data, digests.digests[0].digest.sha256,
crypto::kSHA256Length);
std::unique_ptr<AuthorizationDelegate> empty_password_delegate =
factory_.GetPasswordAuthorization("");
if (!delegate) {
delegate = empty_password_delegate.get();
}
return factory_.GetTpm()->PCR_ExtendSync(pcr_handle, pcr_name, digests,
delegate);
}
TPM_RC TpmUtilityImpl::ReadPCR(int pcr_index, std::string* pcr_value) {
TPML_PCR_SELECTION pcr_select_in;
uint32_t pcr_update_counter;
TPML_PCR_SELECTION pcr_select_out;
TPML_DIGEST pcr_values;
// This process of selecting pcrs is highlighted in TPM 2.0 Library Spec
// Part 2 (Section 10.5 - PCR structures).
uint8_t pcr_select_index = pcr_index / 8;
uint8_t pcr_select_byte = 1 << (pcr_index % 8);
memset(&pcr_select_in, 0, sizeof(pcr_select_in));
pcr_select_in.count = 1;
pcr_select_in.pcr_selections[0].hash = TPM_ALG_SHA256;
pcr_select_in.pcr_selections[0].sizeof_select = PCR_SELECT_MIN;
pcr_select_in.pcr_selections[0].pcr_select[pcr_select_index] =
pcr_select_byte;
TPM_RC rc =
factory_.GetTpm()->PCR_ReadSync(pcr_select_in, &pcr_update_counter,
&pcr_select_out, &pcr_values, nullptr);
if (rc) {
LOG(INFO) << __func__
<< ": Error trying to read a pcr: " << GetErrorString(rc);
return rc;
}
if (pcr_select_out.count != 1 ||
pcr_select_out.pcr_selections[0].sizeof_select < (pcr_select_index + 1) ||
pcr_select_out.pcr_selections[0].pcr_select[pcr_select_index] !=
pcr_select_byte) {
LOG(ERROR) << __func__ << ": TPM did not return the requested PCR";
return TPM_RC_FAILURE;
}
CHECK_GE(pcr_values.count, 1U);
pcr_value->assign(StringFrom_TPM2B_DIGEST(pcr_values.digests[0]));
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::AsymmetricEncrypt(TPM_HANDLE key_handle,
TPM_ALG_ID scheme,
TPM_ALG_ID hash_alg,
const std::string& plaintext,
AuthorizationDelegate* delegate,
std::string* ciphertext) {
TPMT_RSA_DECRYPT in_scheme;
if (hash_alg == TPM_ALG_NULL) {
hash_alg = TPM_ALG_SHA256;
}
if (scheme == TPM_ALG_RSAES) {
in_scheme.scheme = TPM_ALG_RSAES;
} else if (scheme == TPM_ALG_OAEP || scheme == TPM_ALG_NULL) {
in_scheme.scheme = TPM_ALG_OAEP;
in_scheme.details.oaep.hash_alg = hash_alg;
} else {
LOG(ERROR) << __func__ << ": Invalid encryption scheme used.";
return SAPI_RC_BAD_PARAMETER;
}
TPMT_PUBLIC public_area;
TPM_RC result = GetKeyPublicArea(key_handle, &public_area);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error finding public area for: " << key_handle;
return result;
} else if (public_area.type != TPM_ALG_RSA) {
LOG(ERROR) << __func__ << ": Key handle given is not an RSA key";
return SAPI_RC_BAD_PARAMETER;
} else if ((public_area.object_attributes & kDecrypt) == 0) {
LOG(ERROR) << __func__ << ": Key handle given is not a decryption key";
return SAPI_RC_BAD_PARAMETER;
}
if ((public_area.object_attributes & kRestricted) != 0) {
LOG(ERROR) << __func__
<< ": Cannot use RSAES for encryption with a restricted key";
return SAPI_RC_BAD_PARAMETER;
}
std::string key_name;
result = ComputeKeyName(public_area, &key_name);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error computing key name for: " << key_handle;
return result;
}
TPM2B_DATA label;
label.size = 0;
TPM2B_PUBLIC_KEY_RSA in_message = Make_TPM2B_PUBLIC_KEY_RSA(plaintext);
TPM2B_PUBLIC_KEY_RSA out_message;
result = factory_.GetTpm()->RSA_EncryptSync(key_handle, key_name, in_message,
in_scheme, label, &out_message,
delegate);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__
<< ": Error performing RSA encrypt: " << GetErrorString(result);
return result;
}
ciphertext->assign(StringFrom_TPM2B_PUBLIC_KEY_RSA(out_message));
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::AsymmetricDecrypt(TPM_HANDLE key_handle,
TPM_ALG_ID scheme,
TPM_ALG_ID hash_alg,
const std::string& ciphertext,
AuthorizationDelegate* delegate,
std::string* plaintext) {
TPMT_RSA_DECRYPT in_scheme;
if (scheme == TPM_ALG_RSAES || scheme == TPM_ALG_NULL) {
in_scheme.scheme = scheme;
} else if (scheme == TPM_ALG_OAEP) {
in_scheme.scheme = TPM_ALG_OAEP;
if (hash_alg == TPM_ALG_NULL) {
hash_alg = TPM_ALG_SHA256;
}
in_scheme.details.oaep.hash_alg = hash_alg;
} else {
LOG(ERROR) << __func__ << ": Invalid decryption scheme used.";
return SAPI_RC_BAD_PARAMETER;
}
TPM_RC result;
if (delegate == nullptr) {
result = SAPI_RC_INVALID_SESSIONS;
LOG(ERROR) << __func__
<< ": This method needs a valid authorization delegate: "
<< GetErrorString(result);
return result;
}
TPMT_PUBLIC public_area;
result = GetKeyPublicArea(key_handle, &public_area);
if (result) {
LOG(ERROR) << __func__ << ": Error finding public area for: " << key_handle;
return result;
} else if (public_area.type != TPM_ALG_RSA) {
LOG(ERROR) << __func__ << ": Key handle given is not an RSA key";
return SAPI_RC_BAD_PARAMETER;
} else if ((public_area.object_attributes & kDecrypt) == 0) {
LOG(ERROR) << __func__ << ": Key handle given is not a decryption key";
return SAPI_RC_BAD_PARAMETER;
}
if ((public_area.object_attributes & kRestricted) != 0) {
LOG(ERROR) << __func__
<< ": Cannot use RSAES for encryption with a restricted key";
return SAPI_RC_BAD_PARAMETER;
}
std::string key_name;
result = ComputeKeyName(public_area, &key_name);
if (result) {
LOG(ERROR) << __func__ << ": Error computing key name for: " << key_handle;
return result;
}
TPM2B_DATA label;
label.size = 0;
TPM2B_PUBLIC_KEY_RSA in_message = Make_TPM2B_PUBLIC_KEY_RSA(ciphertext);
TPM2B_PUBLIC_KEY_RSA out_message;
result = factory_.GetTpm()->RSA_DecryptSync(key_handle, key_name, in_message,
in_scheme, label, &out_message,
delegate);
if (result) {
LOG(ERROR) << __func__
<< ": Error performing RSA decrypt: " << GetErrorString(result);
return result;
}
plaintext->assign(StringFrom_TPM2B_PUBLIC_KEY_RSA(out_message));
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::RawSign(TPM_HANDLE key_handle,
TPM_ALG_ID scheme,
TPM_ALG_ID hash_alg,
const std::string& plaintext,
bool generate_hash,
AuthorizationDelegate* delegate,
TPMT_SIGNATURE* auth) {
TPM_RC result;
if (delegate == nullptr) {
result = SAPI_RC_INVALID_SESSIONS;
LOG(ERROR) << __func__
<< ": This method needs a valid authorization delegate: "
<< GetErrorString(result);
return result;
}
// Get public information of the key handle
TPMT_PUBLIC public_area;
result = GetKeyPublicArea(key_handle, &public_area);
if (result) {
LOG(ERROR) << __func__ << ": Error finding public area for: " << key_handle;
return result;
} else if (public_area.type != TPM_ALG_RSA &&
public_area.type != TPM_ALG_ECC) {
LOG(ERROR) << __func__
<< ": Key handle given is not a supported key (RSA, ECC)";
return SAPI_RC_BAD_PARAMETER;
} else if ((public_area.object_attributes & kSign) == 0) {
LOG(ERROR) << __func__ << ": Key handle given is not a signging key";
return SAPI_RC_BAD_PARAMETER;
} else if ((public_area.object_attributes & kRestricted) != 0) {
LOG(ERROR) << __func__ << ": Key handle references a restricted key";
return SAPI_RC_BAD_PARAMETER;
}
// Default scheme is TPM_ALG_RSASSA
if (scheme == TPM_ALG_NULL) {
scheme = TPM_ALG_RSASSA;
}
// Default hash algorithm is SHA256, except TPM_ALG_RSASSA
// For RSASSA, we allow TPM_ALG_NULL since TPMs can support padding-only
// scheme for RSASSA which is indicated by passing TPM_ALG_NULL as a hashing
// algorithm to TPM2_Sign.
if (scheme != TPM_ALG_RSASSA && hash_alg == TPM_ALG_NULL) {
hash_alg = TPM_ALG_SHA256;
}
// Check key type and scheme.
std::function<std::string(const TPMT_SIGNATURE&)> unpack_helper;
if (public_area.type == TPM_ALG_RSA) {
if (scheme != TPM_ALG_RSAPSS && scheme != TPM_ALG_RSASSA) {
LOG(ERROR) << __func__ << ": Invalid signing scheme used for RSA key.";
return SAPI_RC_BAD_PARAMETER;
}
} else if (public_area.type == TPM_ALG_ECC) {
if (scheme != TPM_ALG_ECDSA) {
LOG(ERROR) << __func__ << ": Invalid signing scheme used for ECC key.";
return SAPI_RC_BAD_PARAMETER;
}
}
// Fill the checked parameters
TPMT_SIG_SCHEME in_scheme;
in_scheme.scheme = scheme;
in_scheme.details.any.hash_alg = hash_alg;
// Compute key name
std::string key_name;
result = ComputeKeyName(public_area, &key_name);
if (result) {
LOG(ERROR) << __func__ << ": Error computing key name for: " << key_handle;
return result;
}
// Call TPM
std::string digest =
generate_hash ? HashString(plaintext, hash_alg) : plaintext;
if (digest.size() > sizeof(TPMU_HA)) {
LOG(ERROR)
<< __func__
<< ": digest is too long for TPM signing command. Input length: "
<< digest.size() << ", the limit: " << sizeof(TPMU_HA);
return SAPI_RC_BAD_PARAMETER;
}
TPM2B_DIGEST tpm_digest = Make_TPM2B_DIGEST(digest);
TPMT_TK_HASHCHECK validation;
validation.tag = TPM_ST_HASHCHECK;
validation.hierarchy = TPM_RH_NULL;
validation.digest.size = 0;
result = factory_.GetTpm()->SignSync(key_handle, key_name, tpm_digest,
in_scheme, validation, auth, delegate);
if (result) {
LOG(ERROR) << __func__
<< ": Error signing digest: " << GetErrorString(result);
return result;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::Sign(TPM_HANDLE key_handle,
TPM_ALG_ID scheme,
TPM_ALG_ID hash_alg,
const std::string& plaintext,
bool generate_hash,
AuthorizationDelegate* delegate,
std::string* signature) {
TPM_RC result;
TPMT_SIGNATURE signature_out;
// Default scheme is TPM_ALG_RSASSA
if (scheme == TPM_ALG_NULL)
scheme = TPM_ALG_RSASSA;
result = RawSign(key_handle, scheme, hash_alg, plaintext, generate_hash,
delegate, &signature_out);
if (result) {
LOG(ERROR) << __func__
<< ": Error from RawSign(): " << GetErrorString(result);
return result;
}
// Simply check scheme and parse the output from TPM.
switch (scheme) {
case TPM_ALG_RSAPSS:
*signature =
StringFrom_TPM2B_PUBLIC_KEY_RSA(signature_out.signature.rsapss.sig);
break;
case TPM_ALG_RSASSA:
*signature =
StringFrom_TPM2B_PUBLIC_KEY_RSA(signature_out.signature.rsassa.sig);
break;
case TPM_ALG_ECDSA:
Serialize_TPMT_SIGNATURE(signature_out, signature);
break;
default:
LOG(ERROR) << __func__ << ": Invalid signing scheme used for the key.";
return SAPI_RC_BAD_PARAMETER;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::CertifyCreation(TPM_HANDLE key_handle,
const std::string& creation_blob) {
TPM2B_CREATION_DATA creation_data;
TPM2B_DIGEST creation_hash;
TPMT_TK_CREATION creation_ticket;
if (!factory_.GetBlobParser()->ParseCreationBlob(
creation_blob, &creation_data, &creation_hash, &creation_ticket)) {
LOG(ERROR) << __func__ << ": Error parsing CreationBlob.";
return SAPI_RC_BAD_PARAMETER;
}
TPM2B_DATA qualifying_data;
qualifying_data.size = 0;
TPMT_SIG_SCHEME in_scheme;
in_scheme.scheme = TPM_ALG_NULL;
TPM2B_ATTEST certify_info;
TPMT_SIGNATURE signature;
std::unique_ptr<AuthorizationDelegate> delegate =
factory_.GetPasswordAuthorization("");
TPM_RC result = factory_.GetTpm()->CertifyCreationSync(
TPM_RH_NULL, "", key_handle, "", qualifying_data, creation_hash,
in_scheme, creation_ticket, &certify_info, &signature, delegate.get());
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__
<< ": Error certifying key creation: " << GetErrorString(result);
return result;
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::ChangeKeyAuthorizationData(
TPM_HANDLE key_handle,
const std::string& new_password,
AuthorizationDelegate* delegate,
std::string* key_blob) {
TPM_RC result;
if (delegate == nullptr) {
result = SAPI_RC_INVALID_SESSIONS;
LOG(ERROR) << __func__
<< ": This method needs a valid authorization delegate: "
<< GetErrorString(result);
return result;
}
std::string key_name;
std::string parent_name;
result = GetKeyName(key_handle, &key_name);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error getting Key name for key_handle: "
<< GetErrorString(result);
return result;
}
result = GetKeyName(kStorageRootKey, &parent_name);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error getting Key name for RSA-SRK: "
<< GetErrorString(result);
return result;
}
TPM2B_AUTH new_auth = Make_TPM2B_DIGEST(new_password);
TPM2B_PRIVATE new_private_data;
new_private_data.size = 0;
result = factory_.GetTpm()->ObjectChangeAuthSync(
key_handle, key_name, kStorageRootKey, parent_name, new_auth,
&new_private_data, delegate);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error changing object authorization data: "
<< GetErrorString(result);
return result;
}
if (key_blob) {
TPMT_PUBLIC public_data;
result = GetKeyPublicArea(key_handle, &public_data);
if (result != TPM_RC_SUCCESS) {
return result;
}
if (!factory_.GetBlobParser()->SerializeKeyBlob(
Make_TPM2B_PUBLIC(public_data), new_private_data, key_blob)) {
return SAPI_RC_BAD_TCTI_STRUCTURE;
}
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::ImportRSAKey(AsymmetricKeyUsage key_type,
const std::string& modulus,
uint32_t public_exponent,
const std::string& prime_factor,
const std::string& password,
AuthorizationDelegate* delegate,
std::string* key_blob) {
TPMT_PUBLIC public_area = CreateDefaultPublicArea(TPM_ALG_RSA);
public_area.parameters.rsa_detail.key_bits = modulus.size() * 8;
public_area.parameters.rsa_detail.exponent = public_exponent;
public_area.unique.rsa = Make_TPM2B_PUBLIC_KEY_RSA(modulus);
TPMT_SENSITIVE in_sensitive;
in_sensitive.sensitive_type = TPM_ALG_RSA;
in_sensitive.sensitive.rsa = Make_TPM2B_PRIVATE_KEY_RSA(prime_factor);
return ImportKeyInner(key_type, public_area, in_sensitive, password, delegate,
key_blob);
}
TPM_RC TpmUtilityImpl::ImportECCKey(AsymmetricKeyUsage key_type,
TPMI_ECC_CURVE curve_id,
const std::string& public_point_x,
const std::string& public_point_y,
const std::string& private_value,
const std::string& password,
AuthorizationDelegate* delegate,
std::string* key_blob) {
TPMT_PUBLIC public_area = CreateDefaultPublicArea(TPM_ALG_ECC);
public_area.parameters.ecc_detail.curve_id = curve_id;
public_area.unique.ecc.x = Make_TPM2B_ECC_PARAMETER(public_point_x);
public_area.unique.ecc.y = Make_TPM2B_ECC_PARAMETER(public_point_y);
TPMT_SENSITIVE in_sensitive;
in_sensitive.sensitive_type = TPM_ALG_ECC;
in_sensitive.sensitive.ecc = Make_TPM2B_ECC_PARAMETER(private_value);
return ImportKeyInner(key_type, public_area, in_sensitive, password, delegate,
key_blob);
}
TPM_RC TpmUtilityImpl::ImportKeyInner(AsymmetricKeyUsage key_type,
TPMT_PUBLIC public_area,
TPMT_SENSITIVE in_sensitive,
const std::string& password,
AuthorizationDelegate* delegate,
std::string* key_blob) {
TPM_RC result;
if (delegate == nullptr) {
result = SAPI_RC_INVALID_SESSIONS;
LOG(ERROR) << __func__
<< ": This method needs a valid authorization delegate: "
<< GetErrorString(result);
return result;
}
std::string parent_name;
result = GetKeyName(kStorageRootKey, &parent_name);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error getting Key name for SRK: "
<< GetErrorString(result);
return result;
}
public_area.object_attributes = kUserWithAuth | kNoDA;
switch (key_type) {
case AsymmetricKeyUsage::kDecryptKey:
public_area.object_attributes |= kDecrypt;
break;
case AsymmetricKeyUsage::kSignKey:
public_area.object_attributes |= kSign;
break;
case AsymmetricKeyUsage::kDecryptAndSignKey:
public_area.object_attributes |= (kSign | kDecrypt);
break;
}
TPM2B_ENCRYPTED_SECRET in_sym_seed = Make_TPM2B_ENCRYPTED_SECRET("");
TPMT_SYM_DEF_OBJECT symmetric_alg;
symmetric_alg.algorithm = TPM_ALG_AES;
symmetric_alg.key_bits.aes = kAesKeySize * 8;
symmetric_alg.mode.aes = TPM_ALG_CFB;
in_sensitive.auth_value = Make_TPM2B_DIGEST(password);
in_sensitive.seed_value = Make_TPM2B_DIGEST("");
TPM2B_PUBLIC public_data = Make_TPM2B_PUBLIC(public_area);
TPM2B_DATA encryption_key;
encryption_key.size = kAesKeySize;
CHECK_EQ(RAND_bytes(encryption_key.buffer, encryption_key.size), 1)
<< "Error generating a cryptographically random AES Key.";
TPM2B_PRIVATE private_data;
result = EncryptPrivateData(in_sensitive, public_area, &private_data,
&encryption_key);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__ << ": Error creating encrypted private struct: "
<< GetErrorString(result);
return result;
}
TPM2B_PRIVATE tpm_private_data;
tpm_private_data.size = 0;
result = factory_.GetTpm()->ImportSync(
kStorageRootKey, parent_name, encryption_key, public_data, private_data,
in_sym_seed, symmetric_alg, &tpm_private_data, delegate);
if (result != TPM_RC_SUCCESS) {
LOG(ERROR) << __func__
<< ": Error importing key: " << GetErrorString(result);
return result;
}
if (key_blob) {
if (!factory_.GetBlobParser()->SerializeKeyBlob(
public_data, tpm_private_data, key_blob)) {
return SAPI_RC_BAD_TCTI_STRUCTURE;
}
}
return TPM_RC_SUCCESS;
}
TPM_RC TpmUtilityImpl::CreateRSAKeyPair(
AsymmetricKeyUsage key_type,
int modulus_bits,
uint32_t public_exponent,
const std::string& password,
const std::string& policy_digest,
bool use_only_policy_authorization,
const std::vector<uint32_t>& creation_pcr_indexes,
AuthorizationDelegate* delegate,
std::string* key_blob,
std::string* creation_blob) {
TPMT_PUBLIC public_area = CreateDefaultPublicArea(TPM_ALG_RSA);
public_area.parameters.rsa_detail.key_bits = modulus_bits;
public_area.parameters.rsa_detail.exponent = public_exponent;
return CreateKeyPairInner(key_type, public_area, password, policy_digest,
use_only_policy_authorization, creation_pcr_indexes,
delegate, key_blob, creation_blob);
}
TPM_RC TpmUtilityImpl::CreateECCKeyPair(
AsymmetricKeyUsage key_type,
TPMI_ECC_CURVE curve_id,
const std::string& password,
const std::string& policy_digest,
bool use_only_policy_authorization,
const std::vector<uint32_t>& creation_pcr_indexes,
AuthorizationDelegate* delegate,
std::string* key_blob,
std::string* creation_blob) {
TPMT_PUBLIC public_area = CreateDefaultPublicArea(TPM_ALG_ECC);
public_area.parameters.ecc_detail.curve_id = curve_id;
return CreateKeyPairInner(key_type, public_area, password, policy_digest,
use_only_policy_authorization, creation_pcr_indexes,
delegate, key_blob, creation_blob);
}