forked from microsoft/TSS.MSR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestFramework.cs
More file actions
2325 lines (2056 loc) · 92.8 KB
/
Copy pathTestFramework.cs
File metadata and controls
2325 lines (2056 loc) · 92.8 KB
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.Linq;
using System.IO;
using System.IO.Pipes;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Text;
using Tpm2Lib;
namespace Tpm2Tester
{
internal partial class TestFramework
{
//internal static TestProg MyTestProg;
//internal TestCases TpmTester = null;
const int MaxConcurrentInstances = 64;
class ThreadTestContext
{
internal int testIndex;
internal TestContext testCtx;
internal TestLogger logger;
internal Tbs tbs;
internal DateTime endTime;
internal List<MethodInfo> tests;
internal Barrier barrier;
internal bool aTestFailed;
};
// Part of the test infrastructure used by tests implemented in the client assemblies
internal TestSubstrate Substrate;
// Shortcut to the corresponding Substrate member
internal TestConfig TestCfg;
// Shortcut to the corresponding Substrate member
internal TpmConfig TpmCfg;
// The primary Tpm2 instance.
internal Tpm2 MainTpm;
// Primary test context
internal TestContext MainTestContext;
// Primary logger
internal TestLogger MainTestLogger;
// Primary TPM device
TpmPassThroughDevice MainTpmDevice;
// Primary underlying TPM device
Tpm2Device UnderlyingTpmDevice;
// A TBS abstraction layer created on top of MainTpmDevice.
Tbs Tbs;
// TPM simulator process object created with '-tpm' option. See TestCfg.TpmPath.
Process TpmProcess;
static readonly AuthValue NullAuth = new AuthValue();
private TesterCmdLine CmdLine;
private delegate Tpm2Device MakeNewTpm(TestContext testCtx);
private MakeNewTpm TpmFactory;
private List<MethodInfo> _AllTests;
private List<string> _AllTestNames;
// Reference to an object in the client assembly that contains test methods to run.
// This object must implement all non-static test methods in the assembly.
// Static test methods can be spread across multiple classes. If the client
// assembly only contains static test methods, TestContainer may reference any
// object in the assembly.
static object TestContainer = null;
bool InitTPM;
// State of the current test. Used to pass in the string of the '-params' option,
// and/or to restart failing tests.
// Restart can be useful when the same method tests multiple scenarios in order
// to achieve better coverage during a single run in the presence of failures
// that may happen only in a few cases out of the many.
TestState TheTestState;
// Set of handles that Tpm2Tester failed to delete during TPM cleanup.
// This is normally NV indices in platform hierarchy that require a policy
// for their deletion.
static HashSet<uint> ToughHandles = new HashSet<uint>();
#if !TSS_NO_TCP
// Output of the TPM simulator process to its stderr (with -tpm option).
// Used to report simulator's crash dump. May be obsolete.
internal string TpmStderr;
#endif
#if !WLK
// Base of the report file name
string StemFile = "TpmTests";
#endif
internal string RemainingTestsFile = "RemainingTests";
// Each tester assigns itself a separate instance to make it easier to run
// more than one tester/TPM pair on a machine.
internal int TesterInstance = 0;
// Common prefix used to name InstanceAnchor objects.
const string TesterMutexNamePrefix = "TPM_TESTER_MUTEX_";
// An instance of a named kernel mode object used to uniquely number concurrent Tpm2Tester instances.
static NamedPipeServerStream InstanceAnchor;
string CheckinFileName = "";
DateTime startTime;
private TestFramework(TestSubstrate substrate)
{
Substrate = substrate;
TestCfg = substrate.TestCfg;
TpmCfg = substrate.TpmCfg;
}
/// <summary>Create a test framework 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>
internal static TestFramework Create(TestSubstrate substrate,
string[] args, object testContainer)
{
var framework = new TestFramework(substrate);
return framework.Init(args, testContainer) ? framework : null;
}
internal bool Init(string[] args, object testContainer)
{
Console.ResetColor();
MainTestLogger = new TestLogger(testContainer.GetType().Assembly);
TesterInstance = SetTesterInstance();
if (TesterInstance < 0)
{
WriteErrorToLog("Too many tester instances running on this host. Aborting...");
MainTestLogger = null;
return false;
}
// So that multiple tester instances don't collide:
RemainingTestsFile = RemainingTestsFile + "_" + TesterInstance + ".txt";
TestContainer = testContainer;
_AllTests = new List<MethodInfo>();
MethodInfo[] methods = TestContainer.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (MethodInfo mi in methods)
{
TestAttribute attr = Globs.GetAttr<TestAttribute>(mi);
if (attr == null || attr.CommProfile.HasFlag(Profile.Disabled))
{
continue;
}
_AllTests.Add(mi);
}
_AllTestNames = Globs.ConvertAll(AllTests, item => item.Name);
// By default (unless command line options intervene) all found test methods will be run.
TestCfg.TestsToRun = AllTestNames;
CmdLine = new TesterCmdLine(this, args);
if (!CmdLine.Parse())
{
if (System.Diagnostics.Debugger.IsAttached)
{
// give us a few seconds to see the error text.
Thread.Sleep(5000);
}
return false;
}
if (TestCfg.TestsToRun == null && !TestCfg.StopTpm && !TestCfg.DumpTpmInfo)
{
// Options "-list", "-help", etc.
// Terminate without communicating with the TPM device.
return false;
}
MainTestContext = MainTestLogger.NewContext(true);
TestCategorizer.Init();
return true;
}
internal bool RunTestSession()
{
Console.ResetColor();
if (TesterInstance != 0 && TestCfg.Verbose)
{
WriteToLog("Tester Instance: " + TesterInstance);
}
TheTestState = new TestState(TestCfg.TestParams);
// Instruct library to use deterministic "random" numbers for test
// repeatability (at least in the case of single-threaded tests)
if (TestCfg.SeededRng)
{
Globs.SetRngSeed(TestCfg.RngSeed);
}
#if !TSS_NO_TCP
if (TestCfg.TpmPath != "" && !StartTpm())
{
return false;
}
#endif
// Create a new device of class requested. The object returned is a wrapper
// of type TpmPassThruDevice, which allows callbacks to be installed.
var tpmDevice = CreateTpmDevice(MainTestContext);
if (tpmDevice == null)
return false;
int initialErrorCount = NumTestFailures();
if (TestCfg.StopTpm)
goto ExitProgram;
#if !TSS_NO_TCP
if (TestCfg.TpmAutoRestart)
{
// Set the sockets to timeout so that we can propagate a failure to
// the caller if the TPM seems to be busted.
TestCfg.TheTcpTpmDevice.SetSocketTimeout((int)(TestConfig.NumMinsBeforeAutoRestart * 60));
}
if (TestCfg.TransportLogsDirectory != null)
{
if (!(UnderlyingTpmDevice is TcpTpmDevice))
{
WriteErrorToLog("Can only log TCP TPM device");
return false;
}
if (TestCfg.StressMode == true)
{
WriteErrorToLog("Cannot log in stress mode");
return false;
}
InitTransportLogger(TestCfg.TransportLogsDirectory,
(TcpTpmDevice)UnderlyingTpmDevice);
}
#endif
if (TestCfg.DumpConsole)
{
string consoleLogFile;
if (TestCfg.TransportLogsDirectory != null)
{
consoleLogFile = System.IO.Path.Combine(TestCfg.TransportLogsDirectory,
"console.txt");
}
else
{
#if TSS_MIN_API
consoleLogFile = "console.txt";
#else
string docsPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
consoleLogFile = System.IO.Path.Combine(docsPath, "console.txt");
#endif
}
MainTestLogger.SetLogFileName(consoleLogFile);
}
#if false
// Testing TPM with minimal Tpm2Tester infrastructure initialization
tpmDevice.PowerCycle();
tpmDevice.SignalNvOn();
var tpm = new Tpm2(tpmDevice);
tpm.Startup(Su.Clear);
// Insert test code here
return true;
#endif
TestCfg.HasTRM = tpmDevice.HasRM();
PowerUpTpm(tpmDevice);
// "Stress-mode" creates threads that randomly execute TPM tests. If the
// TPM is multi-context (like TBS) we open one context per stress thread.
// If the device is not multi-context then Tpm2Tester uses its own emulated RM.
if (TestCfg.HasTRM)
TpmFactory = CreateTpmDevice;
TestCfg.DoInit = TestCfg.DoInit && tpmDevice.PlatformAvailable();
// Initialize the testCtx. It will try to communicate with the TPM.
try
{
if (!InitTpmDevice(tpmDevice))
return false;
}
catch (Exception e)
{
var exceptionInfo = TestLogger.ParseException(e);
WriteErrorToLog("Failed to communicate with the TPM during " +
"initialization.\n" + exceptionInfo.message);
return false;
}
if (TestCfg.DumpTpmInfo)
{
// -tpmInfo option was used. Quit after dumping TPM information.
goto ExitProgram;
}
TestCfg.TestsToRun = CmdLine.GenerateTestSet(tpmDevice);
if (TestCfg.TestsToRun.Count == 0)
goto ExitProgram;
// Ready to start tests...
NotifyTestStartStop(true);
// In the following we perform the requested test run with the requested
// test routine set.
// TestValidation tests that the test use the privileges that they state.
// Test validation runs should be performed as new tests are added.
if (FuzzMode)
{
if (TestCfg.Verbose)
WriteToLog("\nRunning TPM tests in fuzz mode\n");
if (TestCfg.TestEndTime == DateTime.MinValue)
{
if (TestCfg.Verbose)
WriteToLog("Test duration defaulting to 60 minutes");
TestCfg.TestEndTime = DateTime.Now + new TimeSpan(0, 60, 0);
}
RunFuzz(TestCfg.TestsToRun.ToArray(), TestCfg.TestEndTime);
#if !TSS_NO_TCP
if (TestCfg.TpmPath != "")
{
KillTpmProcess();
}
#endif
}
else if (TestCfg.StressMode)
{
if (TestCfg.Verbose)
WriteToLog("\nRunning TPM tests in stress mode\n");
if (TestCfg.TestEndTime == DateTime.MinValue)
{
if (TestCfg.Verbose)
WriteToLog("Test duration defaulting to {0} minutes",
TestConfig.DefaultStressModeDuration);
TestCfg.TestEndTime = DateTime.Now +
new TimeSpan(0, TestConfig.DefaultStressModeDuration, 0);
}
double stateSaveProb = TestCfg.TestS3 ? TestConfig.StateSaveProbability : 0.0;
RunStress(TestCfg.TestsToRun.ToArray(), TestCfg.NumThreads, TestCfg.TestEndTime,
TestCfg.StopOnFirstError, stateSaveProb, TestCfg.TestNvAvailable);
}
else
{
if (TestCfg.Verbose)
WriteToLog("\nRunning TPM tests sequentially\n");
RunTestsSerially(TestCfg.TestsToRun.ToArray(), TestCfg.TestEndTime);
}
// Tests completed
string reportFileName = null;
#if !WLK
if (TestCfg.ShowHTML)
reportFileName = StemFile + "_" + TesterInstance.ToString() + ".Report.html";
#endif
MainTestLogger.TestRunCompleted(reportFileName);
ExitProgram:
if (TestCfg.DoInit)
MainTpm.Shutdown(Su.Clear);
if (TestCfg.UseKeyCache)
UnderlyingTpmDevice.SignalKeyCacheOff();
tpmDevice.Dispose();
if (!Debugger.IsAttached)
{
NotifyTestStartStop(false);
}
return initialErrorCount >= NumTestFailures();
} // RunTestSession()
public int NumTestFailures()
{
return MainTestLogger.CumulativeFailures.Count;
}
private int SetTesterInstance()
{
for (int j = 0; j < MaxConcurrentInstances; j++)
{
try
{
InstanceAnchor = new NamedPipeServerStream(TesterMutexNamePrefix + j, PipeDirection.InOut, 1);
}
catch (IOException)
{
continue;
}
return j;
}
return -1;
}
private int GetTesterInstance()
{
return TesterInstance;
}
// If instructed the tester will create a file in Crashes/Checkins to notify the world
// that an instance has started
private void NotifyTestStartStop(bool isStarting)
{
if (!TestCfg.GenerateStartupCheckin)
return;
string msg;
if (isStarting)
{
startTime = DateTime.Now;
string checkinFileDir = TestCfg.FuzzCrashesDirectory + "Checkins" + Path.DirectorySeparatorChar;
string hostName = Process.GetCurrentProcess().MachineName;
string dateTime = DateTime.Now.ToString("MMMM_dd_yyyy_HH_mm_ss_FFFF");
string fileName = "checkin_" + hostName + "_" + TesterInstance.ToString() + "_" + dateTime + "_" + Guid.NewGuid().ToString() + ".txt";
CheckinFileName = checkinFileDir + fileName;
msg = "running...";
}
else
{
msg = "Test run " + (DateTime.Now - startTime).TotalHours + " hours";
}
try
{
File.WriteAllText(CheckinFileName, msg);
}
catch (Exception e)
{
WriteErrorToLog("Failed to create the checkin-file. Error: \n" + e.Message);
}
} // NotifyTestStartStop()
// The warning appears to be a false positive, as the potentially leaked object is returned.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
// Make a device of the type specified on the command line. A PassThroughDevice
// is instantiated on top of the actual TPM device and necessary callbacks are installed
// Note: in stress mode, and if TpmHasResourceManager=true, the test framework
// will instantiate one device per thread.
private TpmPassThroughDevice CreateTpmDevice(ICommandCallbacks callbacks)
{
Tpm2Device underlyingTpmDevice = null;
try
{
switch (TestCfg.DeviceType)
{
case TpmDeviceType.dll:
if (TestCfg.TpmDllPath == null)
{
WriteErrorToLog("-device dll requires -dllpath PathToDll");
return null;
}
if (!Directory.Exists(TestCfg.TpmDllPath))
{
WriteErrorToLog("dllpath does not exist:" + TestCfg.TpmDllPath);
return null;
}
underlyingTpmDevice = new InprocTpm(TestCfg.TpmDllPath);
break;
case TpmDeviceType.tbs:
case TpmDeviceType.tbsraw:
if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
underlyingTpmDevice = new LinuxTpmDevice();
else
underlyingTpmDevice = new TbsDevice(TestCfg.DeviceType != TpmDeviceType.tbsraw);
break;
#if !TSS_NO_TCP
case TpmDeviceType.tcp:
case TpmDeviceType.rmsim:
{
var tcpDev = new TcpTpmDevice(TestCfg.TcpHostName, GetTcpServerPort(), TestCfg.StopTpm);
#if !DEBUG
tcpDev.SetSocketTimeout(2000);
#endif
underlyingTpmDevice = tcpDev;
if (TestCfg.DeviceType == TpmDeviceType.rmsim)
{
underlyingTpmDevice = new Tbs.TbsContext(new Tbs(underlyingTpmDevice, true));
}
break;
}
#endif
default:
throw new Exception("should not be here");
}
#if !TSS_NO_TCP
if (underlyingTpmDevice is TcpTpmDevice)
{
TestCfg.TheTcpTpmDevice = (TcpTpmDevice)underlyingTpmDevice;
}
#endif
}
catch (Exception)
{
if (underlyingTpmDevice != null)
underlyingTpmDevice.Dispose();
throw;
}
try
{
underlyingTpmDevice.Connect();
}
catch (Exception e)
{
WriteErrorToLog("Failed to connect to the TPM. Error: " + e.Message);
underlyingTpmDevice.Dispose();
Thread.Sleep(3000);
return null;
}
try
{
var tpmDevice = new TpmPassThroughDevice(underlyingTpmDevice);
tpmDevice.SetCommandCallbacks(callbacks);
UnderlyingTpmDevice = underlyingTpmDevice;
if (TestCfg.UseKeyCache)
UnderlyingTpmDevice.SignalKeyCacheOn();
return tpmDevice;
}
catch (Exception)
{
underlyingTpmDevice.Dispose();
throw;
}
} // CreateTpmDevice()
internal class BadRsaKeyException : Exception
{
internal byte[] PublicKey { get; set; }
internal BadRsaKeyException(byte[] publicKey)
{
PublicKey = publicKey;
}
}
private void ParamsTraceCallback(TpmCc ordinal, TpmStructureBase inParms,
TpmStructureBase outParms)
{
TpmPublic pub = null;
if (ordinal == TpmCc.Create)
{
pub = (outParms as Tpm2CreateResponse).outPublic;
}
else if (ordinal == TpmCc.CreatePrimary)
{
pub = (outParms as Tpm2CreatePrimaryResponse).outPublic;
}
if (pub != null)
{
if (pub.unique.GetUnionSelector() == TpmAlgId.Rsa)
{
Tpm2bPublicKeyRsa rsaPub = (Tpm2bPublicKeyRsa)pub.unique;
if ((rsaPub.buffer[0] & 0x80) != 0x80)
{
WriteErrorToLog("RSA key was generated incorrectly: {0}",
Globs.HexFromByteArray(rsaPub.buffer));
//throw new BadRsaKeyException(rsaPub.buffer);
}
}
}
} // ParamsTraceCallback()
private bool InitTpmDevice(TpmPassThroughDevice device)
{
MainTpmDevice = device;
#if WLK
// the WHCK (WLK) is already clearing the TPM, no need to initialize here.
InitTPM = false;
#else
InitTPM = !TestCfg.RunAsStandardUser && TestCfg.DoInit;
#endif
if (TestCfg.StressMode)
{
TpmCfg.PlatformDisabled = true;
TpmCfg.PowerControl = TpmCfg.LocalityControl = false;
}
else
{
TpmCfg.PlatformDisabled = !device.PlatformAvailable();
TpmCfg.PowerControl = device.PowerCtlAvailable();
TpmCfg.LocalityControl = device.LocalityCtlAvailable();
TpmCfg.NvControl = device.NvCtlAvailable();
}
MainTpm = new Tpm2(MainTpmDevice);
// To test TBS-like environment:
#if false
TpmCfg.PlatformDisabled = true;
MainTpm.LockoutAuth = new byte[] { 1 };
#endif
//MainTpm._SetTraceCallback(RawCommandCallback);
MainTpm._SetParamsTraceCallback(ParamsTraceCallback);
// See whether the TPM is alive ...
byte[] r = MainTpm._AllowErrors().GetRandom(1);
if (MainTpm._GetLastResponseCode() != TpmRc.Success)
{
WriteErrorToLog("TPM failed to execute GetRandom command. Error {"
+ MainTpm._GetLastResponseCode() + "}");
return false;
}
#if false
// Test Tpm2Tester reaction on the presence of a policy-delete NV index.
TpmHandle nvHandle = TpmHandle.NV((uint)0xC00002);
byte[] nvPolicy = new TpmHash(TpmAlgId.Sha);
nvPolicy[1] = 1;
var nvPub = new NvPublic(nvHandle, TpmAlgId.Sha,
TestConfig.DefaultNvAttrs
| NvAttr.Platformcreate | NvAttr.PolicyDelete,
nvPolicy, 8);
MainTpm._ExpectResponses(TpmRc.Success, TpmRc.NvDefined)
.NvDefineSpace(TpmRh.Platform, null, nvPub);
MainTpm.NvWrite(nvHandle, nvHandle, new byte[]{1,2,3,4}, 0);
#endif
// ... and accessible to us
ResetTpmDaLogic(MainTpm, true);
if (TestCfg.TestNvAvailable)
{
MainTpm._DebugTestNvIsAvailable();
}
uint[] version = MainTpm.GetFirmwareVersionEx();
if (TpmCfg.TpmVersion == 0)
{
TpmCfg.TpmVersion = version[2];
}
else if (TpmCfg.TpmVersion != version[2])
{
WriteErrorToLog("All TPM devices must be of same revision. "
+ "Encountered revisions: {0}, {1}",
TpmCfg.TpmVersion / 100f, version[2] / 100f);
return false;
}
if (TpmCfg.TpmVersion < 88)
{
WriteErrorToLog("Tpm2Tester does not support TPM revisions before 0.88. "
+ "Aborting...");
return false;
}
if (TpmCfg.TpmVersion > (uint)Spec.Version || TpmCfg.TpmVersion < 88)
{
WriteErrorToLog("This Tpm2Tester is only aware of TPM revisions up to {0}. "
+ "Some test cases may fail.", (float)Spec.Version / 100);
}
// TPM version, spec date and manufacturer info
string manufacturer;
uint specYear, specDay;
Tpm2.GetTpmInfo(MainTpm, out manufacturer, out specYear, out specDay);
TpmCfg.TpmSpecDate = new DateTime((int)specYear, 1, 1);
TpmCfg.TpmSpecDate = TpmCfg.TpmSpecDate.AddDays(specDay - 1);
if (TestCfg.Verbose || TestCfg.DumpTpmInfo)
{
WriteToLog("TPM manufacturer: " + manufacturer);
WriteToLog("TPM revision : {0:F2}", TpmCfg.TpmVersion / 100f);
WriteToLog("TPM Spec date : " + TpmCfg.TpmSpecDate.ToString("MMMM dd, yyyy"));
// NOTE: This is a convention in the reference implementation, that
// the FW version reports a build time. But this is not normative.
string fwDateTime = "Date= " + Globs.HexFromValueType(version[0]) +
", Time=" + Globs.HexFromValueType(version[1]);
WriteToLog("TPM Firmware Build Time Stamp: " + fwDateTime);
}
Tbs = new Tbs(MainTpmDevice, device.HasRM());
// Clean up TPM
try
{
if (!RecoverTpm(MainTpm) &&
(!PlatformCleanTpm(MainTpm) || !RecoverTpm(MainTpm)))
{
WriteErrorToLog("Failed to completely clean up the TPM.\n" +
"Possibly one of the primary auth values is not known.\n" +
"Continuing, but some tests may fail or will be bypassed...");
}
}
catch (Exception e)
{
WriteErrorToLog("Unknown error while cleaning up the TPM: " + e.Message);
WriteErrorToLog("Will try to proceed, but some tests may fail...");
}
InitTpmParams(MainTpm);
return true;
} // InitTpmDevice()
private void InitTpmParams(Tpm2 tpm)
{
if (TpmCfg.ImplementedAlgs != null)
return;
if (TestCfg.Verbose || TestCfg.DumpTpmInfo)
WriteToLog("TPM configuration:");
TpmCfg.Hierarchies = TpmCfg.PlatformDisabled
? new TpmRh[] {TpmRh.Owner, TpmRh.Endorsement}
: new TpmRh[] {TpmRh.Owner, TpmRh.Endorsement, TpmRh.Platform};
// Enumerate commands implemented by the target TPM instance.
// If a test attempts to execute not implemented command, it will be reported
// as "aborted" instead of "failed".
uint totalCommands = Tpm2.GetProperty(MainTpm, Pt.TotalCommands);
TpmCfg.FipsMode = (Tpm2.GetProperty(tpm, Pt.Modes) & (uint)ModesAttr.Fips1402) != 0;
if (TpmCfg.FipsMode)
WriteToLog("FIPS 140-2 compliant");
ICapabilitiesUnion caps;
byte more = tpm.GetCapability(Cap.Commands, (uint)TpmCc.First,
totalCommands, out caps);
TpmCfg.SupportedCommands = Globs.ConvertAll((caps as CcaArray).commandAttributes,
cmdAttr => (TpmCc)(cmdAttr & (CcAttr.commandIndexBitMask | CcAttr.V)))
.ToArray();
Substrate.Assert(totalCommands == TpmCfg.SupportedCommands.Length);
TpmCfg.ResettablePcrs = Tpm2.GetPcrProperty(tpm, PtPcr.ResetL0);
TpmCfg.ExtendablePcrs = Tpm2.GetPcrProperty(tpm, PtPcr.ExtendL0);
TpmCfg.ContextHashAlg = (TpmAlgId)Tpm2.GetProperty(tpm, Pt.ContextHash);
ushort ctxDigestSize = TpmHash.DigestSize(TpmCfg.ContextHashAlg);
var hashAlgs = new List<TpmAlgId>();
var symAlgs = new List<TpmAlgId>();
var blockModes = new List<TpmAlgId>();
more = tpm.GetCapability(Cap.Algs, (uint)TpmAlgId.First,
(uint)TpmAlgId.Last - (uint)TpmAlgId.First + 1,
out caps);
TpmCfg.ImplementedAlgs = Globs.ConvertAll(
(caps as AlgPropertyArray).algProperties,
algProp =>
{
if (algProp.algProperties == AlgorithmAttr.Hash)
{
if (CryptoLib.IsHashAlgorithm(algProp.alg))
{
hashAlgs.Add(algProp.alg);
if (TpmHash.DigestSize(algProp.alg) > ctxDigestSize)
{
WriteErrorToLog("Warning: {0} has larger digest " +
"than that of the context integrity {1}",
algProp.alg, TpmCfg.ContextHashAlg, ConsoleColor.Cyan);
}
}
else
{
WriteErrorToLog("Warning: Tpm2Tester's software crypto " +
"layer does not support {0}",
algProp.alg, ConsoleColor.Cyan);
}
}
else if (algProp.algProperties.HasFlag(AlgorithmAttr.Symmetric))
{
if (algProp.algProperties.HasFlag(AlgorithmAttr.Encrypting))
{
blockModes.Add(algProp.alg);
}
else
{
symAlgs.Add(algProp.alg);
}
}
return algProp.alg;
})
.ToArray();
TpmCfg.HashAlgs = hashAlgs.ToArray();
TpmCfg.HashAlgsEx = Array.CreateInstance(typeof(TpmAlgId), TpmCfg.HashAlgs.Length + 1)
as TpmAlgId[];
TpmCfg.HashAlgsEx[0] = TpmAlgId.Null;
Array.Copy(TpmCfg.HashAlgs, 0, TpmCfg.HashAlgsEx, 1, TpmCfg.HashAlgs.Length);
LogListOfValues("Hash algorithms: ", hashAlgs);
TpmCfg.EccCurves = new Dictionary<EccCurve, AlgorithmDetailEcc>();
var swEccCurves = new List<EccCurve>();
int maxEccKeyBits = 0;
more = tpm._AllowErrors()
.GetCapability(Cap.EccCurves, (uint)0, (uint)0xFFFF, out caps);
if (MainTpm._LastCommandSucceeded())
{
foreach (var curve in (caps as EccCurveArray).eccCurves)
{
AlgorithmDetailEcc curveDetail = tpm.EccParameters(curve);
maxEccKeyBits = Math.Max(maxEccKeyBits, curveDetail.keySize);
var coordBytes = curveDetail.gX.Length;
if (!TpmCfg.Tpm_115_Errata_13() && coordBytes > 32)
{
continue;
}
TpmCfg.EccCurves.Add(curve, curveDetail);
if (AsymCryptoSystem.IsCurveSupported(curve))
{
swEccCurves.Add(curve);
}
}
}
else
{
TestCfg.DisabledTests.Category |= Category.Ecc;
}
LogListOfValues("ECC curves: ", TpmCfg.EccCurves.Keys);
TpmCfg.SwEccCurves = swEccCurves.ToArray();
TpmCfg.MaxEccKeySize = (maxEccKeyBits + 7) / 8;
TpmCfg.MaxDigestSize = (ushort)Tpm2.GetProperty(MainTpm, Pt.MaxDigest);
TpmCfg.MaxInputBuffer = (ushort)Tpm2.GetProperty(tpm, Pt.InputBuffer);
TpmCfg.MaxNvIndexSize = (ushort)Tpm2.GetProperty(tpm, Pt.NvIndexMax);
TpmCfg.MaxNvOpSize = (ushort)Tpm2.GetProperty(tpm, Pt.NvBufferMax);
TpmCfg.MaxLabelSize = Math.Min(32, (Math.Min(TpmCfg.MaxEccKeySize, TpmCfg.MaxDigestSize)));
// Some TPMs allow NV index to take most of the NV. This would break some
// tests. Thus, force the decreased limit.
TpmHandle nvHandle1 = TpmHandle.NV(TestConfig.MaxNvIndex + 1);
TpmHandle nvHandle2 = TpmHandle.NV(TestConfig.MaxNvIndex + 2);
while (true)
{
var nvPub = new NvPublic(nvHandle1, TpmCfg.HashAlgs[0], TestConfig.DefaultNvAttrs,
null, TpmCfg.MaxNvIndexSize);
tpm._ExpectResponses(TpmRc.Success, TpmRc.NvSpace, TpmRc.BadAuth, TpmRc.NvDefined)
.NvDefineSpace(TpmRh.Owner, null, nvPub);
if (tpm._GetLastResponseCode() == TpmRc.NvDefined)
{
nvHandle1.handle++;
nvHandle2.handle++;
continue;
}
// OwnerAuth value recovery
// NOTE: Similar code is used by CleanNv(). Update in sync.
if (tpm._GetLastResponseCode() == TpmRc.BadAuth)
{
// Owner auth may have been changed by a previously failed test
tpm[TestConfig.TempAuth]._ExpectResponses(TpmRc.Success, TpmRc.NvSpace, TpmRc.BadAuth)
.NvDefineSpace(TpmRh.Owner, null, nvPub);
if (tpm._LastCommandSucceeded())
{
tpm.OwnerAuth = TestConfig.TempAuth;
}
else if (!Globs.IsZeroBuffer(tpm.OwnerAuth))
{
tpm[NullAuth]._ExpectResponses(TpmRc.Success, TpmRc.NvSpace)
.NvDefineSpace(TpmRh.Owner, null, nvPub);
if (tpm._LastCommandSucceeded())
{
tpm.OwnerAuth = NullAuth;
}
}
}
if (tpm._LastCommandSucceeded())
{
nvPub.nvIndex = nvHandle2;
tpm._ExpectResponses(TpmRc.Success, TpmRc.NvSpace)
.NvDefineSpace(TpmRh.Owner, null, nvPub);
bool secondIndexAllocated = tpm._LastCommandSucceeded();
tpm.NvUndefineSpace(TpmRh.Owner, nvHandle1);
if (secondIndexAllocated)
{
tpm.NvUndefineSpace(TpmRh.Owner, nvHandle2);
break;
}
}
if (TpmCfg.MaxNvIndexSize / 2 < 2048)
{
TpmCfg.MaxNvIndexSize = 2048;
break;
}
else
TpmCfg.MaxNvIndexSize /= 2;
}
// Workaround for TPMs incorrectly reporting TPM_PT_NV_BUFFER_MAX property
if (TpmCfg.MaxNvOpSize == 0)
{
TpmCfg.MaxNvOpSize = TpmCfg.MaxDigestSize;
}
TpmCfg.SafeNvIndexSize = Math.Min(TpmCfg.MaxNvIndexSize, TpmCfg.MaxNvOpSize);
PcrSelection.MaxPcrs = (ushort)Tpm2.GetProperty(tpm, Pt.PcrCount);
TpmCfg.MaxQualDataSize = (ushort)(TpmCfg.MaxDigestSize + sizeof(UInt16));
TpmCfg.LargestHashAlg = TpmCfg.ShortestHashAlg = TpmAlgId.None;
TpmCfg.MinDigestSize = ushort.MaxValue;
TpmCfg.MaxDigestSize = 0;
foreach (var alg in TpmCfg.HashAlgs)
{
var digestSize = TpmHash.DigestSize(alg);
if (TpmCfg.MaxDigestSize < digestSize)
{
TpmCfg.MaxDigestSize = digestSize;
TpmCfg.LargestHashAlg = alg;
}
if (TpmCfg.MinDigestSize > digestSize)
{
TpmCfg.ShortestHashAlg = alg;
TpmCfg.MinDigestSize = digestSize;
}
}
var keySizes = new List<ushort>();
var symDef = new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb);
var rsaParms = new RsaParms(symDef, null, 1024, 0);
IPublicParmsUnion parms = null;
if (TpmCfg.IsImplemented(TpmAlgId.Rsa))
{
// Find the smallest supported RSA size (currently checks only 1024 and 2048)
tpm._AllowErrors().TestParms(rsaParms);
if (!tpm._LastCommandSucceeded())
{
rsaParms.keyBits = 2048;
tpm._AllowErrors().TestParms(rsaParms);
if (!tpm._LastCommandSucceeded())
{
symDef.KeyBits = 256;
tpm._AllowErrors().TestParms(rsaParms);
if (!tpm._LastCommandSucceeded())
{
WriteToLog("WARNING: Unrecognized TPM algorithm configuration.\n" +
" No standard RSA/AES combinations found.\n" +
" Attempting to continue...", ConsoleColor.Cyan);
}
}
}
parms = rsaParms;
}
else
{
var curve = TpmCfg.IsImplemented(EccCurve.NistP256) ? EccCurve.NistP256 : TpmCfg.EccCurves.Keys.First();
parms = new EccParms(symDef, null, curve, new NullKdfScheme());
tpm._AllowErrors().TestParms(parms);
if (!tpm._LastCommandSucceeded())
{
symDef.KeyBits = 256;
parms = new EccParms(symDef, null, curve, new NullKdfScheme());
tpm._AllowErrors().TestParms(parms);
if (!tpm._LastCommandSucceeded())
{
WriteToLog("WARNING: Unrecognized TPM algorithm configuration.\n" +
" No RSA is supported and, no working ECC/AES combination found.\n" +
" Attempting to continue...", ConsoleColor.Cyan);
}
}