-
Notifications
You must be signed in to change notification settings - Fork 161
/
TestSubstrate.cs
1578 lines (1378 loc) · 63.4 KB
/
TestSubstrate.cs
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) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See the LICENSE file in the project root for full license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using Tpm2Lib;
/*
* This file contains support data and routines for the test cases
*/
namespace Tpm2Tester
{
public class TestState
{
public static readonly int NullPhase = 0;
// Initially this field is NullPhase. The test accepting TestState parameter
// (passed as the third by-ref argument) may set this field if it wants the
// framework to restart it in case of failure.
// If this field remains set to the same value after the restarted test failed,
// the framework won't restart the test again.
public int TestPhase;
// The value of the '-params' option. An arbitrary string w/o spaces passed
// to a single test specified with '-tests' option.
// Alternatively the test may set this field when it requests restart (by setting
// the TestPhase member).
// The string is reset upon each test completion (i.e. if no restart is requested).
public string TestParams;
internal TestState(string testParams = null)
{
TestPhase = NullPhase;
TestParams = testParams;
}
}; // class TestState
// Represents Tpm2Tester execution environment for the
public class TestSubstrate
{
//
public TestConfig TestCfg;
public TpmConfig TpmCfg;
internal TestFramework Framework;
public class TpmCommandCaller
{
Tpm2 tpm;
public TpmCommandCaller(Tpm2 _tpm)
{
tpm = _tpm;
}
public void PcrEvent(uint pcr)
{
tpm.PcrEvent(TpmHandle.Pcr(pcr), Globs.GetRandomBytes(Globs.GetRandomInt(1024)));
}
public void Clear()
{
tpm.Clear(TpmRh.Platform);
}
public void ChangePPS()
{
tpm.ChangePPS(TpmRh.Platform);
}
public void ChangeEPS()
{
tpm.ChangeEPS(TpmRh.Platform);
}
} // class TpmCommandCaller
private TestSubstrate()
{
TestCfg = new TestConfig();
TpmCfg = new TpmConfig();
}
/// <summary>Create a test substrate instance with the test methods from the specified
/// containing object and given comamnd line options for the test session.</summary>
/// <param name="testContainer">A reference to an object in the client assembly that
/// implements test methods (the ones with the Tpm2Tester.Test attribute). Such
/// methods are automatically enumerated, and then filtered and executed based
/// on the command line options.</param>
public static TestSubstrate Create(string[] args, object testContainer)
{
var substrate = new TestSubstrate();
substrate.Framework = TestFramework.Create(substrate, args, testContainer);
return substrate.Framework != null ? substrate : null;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool RunTestSession()
{
return Framework.RunTestSession();
}
public void WriteToLog(string msgFormat, params object[] msgParams)
{
Framework.WriteToLog(msgFormat, msgParams);
}
public void WriteErrorToLog(string msgFormat, params object[] msgParams)
{
Framework.WriteErrorToLog(msgFormat, msgParams);
}
public void SimpleFuzzer(byte[] x)
{
Framework.SimpleFuzzer(x);
}
public void DisableKeyCache(Tpm2 tpm)
{
if (TestCfg.UseKeyCache)
tpm._GetUnderlyingDevice().SignalKeyCacheOff();
}
public void ReactivateKeyCache(Tpm2 tpm)
{
if (TestCfg.UseKeyCache)
tpm._GetUnderlyingDevice().SignalKeyCacheOn();
}
public void SimpleInterferenceCallback(Tpm2 tpm, TpmCc nextCmd)
{
tpm.GetRandom(16);
}
int retryCount = 0;
public void SimulateConcurrentInterference(Tpm2 tpm, Tpm2.InjectCmdCallback cb)
{
tpm._SetInjectCmdCallback(cb);
retryCount = 0;
}
public void SimulateConcurrentInterference(Tpm2 tpm)
{
SimulateConcurrentInterference(tpm, SimpleInterferenceCallback);
}
// returns true if the test should repeat the failed audited command sequence
public bool RetryAfterConcurrentTpmCommandInterference(Tpm2 tpm)
{
bool simulated = tpm._GetInjectCmdCallback() != null;
tpm._SetInjectCmdCallback(null);
if (++retryCount > TestConfig.MaxRetriesUponInterference)
{
WriteErrorToLog("Either TPM audit logic is faulty or a concurrent process " +
"keeps interposing its TPM commands. Aborting the test...");
return false;
}
// If the the first intervention was simulated, no random pause is necessary
if (retryCount > (simulated ? 1 : 0))
{
int pause = 3000 + RandomInt(7000);
WriteErrorToLog("Possible interference by a concurrent process detected. " +
"Retrying the test after {0} ms...", pause, System.ConsoleColor.Cyan);
// Sleep for a while to decrease the probability of being intervened
// again by continued concurrent TPM activity
Thread.Sleep(pause);
}
return true;
}
public void AssertConcurrentTpmCommandInterferenceDetected(TestContext testCtx)
{
testCtx.Assert("Interposed.Cmds.Detection", retryCount > 0);
}
// Production TPM 1.16 in normal (non-bleeding) mode
public bool ProdTpm_116()
{
return !TpmCfg.RefactoredTpm() && !TestCfg.Bleeding;
}
internal void Assert(bool cond)
{
if (Framework.MainTestContext.ReportErrors && !Framework.FuzzMode)
Debug.Assert(cond);
}
// Returns the number of persistent keys allocated by the Tpm2Tester's infra
public int NumPersistentKeys()
{
return (PersRsaPrimOwner == null ? 0 : 1) +
(PersRsaPrimEndors == null ? 0 : 1) +
(PersRsaPrimPlatform == null ? 0 : 1);
}
internal void RecoveryResetTpm(Tpm2 tpm)
{
if (TpmCfg.PowerControl)
TpmHelper.PowerCycle(tpm, Su.Clear, Su.Clear);
}
private bool TpmStateTransition(Tpm2 tpm, Su shutdownMode, Su startupMode)
{
if (TpmCfg.PowerControl)
TpmHelper.PowerCycle(tpm, shutdownMode, startupMode);
return TpmCfg.PowerControl;
}
public bool ResetTpm(Tpm2 tpm)
{
return TpmStateTransition(tpm, Su.Clear, Su.Clear);
}
public bool RestartTpm(Tpm2 tpm)
{
return TpmStateTransition(tpm, Su.State, Su.Clear);
}
public bool ResumeTpm(Tpm2 tpm)
{
return TpmStateTransition(tpm, Su.State, Su.State);
}
public string ReseedRng()
{
string newSeed = TestCfg.RngSeed;
TestCfg.RngSeed = null;
byte[] newSeedBytes;
if (newSeed == null)
{
newSeedBytes = Globs.GetRandomBytes(8);
newSeed = Globs.HexFromByteArray(newSeedBytes);
}
else
{
newSeedBytes = Globs.ByteArrayFromHex(newSeed);
}
Globs.SetRngSeed(newSeed);
return newSeed;
}
public byte[] RandomBytes(int numBytes)
{
return Globs.GetRandomBytes(numBytes);
}
public byte[] RandBytes(int minBytes, int maxBytes)
{
if (maxBytes < minBytes)
return null;
return RandomBytes(RandomInt(maxBytes - minBytes) + minBytes);
}
public int RandomInt(int max)
{
return Globs.GetRandomInt(max);
}
// Generates a non-zero random number up to the max value and different from excludedSize.
public ushort RandomSize(int max, ushort excludedSize = 0)
{
if (max <= 0)
return 0;
ushort res = 0;
do {
res = (ushort)(Globs.GetRandomInt(max-1) + 1);
} while (res == excludedSize);
return res;
}
public TpmHandle RandomNvHandle(TpmHandle exclude = null)
{
TpmHandle h = null;
do
{
h = TpmHandle.NV(RandomInt(TestConfig.MaxNvIndex));
} while (exclude != null && h.handle == exclude.handle);
return h;
}
public byte[] RandomAuth(TpmAlgId associatedHash = TpmAlgId.None, int minSize = 1)
{
int maxSize = 0;
if (associatedHash == TpmAlgId.Null || associatedHash == TpmAlgId.None)
{
maxSize = TpmCfg.MaxDigestSize;
}
else
maxSize = TpmHash.DigestSize(associatedHash);
byte[] authVal = null;
Debug.Assert(minSize <= maxSize);
if (!TpmCfg.Tpm_115_Errata_13())
{
authVal = RandBytes(16, maxSize);
authVal[0] |= 0x80;
authVal[authVal.Length - 1] |= 0x80;
}
// Make sure that an auth value with trailing zeros is generated sometimes
else if (RandomInt(10) != 0)
{
authVal = RandBytes(minSize, maxSize);
}
else
{
int trailingZeros = RandomInt(maxSize - minSize);
authVal = Globs.Concatenate(RandBytes(minSize, maxSize - trailingZeros),
Globs.ByteArray(trailingZeros, 0));
}
if (Globs.IsZeroBuffer(authVal))
{
authVal[0] = (byte)(RandomInt(254) + 1);
}
return authVal;
}
public byte[] RandomNonce(TpmAlgId associatedHash = TpmAlgId.None)
{
return RandomAuth(associatedHash, 16);
}
public byte[] RandomBlob(TpmAlgId associatedAlg = TpmAlgId.None)
{
int maxSize = TestConfig.MaxSymData;
if (associatedAlg != TpmAlgId.None)
{
maxSize = CryptoLib.BlockSize(associatedAlg);
}
return RandBytes(1, maxSize);
}
public byte[] RandomDerivationLabel()
{
return RandBytes(0, TpmCfg.MaxLabelSize);
}
public byte[] RandomDerivationContext()
{
return RandomDerivationLabel();
}
public TpmDerive RandomTpmDerive()
{
return new TpmDerive(RandomDerivationLabel(), RandomDerivationContext());
}
public E Random<E>(IEnumerable<E> coll)
{
return coll.ElementAt(Globs.GetRandomInt(coll.Count()));
}
public E Random<E>(IEnumerable<E> coll, E valueIfEmpty)
{
return coll == null || coll.Count() == 0 ? valueIfEmpty : Random(coll);
}
public EccCurve RandomCurve(TpmAlgId scheme = TpmAlgId.Null, bool swCompat = false)
{
if (TpmCfg.EccCurves == null || TpmCfg.EccCurves.Count == 0)
{
return EccCurve.None;
}
return Random(TpmCfg.CurvesForScheme(scheme, swCompat));
}
public ushort RandomRsaKeySize (TpmAlgId nameAlg)
{
return TpmHash.DigestSize(nameAlg) < 0x30
? Random(TpmCfg.RsaKeySizes)
: Random(TpmCfg.RsaKeySizes.Where(size => size > 1536));
}
// Retuns a supported hash algorithm with the digest of the given size
public TpmAlgId RandomHashAlg(int digestSize)
{
if (digestSize == 0)
return Random(TpmCfg.HashAlgs);
var candidateAlgs = new List<TpmAlgId>();
for (int i = 0; i < TpmCfg.HashAlgs.Length; ++i)
{
if (TpmHash.DigestSize(TpmCfg.HashAlgs[i]) == digestSize)
{
candidateAlgs.Add(TpmCfg.HashAlgs[i]);
}
}
return Random(candidateAlgs, TpmAlgId.Null);
}
// Returns two hash algorithms of different size
public TpmAlgId[] TwoRandomHashAlgs(int digestSize = 0)
{
if (TpmCfg.HashAlgs.Length <= 2)
return TpmCfg.HashAlgs;
TpmAlgId hashAlg = RandomHashAlg(digestSize);
return new TpmAlgId[2] { hashAlg, AltHashAlg(hashAlg) };
}
public TpmAlgId[] RandomHashAlgs(int numAlgs)
{
if (TpmCfg.HashAlgs.Length <= numAlgs)
return TpmCfg.HashAlgs;
var hashAlgs = new TpmAlgId[numAlgs];
int selected = 0;
for (int i = 0;
selected < numAlgs && selected < TpmCfg.HashAlgs.Length - i;
++i )
{
if (Globs.GetRandomInt(TpmCfg.HashAlgs.Length) < numAlgs )
{
hashAlgs[selected++] = TpmCfg.HashAlgs[i];
}
}
while (selected < numAlgs)
{
hashAlgs[selected] = hashAlgs[TpmCfg.HashAlgs.Length - (numAlgs - selected)];
++selected;
}
return hashAlgs;
}
// Returns a hash algorithm with the digest size different from that of baseAlg.
// If all implemented hash algorithms besides baseAlg have the same digest size,
// returns one of them. If only one hash algorithms is implemented, returns it.
public TpmAlgId AltHashAlg(TpmAlgId baseAlg, bool onlyDiffSize = false)
{
ushort baseSize = TpmHash.DigestSize(baseAlg);
int numDiffs = 0;
TpmAlgId altAlg = baseAlg;
for (int i = 0; i < TpmCfg.HashAlgs.Length; ++i)
{
if (TpmCfg.HashAlgs[i] == baseAlg)
{
continue;
}
if (TpmHash.DigestSize(TpmCfg.HashAlgs[i]) == baseSize)
{
if (altAlg == baseAlg)
{
altAlg = TpmCfg.HashAlgs[i];
}
continue;
}
// Ensure equal probability of all of the suitable candidates selection.
// The first suitable candidate is selected unconditionally, as RandInt(0)
// always returns 0.
if (RandomInt(++numDiffs) == 0)
{
altAlg = TpmCfg.HashAlgs[i];
onlyDiffSize = false;
}
}
return onlyDiffSize ? TpmAlgId.Null : altAlg;
}
public static void
RandomApply(Action<uint /*index*/> f,
int numItemsToPick, int sequenceLength,
PcrSelection templateBank)
{
uint index = 0;
while (numItemsToPick > 0)
{
if (templateBank.IsPcrSelected(index))
{
if (Globs.GetRandomInt(sequenceLength) < numItemsToPick)
{
f(index);
--numItemsToPick;
}
--sequenceLength;
Debug.Assert(sequenceLength >= 0);
}
++index;
}
}
public void RandomizeSinglePcr(Tpm2 tpm, PcrSelection sel)
{
var selected = sel.GetSelectedPcrs();
Assert(selected.Length > 0);
tpm.PcrEvent(TpmHandle.Pcr(selected[RandomInt(selected.Length)]),
RandBytes(1, TpmCfg.MaxDigestSize));
}
public void RandomizePcrs(Tpm2 tpm, PcrSelection sel)
{
int maxPcrs = sel.NumPcrsSelected();
var caller = new TpmCommandCaller(tpm);
RandomApply(caller.PcrEvent, RandomInt(maxPcrs) + 1, maxPcrs, sel);
}
// Returns randomly selected non-empty PCR bank
public PcrSelection RandomPcrBank()
{
PcrSelection bank = TpmCfg.PcrBanks[RandomInt(TpmCfg.PcrBanks.Count)];
if (!CryptoLib.IsSupported(bank.hash))
{
// The TPM implements hash algorithms unsupported by Tpm2Tester
// Make sure that we find a supported one
foreach(var b in TpmCfg.PcrBanks)
{
if (CryptoLib.IsSupported(b.hash))
{
bank = b;
break;
}
}
}
return bank;
}
public int RandomPcr(TpmAlgId hashAlg)
{
return (int)Random(TpmCfg.PcrBank(hashAlg).GetSelectedPcrs());
}
// Generates a random subset of a non-empty PCR bank for the specified hashAlg
// or randomly selected one by default. The size of subset is either numPcrs,
// if specified, or randomly selected by default.
public PcrSelection RandomPcrSel(TpmAlgId hashAlg = TpmAlgId.None, int numPcrs = 0)
{
int maxPcrs = Math.Min((ushort)16, PcrSelection.MaxPcrs);
if (numPcrs == 0)
{
numPcrs = Globs.GetRandomInt(maxPcrs - 2) + 1;
}
Assert(numPcrs < maxPcrs - 1);
PcrSelection tpmBank = hashAlg != TpmAlgId.None ? TpmCfg.PcrBank(hashAlg)
: RandomPcrBank();
var sel = new PcrSelection(tpmBank.hash);
RandomApply(sel.SelectPcr, numPcrs, maxPcrs, tpmBank);
return sel;
}
public PcrSelection[] RandomSinglePcrSelArr()
{
return new PcrSelection[] { RandomPcrSel(TpmAlgId.None, 1) };
}
public EccPoint RandomEccPoint(Tpm2 tpm, EccCurve curveID)
{
int ptSize = tpm.EccParameters(curveID).gX.Length;
return new EccPoint(RandomBytes(ptSize), RandomBytes(ptSize));
}
// Generates a random unique value for a key with the given template
public IPublicIdUnion RandomUnique(Tpm2 tpm, TpmPublic pub)
{
IPublicIdUnion unique = null;
switch (pub.type)
{
case TpmAlgId.Rsa:
unique = new Tpm2bPublicKeyRsa(
RandomBytes(((pub.parameters as RsaParms).keyBits + 7) / 8));
break;
case TpmAlgId.Ecc:
unique = RandomEccPoint(tpm, (pub.parameters as EccParms).curveID);
break;
case TpmAlgId.Symcipher:
unique = new Tpm2bDigestSymcipher(TpmHash.FromRandom(pub.nameAlg));
break;
case TpmAlgId.Keyedhash:
unique = new Tpm2bDigestKeyedhash(TpmHash.FromRandom(pub.nameAlg));
break;
}
return unique;
}
public void ForAllInvalidHandles(Tpm2 tpm, Action<TpmHandle, bool /*freshlyFlushed*/> action)
{
if (!TestCfg.StressMode && !TestCfg.HasTRM)
{
TpmHandle h = CreateDataObject(tpm);
tpm.FlushContext(h);
action(h, true);
}
var handleTypes = new Ht[] { Ht.Transient, Ht.Persistent, Ht.Permanent,
Ht.NvIndex, Ht.Pcr, (Ht)0x88};
foreach (var handleType in handleTypes)
{
TpmHandle h = RandomInvalidHandle(tpm, handleType);
action(h, false);
}
}
public void ExpectBadHandleError(Tpm2 tpm, TpmHandle h)
{
if (TestCfg.StressMode)
tpm._ExpectResponses(TpmRc.Handle, TpmRc.Value);
else if (Globs.IsOneOf(h.GetType(), Ht.Persistent, Ht.NvIndex) ||
// TBS intercepts out of range transient handles and returns RC_HANDLE,
// even though the correct reply is RC_VALUE.
(TestCfg.HasTRM && h.GetType() == Ht.Transient))
tpm._ExpectError(TpmRc.Handle);
else
tpm._ExpectError(TpmRc.Value);
}
public void ExpectBadNvHandleError(Tpm2 tpm, TpmHandle h)
{
if (TestCfg.StressMode)
tpm._ExpectResponses(TpmRc.Handle, TpmRc.Value);
else if (h.GetType() == Ht.NvIndex ||
// TBS intercepts transient handles and returns RC_HANDLE,
// even though the correct reply is RC_VALUE.
(TestCfg.HasTRM && h.GetType() == Ht.Transient))
tpm._ExpectError(TpmRc.Handle);
else
tpm._ExpectError(TpmRc.Value);
}
public TpmHandle RandomInvalidHandle(Tpm2 tpm, Ht handleType)
{
TpmHandle h = null;
do
{
h = new TpmHandle(handleType, RandomInt(0x00100000 - 0x100) + 0x100);
// Preclude TSS.Net from failing in an attempt to use ReadPublic
// in order to get the nonexistent handle name
h.Name = new byte[0];
if (!Globs.IsOneOf(handleType, Ht.Persistent, Ht.Transient, Ht.Permanent, Ht.NvIndex))
return h;
ExpectBadHandleError(tpm, h);
if (handleType == Ht.NvIndex)
TpmHelper.NvReadPublic(tpm, h);
else
TpmHelper.ReadPublic(tpm, h);
} while (tpm._LastCommandSucceeded());
return h;
} // RandomInvalidHandle()
// Allocate randomly configured NV index (in a thread-safe manner, if necessary)
public NvPublic SafeDefineRandomNvIndex (Tpm2 tpm, ushort dataSize = 0, NvAttr attr = TestConfig.DefaultNvAttrs,
TpmAlgId nameAlg = TpmAlgId.Null, byte[] auth = null)
{
bool randomSize = dataSize == 0;
if (nameAlg == TpmAlgId.Null)
nameAlg = Random(TpmCfg.HashAlgs);
if (auth == null)
auth = RandomAuth(nameAlg);
NvPublic nvPub = new NvPublic(RandomNvHandle(), nameAlg, attr, null, 0);
nvPub.dataSize = randomSize ? (ushort)RandomInt(TpmCfg.MaxNvOpSize) : dataSize;
var expectedResp = tpm._GetExpectedResponses() ?? new TpmRc[] { TpmRc.Success };
// Wait no more than 10 sec for parallel threads to free NV
int i = 0;
while (i++ < 20)
{
if (TestCfg.StressMode)
tpm._ExpectMoreResponses(TpmRc.NvSpace, TpmRc.NvDefined);
tpm.NvDefineSpace(TpmRh.Owner, auth, nvPub);
TpmRc res = tpm._GetLastResponseCode();
if (res == TpmRc.Success || expectedResp.Contains(res))
break;
tpm._ExpectResponses(expectedResp);
if (res == TpmRc.NvDefined)
{
nvPub.nvIndex = RandomNvHandle();
}
else if (randomSize && nvPub.dataSize > 8)
{
nvPub.dataSize = (ushort)RandomInt(nvPub.dataSize);
}
else
{
// Wait for other threads to free NV resources
Thread.Sleep(500);
}
}
return i < 20 ? nvPub : null;
}
// Persist an object in a thread-safe manner.
// Can return false only in stress mode.
public bool StressSafeEvictControl(Tpm2 tpm, TpmHandle hObj, TpmHandle hPers,
TpmRh hierarchy = TpmRh.Owner)
{
if (!TestCfg.StressMode)
{
tpm.EvictControl(hierarchy, hObj, hPers);
return true;
}
// Wait no more than 10 sec for parallel threads to free NV
for (int i = 0; i < 20; ++i)
{
tpm._ExpectResponses(TpmRc.Success, TpmRc.NvSpace);
// Use lock to avoid interference with the creation of persistent
// primary objects used by Tpm2Tester infra.
lock (persKeysLock)
tpm.EvictControl(hierarchy, hObj, hPers);
if (tpm._LastCommandSucceeded())
return true;
// Wait until tests in parallel threads free NV
Thread.Sleep(500);
}
return false;
}
// This is a test callback function to help the owner-evict RSA primary
// semantics. Note that if you return true then the library will not send
// the command to the TPM.
bool AlternateActionCallback(TpmCc ordinal, TpmStructureBase inParms,
Type expectedResponseType,
out TpmStructureBase outParms,
out bool desiredResponse)
{
outParms = null;
desiredResponse = true;
if (ordinal == TpmCc.Clear)
{
// persistent Owner keys will be invalidated by the command
PersRsaPrimOwner = null;
RsaPrimOwnerPub = null;
PersRsaPrimEndors = null;
return false;
}
if (ordinal == TpmCc.ChangeEPS)
{
// persistent Endorsement keys will be invalidated by the command
PersRsaPrimEndors = null;
return false;
}
if (ordinal == TpmCc.ChangePPS)
{
// persistent Platform keys will be invalidated by the command
PersRsaPrimPlatform = null;
return false;
}
if (ordinal != TpmCc.FlushContext)
return false;
// TODO: replace the condition with a more general check for persistent handles
Tpm2FlushContextRequest req = (Tpm2FlushContextRequest)inParms;
if (req.flushHandle == PersRsaPrimOwner ||
req.flushHandle == PersRsaPrimEndors ||
req.flushHandle == PersRsaPrimPlatform)
{
string errMsg = "Use TPM2_EvictControl() to relinquish persistent handles";
WriteToLog(errMsg);
throw new Exception(errMsg);
}
return false;
}
Object persKeysLock = new Object();
uint NextPersHandle = (uint)TpmHc.PersistentFirst;
uint NextPlatformPersHandle = (uint)TpmHc.PlatformPersistent;
internal TpmHandle PersRsaPrimOwner = null;
internal TpmHandle PersRsaPrimPlatform = null;
internal TpmHandle PersRsaPrimEndors = null;
TpmPublic RsaPrimOwnerPub = null;
public TpmPublic GetRsaPrimOwnerPub(Tpm2 tpm)
{
if (RsaPrimOwnerPub == null)
LoadRsaPrimary(tpm);
return RsaPrimOwnerPub;
}
private int OneIfExists(object o)
{
return o == null ? 0 : 1;
}
// returns the number of persistent objects allocated by the Tpm2Tester infra.
public int NumPersistentHandles()
{
return OneIfExists(PersRsaPrimOwner) +
OneIfExists(PersRsaPrimPlatform) +
OneIfExists(PersRsaPrimEndors);
}
private TpmHandle GeneratePersistentHandle(ref uint nextHandle,
TpmHc first, TpmHc last,
TpmHandle pers1,
TpmHandle pers2 = null)
{
if (nextHandle == (uint)last)
nextHandle = (uint)first;
while (pers1 != null && nextHandle == pers1.handle ||
pers2 != null && nextHandle == pers2.handle)
{
++nextHandle;
}
return new TpmHandle(nextHandle++);
}
public TpmHandle NextPersistentHandle(TpmRh hierarchy = TpmRh.Owner)
{
lock (persKeysLock)
{
if (hierarchy == TpmRh.Owner || hierarchy == TpmRh.Endorsement)
{
return GeneratePersistentHandle(ref NextPersHandle,
TpmHc.PersistentFirst, TpmHc.PlatformPersistent - 1,
PersRsaPrimOwner, PersRsaPrimEndors);
}
else if (hierarchy == TpmRh.Platform)
{
return GeneratePersistentHandle(ref NextPlatformPersHandle,
TpmHc.PlatformPersistent, TpmHc.PersistentLast,
PersRsaPrimPlatform);
}
}
throw new Exception("Handle " + hierarchy + "is not a hierarchy");
}
private bool ClearPersistent(Tpm2 tpm, TpmRh hierarchy,
ref TpmHandle hPersistent)
{
if (hPersistent != null)
{
tpm.EvictControl(hierarchy, hPersistent, hPersistent);
hPersistent = null;
return true;
}
return false;
}
private ushort GetSupportedPrimaryRsaKeySize(Tpm2 tpm, ushort keySize, TpmRh hierarchy)
{
if (!TpmCfg.RsaKeySizes.Contains(keySize))
return keySize;
bool owner = hierarchy == TpmRh.Owner;
var supportedSizes = owner ? TpmCfg.PrimaryRsaKeySizes : TpmCfg.PrimaryEndorsRsaKeySizes;
if (supportedSizes == null)
{
var keySizes = new List<ushort>();
var scheme = owner ? (IAsymSchemeUnion)new SchemeOaep(TpmCfg.HashAlgs[0])
: (IAsymSchemeUnion)new SchemeRsassa(TpmCfg.HashAlgs[0]);
var rsaParams = new RsaParms(new SymDef(), scheme, 0, 0);
var inPub = new TpmPublic(AltHashAlg(TpmAlgId.Sha1),
(owner ? ObjectAttr.Decrypt : ObjectAttr.Sign)
| ObjectAttr.FixedTPM | ObjectAttr.FixedParent
| ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin,
null,
rsaParams,
new Tpm2bPublicKeyRsa());
foreach (var size in TpmCfg.RsaKeySizes)
{
rsaParams.keyBits = size;
tpm._ExpectResponses(TpmRc.Success, TpmRc.Asymmetric, TpmRc.Value);
var sensCreate = new SensitiveCreate(null, null);
TpmPublic pub;
CreationData creationData;
byte[] creationHash;
TkCreation creationTicket;
TpmHandle h = tpm.CreatePrimary(hierarchy, sensCreate,
inPub, null, null,
out pub, out creationData,
out creationHash, out creationTicket);
if (tpm._LastCommandSucceeded())
{
keySizes.Add(size);
tpm.FlushContext(h);
}
}
if (owner)
{
supportedSizes = TpmCfg.PrimaryRsaKeySizes = keySizes.ToArray();
if ( supportedSizes.Length != TpmCfg.RsaKeySizes.Length
&& !TpmCfg.FipsMode)
{
WriteErrorToLog("CreatePrimary supports not all RSA key sizes, " +
"but FIPS compliance is not indicated",
ConsoleColor.Magenta);
}
}
else
supportedSizes = TpmCfg.PrimaryEndorsRsaKeySizes = keySizes.ToArray();
}
return supportedSizes.Contains(keySize) ? keySize : supportedSizes[0];
}
private EccCurve GetSupportedPrimaryEccCurve(Tpm2 tpm, EccCurve curveId, TpmRh hierarchy)
{
if (!TpmCfg.EccCurves.ContainsKey(curveId))
return curveId;
bool owner = hierarchy == TpmRh.Owner;
var supportedCurves = owner ? TpmCfg.PrimaryCurves : TpmCfg.PrimaryEndorsmentCurves;
if (supportedCurves == null)
{
var curves = new List<EccCurve>();
var scheme = owner ? (IAsymSchemeUnion)new SchemeEcdh(TpmCfg.HashAlgs[0])
: (IAsymSchemeUnion)new SchemeEcdsa(TpmCfg.HashAlgs[0]);
var eccParams = new EccParms(new SymDef(), scheme, EccCurve.None,
new NullKdfScheme());
var inPub = new TpmPublic(AltHashAlg(TpmAlgId.Sha1),
(owner ? ObjectAttr.Decrypt : ObjectAttr.Sign)
| ObjectAttr.FixedTPM | ObjectAttr.FixedParent
| ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin,
null,
eccParams,
new EccPoint());
int numNonEcdhCurves = 0;
foreach (var curve in TpmCfg.EccCurves)
{
if (!TpmCfg.CurveSupportsScheme(curve.Key, TpmAlgId.Ecdh))
{
++numNonEcdhCurves;
continue;
}
eccParams.curveID = curve.Key;
tpm._ExpectResponses(TpmRc.Success, TpmRc.Asymmetric, TpmRc.Value);
var sensCreate = new SensitiveCreate(null, null);
TpmPublic pub;
CreationData creationData;
byte[] creationHash;
TkCreation creationTicket;
TpmHandle h = tpm.CreatePrimary(hierarchy, sensCreate,
inPub, null, null,
out pub, out creationData,
out creationHash, out creationTicket);
if (tpm._LastCommandSucceeded())
{
curves.Add(curve.Key);
tpm.FlushContext(h);
}
}
if (owner)
{
supportedCurves = TpmCfg.PrimaryCurves = curves.ToArray();
if ( supportedCurves.Length != TpmCfg.EccCurves.Count - numNonEcdhCurves
&& !TpmCfg.FipsMode)
{
WriteErrorToLog("CreatePrimary supports not all ECC curves, " +
"but FIPS compliance is not indicated");
}
}
else
supportedCurves = TpmCfg.PrimaryEndorsmentCurves = curves.ToArray();
}
return supportedCurves.Contains(curveId) ? curveId : supportedCurves[0];
}
public TpmHandle CreatePrimary(Tpm2 tpm, TpmPublic inPub, out TpmPublic pub,
out byte[] creationHash, out TkCreation creationTicket,
SensitiveCreate sensCreate = null,
TpmRh hierarchy = TpmRh.Owner,
PcrSelection[] inPcrSel = null,
byte[] outsideInfo = null)
{
inPcrSel = inPcrSel ?? new PcrSelection[] { RandomPcrSel() };
outsideInfo = outsideInfo ?? RandBytes(0, 20);
if (sensCreate == null)
sensCreate = new SensitiveCreate(RandomAuth(inPub.nameAlg), null);
CreationData creationData;
//
// Some TPMs only allow primary keys of no lower than a particular strength.
// Sometimes the restriction is applied only to the endorsement hierarchy,
// and sometimes to both the owner and endorsement hierarchies.
//