Пример #1
0
        static void ReadPcr()
        {
            Console.WriteLine("\nPCR sample started.");

            using (Tpm2Device tpmDevice = new TbsDevice())
            {
                tpmDevice.Connect();

                using (var tpm = new Tpm2(tpmDevice))
                {
                    var valuesToRead = new PcrSelection[]
                    {
                        new PcrSelection(TpmAlgId.Sha1, new uint[] { 1, 2 })
                    };

                    PcrSelection[] valsRead;
                    Tpm2bDigest[]  values;

                    tpm.PcrRead(valuesToRead, out valsRead, out values);

                    if (valsRead[0] != valuesToRead[0])
                    {
                        Console.WriteLine("Unexpected PCR-set");
                    }

                    var pcr1 = new TpmHash(TpmAlgId.Sha1, values[0].buffer);
                    Console.WriteLine("PCR1: " + pcr1);

                    var dataToExtend = new byte[] { 0, 1, 2, 3, 4 };
                    tpm.PcrEvent(TpmHandle.Pcr(1), dataToExtend);
                    tpm.PcrRead(valuesToRead, out valsRead, out values);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// This sample demonstrates how the caller can control simulated power, locality
        /// and physical-presence against the simulated TPM
        /// </summary>
        /// <param name="tpm">Reference to the TPM object.</param>
        static void PowerAndLocality(Tpm2 tpm)
        {
            //
            // Do a complete simulated clean power-down
            //
            tpm.Shutdown(Su.Clear);
            tpm._GetUnderlyingDevice().PowerCycle();
            tpm.Startup(Su.Clear);

            Console.WriteLine("Power cycle with TPM2_Startup(CLEAR) completed.");

            //
            // Now do a simulated hibernate
            //
            tpm.Shutdown(Su.State);
            tpm._GetUnderlyingDevice().PowerCycle();
            tpm.Startup(Su.State);

            Console.WriteLine("Power cycle with TPM2_Startup(STATE) completed.");

            //
            // Execute a command at locality 2
            //
            tpm._SetLocality(LocalityAttr.TpmLocTwo);
            tpm.PcrReset(TpmHandle.Pcr(21));
            tpm._SetLocality(LocalityAttr.TpmLocZero);

            Console.WriteLine("PCR[21] for locality 2 reset.");

            //
            // Execute a command that needs physical-presence
            //

            tpm._AssertPhysicalPresence()
            .PpCommands(TpmHandle.RhPlatform, new TpmCc[0], new TpmCc[0]);
            Console.WriteLine("Physical presence commands tested.");
        }
        public void TestTpmCollector()
        {
            var PcrAlgorithm = TpmAlgId.Sha256;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var process = TpmSim.GetTpmSimulator();
                process.Start();

                var  nvData  = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
                uint nvIndex = 3001;

                var tpmc = new TpmCollector(new CollectorOptions()
                {
                    Verbose = true
                }, null, TestMode: true);
                // Prepare to write to NV 3001
                TpmHandle nvHandle = TpmHandle.NV(nvIndex);

                TcpTpmDevice tcpTpmDevice = new TcpTpmDevice("127.0.0.1", 2321, stopTpm: false);
                tcpTpmDevice.Connect();

                using var tpm = new Tpm2(tcpTpmDevice);
                tcpTpmDevice.PowerCycle();
                tpm.Startup(Su.Clear);

                try
                {
                    tpm._AllowErrors()
                    .NvUndefineSpace(TpmRh.Owner, nvHandle);

                    tpm.NvDefineSpace(TpmRh.Owner, null,
                                      new NvPublic(nvHandle, TpmAlgId.Sha1,
                                                   NvAttr.NoDa | NvAttr.Ownerread | NvAttr.Ownerwrite,
                                                   null, 32));

                    // Write to NV 3001
                    tpm.NvWrite(TpmRh.Owner, nvHandle, nvData, 0);

                    var nvOut = tpm.NvRead(TpmRh.Owner, nvHandle, (ushort)nvData.Length, 0);

                    Assert.IsTrue(nvOut.SequenceEqual(nvData));
                }
                catch (TpmException e)
                {
                    Log.Debug(e, "Failed to Write to NV.");
                    Assert.Fail();
                }

                // Verify that all the PCRs are blank to start with
                var pcrs = TpmCollector.DumpPCRs(tpm, PcrAlgorithm, new PcrSelection[] { new PcrSelection(PcrAlgorithm, new uint[] { 15, 16 }) });
                Assert.IsTrue(pcrs.All(x => x.Value.SequenceEqual(new byte[x.Value.Length])));

                // Measure to PCR 16
                try
                {
                    tpm.PcrExtend(TpmHandle.Pcr(16), tpm.PcrEvent(TpmHandle.Pcr(16), nvData));
                }
                catch (TpmException e)
                {
                    Log.Debug(e, "Failed to Write PCR.");
                }

                // Verify that we extended the PCR
                var pcrs2 = TpmCollector.DumpPCRs(tpm, PcrAlgorithm, new PcrSelection[] { new PcrSelection(PcrAlgorithm, new uint[] { 15, 16 }, 24) });
                Assert.IsTrue(pcrs2[(PcrAlgorithm, 15)].SequenceEqual(pcrs[(PcrAlgorithm, 15)]));
Пример #4
0
        /// <summary>
        /// This sample demonstrates the use of the TPM Platform Configuration
        /// Registers (PCR). TSS.Net provides several features to model PCR
        /// semantics.
        /// </summary>
        /// <param name="tpm">Reference to the TPM object.</param>
        static void Pcrs(Tpm2 tpm)
        {
            Console.WriteLine("\nPCR sample started.");

            //
            // Read the value of the SHA1 PCR 1 and 2
            //
            var valuesToRead = new PcrSelection[]
            {
                new PcrSelection(TpmAlgId.Sha256, new uint[] { 1, 2 })
            };

            PcrSelection[] valsRead;
            Tpm2bDigest[]  values;

            tpm.PcrRead(valuesToRead, out valsRead, out values);

            //
            // Check that what we read is what we asked for (the TPM does not
            // guarantee this)
            //
            if (valsRead[0] != valuesToRead[0])
            {
                Console.WriteLine("Unexpected PCR-set");
            }

            //
            // Print out PCR-1
            //
            var pcr1 = new TpmHash(TpmAlgId.Sha256, values[0].buffer);

            Console.WriteLine("PCR1: " + pcr1);

            //
            // Extend (event) PCR[1] in the TPM and in the external library and
            // see if they match
            //
            var dataToExtend = new byte[] { 0, 1, 2, 3, 4 };

            //
            // Note that most PCR must be authorized with "null" authorization
            //
            tpm.PcrEvent(TpmHandle.Pcr(1), dataToExtend);

            //
            // And read the current value
            //
            tpm.PcrRead(valuesToRead, out valsRead, out values);

            //
            // Update the "simulated" PCR
            //
            pcr1.Event(dataToExtend);

            //
            // And see whether the PCR has the value we expect
            //
            if (pcr1 != values[0].buffer)
            {
                throw new Exception("Event did not work");
            }

            //
            // Update a resettable PCR
            //
            tpm.PcrEvent(TpmHandle.Pcr(16), new byte[] { 1, 2 });

            //
            // And reset it
            //
            tpm.PcrReset(TpmHandle.Pcr(16));

            //
            // And check that it is indeed zero
            //
            tpm.PcrRead(new PcrSelection[] {
                new PcrSelection(TpmAlgId.Sha256, new uint[] { 16 })
            },
                        out valsRead,
                        out values);

            //
            // Did it reset?
            //
            if (TpmHash.ZeroHash(TpmAlgId.Sha256) != values[0].buffer)
            {
                throw new Exception("PCR did not reset");
            }

            Console.WriteLine("PCR sample finished.");
        } // Pcrs
Пример #5
0
        /// <summary>
        /// This sample illustrates the use of a simple TPM policy session. The policy demands
        /// PCR 1, 2, 3 set to current values, and the command be issued at locality zero.
        /// </summary>
        static void SimplePolicy(Tpm2 tpm)
        {
            Console.WriteLine("Simple Policy sample:");

            //
            // Check if policy commands are implemented by TPM. This list
            // could include all the other used commands as well.
            // This check here makes sense for policy commands, because
            // usually a policy has to be executed in full. If a command
            // out of the chain of policy commands is not implemented in the
            // TPM, the policy cannot be satisfied.
            //
            var usedCommands = new[] { TpmCc.PolicyPCR };

            foreach (var commandCode in usedCommands)
            {
                if (!tpm.Helpers.IsImplemented(commandCode))
                {
                    Console.WriteLine("Cancel Simple Policy sample, because command {0} is not implemented by TPM.", commandCode);
                    return;
                }
            }

            //
            // First read the PCR values
            //
            var pcrs = new uint[] { 1, 2, 3 };
            var sel  = new PcrSelection(TpmAlgId.Sha, pcrs);

            PcrSelection[] selOut;
            Tpm2bDigest[]  pcrValues;

            tpm.PcrRead(new[] { sel }, out selOut, out pcrValues);

            Console.WriteLine("PCR Selections:\n");
            foreach (PcrSelection s in selOut)
            {
                Console.WriteLine(s.ToString());
            }

            Console.WriteLine("PCR Values:\n");
            foreach (var v in pcrValues)
            {
                Console.WriteLine(v.ToString());
            }

            //
            // Save the current PCR values in a convenient data structure
            //
            var expectedPcrVals = new PcrValueCollection(selOut, pcrValues);

            //
            // Tpm2Lib encapsulates a set of policy assertions as the PolicyTree class.
            //
            var policy = new PolicyTree(TpmAlgId.Sha256);

            //
            // Set the policy: Locality AND PolicyPcr. This form of CreatePOlicy
            // only creates a single chain. Note that all well-formed policy chains
            // must have leaf identifiers. Leaf identifiers are just strings that
            // are unique in a policy so that the framework can be told what
            // chain to evaluate.
            //
            policy.Create(
                new PolicyAce[]
            {
                new TpmPolicyPcr(expectedPcrVals),
                "leaf"
            }
                );

            //
            // Ask Tpm2Lib for the expected policy-hash for this policy
            //
            TpmHash expectedPolicyHash = policy.GetPolicyDigest();

            //
            // Create a sealed primary object with the policy-hash we just calculated
            //
            var       dataToSeal = new byte[] { 1, 2, 3, 4, 5, 4, 3, 2, 1 };
            TpmHandle primHandle = CreateSealedPrimaryObject(tpm,
                                                             dataToSeal,
                                                             null,
                                                             expectedPolicyHash.HashData);
            //
            // Create an actual TPM policy session to evaluate the policy
            //
            AuthSession session = tpm.StartAuthSessionEx(TpmSe.Policy, TpmAlgId.Sha256);

            //
            // Run the policy on the TPM
            //
            session.RunPolicy(tpm, policy, "leaf");

            //
            // Unseal the object
            //
            byte[] unsealedData = tpm[session].Unseal(primHandle);
            Console.WriteLine("Unsealed data: " + BitConverter.ToString(unsealedData));

            //
            // Change a PCR and make sure that the policy no longer works
            //
            var nullAuth = new AuthValue();

            tpm[nullAuth].PcrEvent(TpmHandle.Pcr(3), new byte[] { 1, 2, 3 });
            tpm.PolicyRestart(session.Handle);

            //
            // Run the policy again - an error will be returned
            //
            TpmRc policyError = session.RunPolicy(tpm, policy, null, true);

            //
            // And the session will be unusable
            //
            unsealedData = tpm[session]._ExpectError(TpmRc.PolicyFail).Unseal(primHandle);

            //
            // Clean up
            //
            tpm.FlushContext(session.Handle);
            tpm.FlushContext(primHandle);
        }