Exemple #1
0
        /// <summary>
        /// Executes the hashing functionality. After parsing arguments, the 
        /// function connects to the selected TPM device and invokes the TPM
        /// commands on that connection.
        /// </summary>
        static void Main()
        {
            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                //
                // Connect to the TPM device. This function actually establishes the
                // connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);

                //
                // If we are using the simulator, we have to do a few things the
                // firmware would usually do. These actions have to occur after
                // the connection has been established.
                // 
                tpmDevice.PowerCycle();
                tpm.Startup(Su.Clear);

                ResetDALogic(tpm);
                ResourceManager(tpm);
                PowerAndLocality(tpm);

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");
            Console.ReadLine();
        }
Exemple #2
0
        public void Destroy()
        {
            TpmHandle nvHandle = new TpmHandle(AIOTH_PERSISTED_URI_INDEX + logicalDeviceId);
            TpmHandle ownerHandle = new TpmHandle(TpmRh.Owner);
            TpmHandle hmacKeyHandle = new TpmHandle(AIOTH_PERSISTED_KEY_HANDLE + logicalDeviceId);

            // Open the TPM
            Tpm2Device tpmDevice = new TbsDevice();
            tpmDevice.Connect();
            var tpm = new Tpm2(tpmDevice);

            // Destyroy the URI
            tpm.NvUndefineSpace(ownerHandle, nvHandle);

            // Destroy the HMAC key
            tpm.EvictControl(ownerHandle, hmacKeyHandle, hmacKeyHandle);

            // Dispose of the TPM
            tpm.Dispose();
        }
Exemple #3
0
        /// <summary>
        /// Executes the GetRandom functionality. After parsing arguments, the function
        /// connects to the selected TPM device and invokes the GetRandom command on
        /// that connection. If the command was successful, the random byte stream
        /// is displayed.
        /// </summary>
        /// <param name="args">Arguments to this program.</param>
        static void Main(string[] args)
        {
            //
            // Parse the program arguments. If the wrong arguments are given or
            // are malformed, then instructions for usage are displayed and 
            // the program terminates.
            // 
            string tpmDeviceName;
            ushort bytesRequested;
            if (!ParseArguments(args, out tpmDeviceName, out bytesRequested))
            {
                WriteUsage();
                return;
            }

            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice;
                switch (tpmDeviceName)
                {
                    case DeviceSimulator:
                        tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                        break;

                    case DeviceWinTbs:
                        tpmDevice = new TbsDevice();
                        break;

                    default:
                        throw new Exception("Unknown device selected.");
                }

                //
                // Connect to the TPM device. This function actually establishes the
                // connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);
                if (tpmDevice is TcpTpmDevice)
                {
                    //
                    // If we are using the simulator, we have to do a few things the
                    // firmware would usually do. These actions have to occur after
                    // the connection has been established.
                    // 
                    tpmDevice.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                //
                // Execute the TPM2_GetRandom command. The function takes the requested
                // number of bytes as input and returns the random bytes generated by
                // the TPM.
                // 
                byte[] randomBytes = tpm.GetRandom(bytesRequested);

                //
                // Output the generated random byte string to the console.
                // 
                WriteBytes(randomBytes);

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");
            Console.ReadLine();
        }
Exemple #4
0
        /// <summary>
        /// Executes the GetCapabilities functionality. After parsing arguments, the 
        /// function connects to the selected TPM device and invokes the GetCapabilities
        /// command on that connection. If the command was successful, the retrieved
        /// capabilities are displayed.
        /// </summary>
        /// <param name="args">Arguments to this program.</param>
        static void Main(string[] args)
        {
            //
            // Parse the program arguments. If the wrong arguments are given or
            // are malformed, then instructions for usage are displayed and 
            // the program terminates.
            // 
            string tpmDeviceName;
            if (!ParseArguments(args, out tpmDeviceName))
            {
                WriteUsage();
                return;
            }

            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice;
                switch (tpmDeviceName)
                {
                    case DeviceSimulator:
                        tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                        break;

                    case DeviceWinTbs:
                        tpmDevice = new TbsDevice();
                        break;

                    default:
                        throw new Exception("Unknown device selected.");
                }

                //
                // Connect to the TPM device. This function actually establishes the
                // connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);
                if (tpmDevice is TcpTpmDevice)
                {
                    //
                    // If we are using the simulator, we have to do a few things the
                    // firmware would usually do. These actions have to occur after
                    // the connection has been established.
                    // 
                    tpmDevice.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                //
                // Query different capabilities
                // 

                ICapabilitiesUnion caps;
                tpm.GetCapability(Cap.Algs, 0, 1000, out caps);
                var algsx = (AlgPropertyArray)caps;

                Console.WriteLine("Supported algorithms:");
                foreach (var alg in algsx.algProperties)
                {
                    Console.WriteLine("  {0}", alg.alg.ToString());
                }

                Console.WriteLine("Supported commands:");
                tpm.GetCapability(Cap.TpmProperties, (uint)Pt.TotalCommands, 1, out caps);
                tpm.GetCapability(Cap.Commands, (uint)TpmCc.First + 1, TpmCc.Last - TpmCc.First + 1, out caps);

                var commands = (CcaArray)caps;
                List<TpmCc> implementedCc = new List<TpmCc>();
                foreach (var attr in commands.commandAttributes)
                {
                    var commandCode = (TpmCc)((uint)attr & 0x0000FFFFU);
                    //
                    // Filter placehoder(s)
                    //
                    if(commandCode == TpmCc.None)
                    {
                        continue;
                    }
                    implementedCc.Add(commandCode);
                    Console.WriteLine("  {0}", commandCode.ToString());
                }
                Console.WriteLine("Commands from spec not implemented:");
                foreach (var cc in Enum.GetValues(typeof(TpmCc)))
                {
                    if (!implementedCc.Contains((TpmCc)cc) &&
                        //
                        // Fiter placeholder(s)
                        //
                        ((TpmCc)cc != TpmCc.None) &&
                        ((TpmCc)cc != TpmCc.First) &&
                        ((TpmCc)cc != TpmCc.Last) )
                    {
                        Console.WriteLine("  {0}", cc.ToString());
                    }
                }

                //
                // As an alternative: call GetCapabilities more than once to obtain all values
                //
                byte more;
                var firstCommandCode = (uint)TpmCc.None;
                do
                {
                    more = tpm.GetCapability(Cap.Commands, firstCommandCode, 10, out caps);
                    commands = (CcaArray)caps;
                    //
                    // Commands are sorted; getting the last element as it will be the largest.
                    //
                    uint lastCommandCode = (uint)commands.commandAttributes[commands.commandAttributes.Length - 1] & 0x0000FFFFU;
                    firstCommandCode = lastCommandCode;
                } while (more == 1);

                //
                // Read PCR attributes. Cap.Pcrs returns the list of PCRs which are supported
                // in different PCR banks. The PCR banks are identified by the hash algorithm
                // used to extend values into the PCRs of this bank.
                // 
                tpm.GetCapability(Cap.Pcrs, 0, 255, out caps);
                PcrSelection[] pcrs = ((PcrSelectionArray)caps).pcrSelections;

                Console.WriteLine();
                Console.WriteLine("Available PCR banks:");
                foreach (PcrSelection pcrBank in pcrs)
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("PCR bank for algorithm {0} has registers at index:", pcrBank.hash);
                    sb.AppendLine();
                    foreach (uint selectedPcr in pcrBank.GetSelectedPcrs())
                    {
                        sb.AppendFormat("{0},", selectedPcr);
                    }
                    Console.WriteLine(sb);
                }

                //
                // Read PCR attributes. Cap.PcrProperties checks for certain properties of each PCR register.
                // 
                tpm.GetCapability(Cap.PcrProperties, 0, 255, out caps);

                Console.WriteLine();
                Console.WriteLine("PCR attributes:");                
                TaggedPcrSelect[] pcrProperties = ((TaggedPcrPropertyArray)caps).pcrProperty;
                foreach (TaggedPcrSelect pcrProperty in pcrProperties)
                {
                    if ((PtPcr)pcrProperty.tag == PtPcr.None)
                    {
                        continue;
                    }

                    uint pcrIndex = 0;
                    var sb = new StringBuilder();
                    sb.AppendFormat("PCR property {0} supported by these registers: ", (PtPcr)pcrProperty.tag);
                    sb.AppendLine();
                    foreach (byte pcrBitmap in pcrProperty.pcrSelect)
                    {
                        for (int i = 0; i < 8; i++)
                        {
                            if ((pcrBitmap & (1 << i)) != 0)
                            {
                                sb.AppendFormat("{0},", pcrIndex);
                            }
                            pcrIndex++;
                        }
                    }
                    Console.WriteLine(sb);
                }

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");
            Console.ReadLine();
        }
Exemple #5
0
        private void button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                Tpm2Device tpmDevice = new TbsDevice();
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);

                NVReadWrite(tpm);
                NVCounter(tpm);

                tpm.Dispose();
            }
            catch (Exception ex)
            {
                this.textBlock.Text = "Exception occurred: " + ex.Message;
            }
        }
Exemple #6
0
        /// <summary>
        /// Executes the hashing functionality. After parsing arguments, the 
        /// function connects to the selected TPM device and invokes the TPM
        /// commands on that connection.
        /// </summary>
        /// <param name="args">Arguments to this program.</param>
        static void Main(string[] args)
        {
            //
            // Parse the program arguments. If the wrong arguments are given or
            // are malformed, then instructions for usage are displayed and 
            // the program terminates.
            // 
            string tpmDeviceName;
            if (!ParseArguments(args, out tpmDeviceName))
            {
                WriteUsage();
                return;
            }

            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice;
                switch (tpmDeviceName)
                {
                    case DeviceSimulator:
                        tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                        break;

                    case DeviceWinTbs:
                        tpmDevice = new TbsDevice();
                        break;

                    default:
                        throw new Exception("Unknown device selected.");
                }

                //
                // Connect to the TPM device. This function actually establishes the
                // connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);
                if (tpmDevice is TcpTpmDevice)
                {
                    //
                    // If we are using the simulator, we have to do a few things the
                    // firmware would usually do. These actions have to occur after
                    // the connection has been established.
                    // 
                    tpmDevice.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                Pcrs(tpm);
                QuotePcrs(tpm);
                StorageRootKey(tpm);
                //
                // Need a synchronization event to avoid disposing TPM object before
                // asynchronous method completed.
                // 
                var sync = new AutoResetEvent(false);
                Console.WriteLine("Calling asynchronous method.");
                PrimarySigningKeyAsync(tpm, sync);

                Console.WriteLine("Waiting for asynchronous method to complete.");
                sync.WaitOne();

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");
            Console.ReadLine();
        }
Exemple #7
0
        /// <summary>
        /// This sample demonstrates the creation of a signing "primary" key and use of this
        /// key to sign data, and use of the TPM and Tpm2Lib to validate the signature.
        /// </summary>
        /// <param name="args">Arguments to this program.</param>
        static void Main(string[] args)
        {
            string tpmDeviceName;

            //
            // Parse the program arguments. If the wrong arguments are given or
            // are malformed, then instructions for usage are displayed and 
            // the program terminates.
            // 
            if (!ParseArguments(args, out tpmDeviceName))
            {
                WriteUsage();
                return;
            }

            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice;
                switch (tpmDeviceName)
                {
                    case DeviceSimulator:
                        tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                        break;

                    case DeviceWinTbs:
                        tpmDevice = new TbsDevice();
                        break;

                    default:
                        throw new Exception("Unknown device selected.");
                }

                //
                // Connect to the TPM device. This function actually establishes the connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);
                if (tpmDevice is TcpTpmDevice)
                {
                    //
                    // If we are using the simulator, we have to do a few things the
                    // firmware would usually do. These actions have to occur after
                    // the connection has been established.
                    // 
                    tpmDevice.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                //
                // Run individual tests.
                // 
                SimplePolicy(tpm);
                PolicyOr(tpm);
                PolicySerialization();
                PolicyEvaluationWithCallback(tpm);
                PolicyEvaluationWithCallback2(tpm);
                SamplePolicySerializationAndCallbacks(tpm);

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (TpmException e)
            {
                //
                // If a command fails because an unexpected return code is in the response,
                // i.e., TPM returns an error code where success is expected or success
                // where an error code is expected. Or if the response is malformed, then
                // the unmarshaling code will throw a TPM exception.
                // The Error string will contain a description of the return code. Usually the
                // return code will be a known TPM return code. However, if using the TPM through
                // TBS, TBS might encode internal error codes into the response code. For instance
                // a return code of 0x80280400 indicates that a command is blocked by TBS. This
                // error code is also returned if the command is not implemented by the TPM.
                // 
                // You can see the information included in the TPM exception by removing the
                // checks for available TPM commands above and running the sample on a TPM
                // without the required commands.
                // 
                Console.WriteLine("TPM exception occurred: {0}", e.ErrorString);
                Console.WriteLine("Call stack: {0}", e.StackTrace);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");

            Console.ReadLine();
        }
Exemple #8
0
        /// <summary>
        /// This sample demonstrates the creation of a signing "primary" key and use of this
        /// key to sign data, and use of the TPM and Tpm2Lib to validate the signature.
        /// </summary>
        /// <param name="args">Arguments to this program.</param>
        static void Main(string[] args)
        {
            //
            // Parse the program arguments. If the wrong arguments are given or
            // are malformed, then instructions for usage are displayed and 
            // the program terminates.
            // 
            string tpmDeviceName;
            if (!ParseArguments(args, out tpmDeviceName))
            {
                WriteUsage();
                return;
            }

            try
            {
                //
                // Create the device according to the selected connection.
                // 
                Tpm2Device tpmDevice;
                switch (tpmDeviceName)
                {
                    case DeviceSimulator:
                        tpmDevice = new TcpTpmDevice(DefaultSimulatorName, DefaultSimulatorPort);
                        break;

                    case DeviceWinTbs:
                        tpmDevice = new TbsDevice();
                        break;

                    default:
                        throw new Exception("Unknown device selected.");
                }
                //
                // Connect to the TPM device. This function actually establishes the
                // connection.
                // 
                tpmDevice.Connect();

                //
                // Pass the device object used for communication to the TPM 2.0 object
                // which provides the command interface.
                // 
                var tpm = new Tpm2(tpmDevice);
                if (tpmDevice is TcpTpmDevice)
                {
                    //
                    // If we are using the simulator, we have to do a few things the
                    // firmware would usually do. These actions have to occur after
                    // the connection has been established.
                    // 
                    tpmDevice.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                //
                // AuthValue encapsulates an authorization value: essentially a byte-array.
                // OwnerAuth is the owner authorization value of the TPM-under-test.  We
                // assume that it (and other) auths are set to the default (null) value.
                // If running on a real TPM, which has been provisioned by Windows, this
                // value will be different. An administrator can retrieve the owner
                // authorization value from the registry.
                //
                var ownerAuth = new AuthValue();

                // 
                // The TPM needs a template that describes the parameters of the key
                // or other object to be created.  The template below instructs the TPM 
                // to create a new 2048-bit non-migratable signing key.
                // 
                var keyTemplate = new TpmPublic(TpmAlgId.Sha1,                                  // Name algorithm
                                                ObjectAttr.UserWithAuth | ObjectAttr.Sign |     // Signing key
                                                ObjectAttr.FixedParent  | ObjectAttr.FixedTPM | // Non-migratable 
                                                ObjectAttr.SensitiveDataOrigin,
                                                new byte[0],                                    // No policy
                                                new RsaParms(new SymDefObject(), 
                                                             new SchemeRsassa(TpmAlgId.Sha1), 2048, 0),
                                                new Tpm2bPublicKeyRsa());

                // 
                // Authorization for the key we are about to create.
                // 
                var keyAuth = new byte[] { 1, 2, 3 };

                TpmPublic keyPublic;
                CreationData creationData;
                TkCreation creationTicket;
                byte[] creationHash;

                // 
                // Ask the TPM to create a new primary RSA signing key.
                // 
                TpmHandle keyHandle = tpm[ownerAuth].CreatePrimary(
                    TpmHandle.RhOwner,                          // In the owner-hierarchy
                    new SensitiveCreate(keyAuth, new byte[0]),  // With this auth-value
                    keyTemplate,                                // Describes key
                    new byte[0],                                // For creation ticket
                    new PcrSelection[0],                        // For creation ticket
                    out keyPublic,                              // Out pubKey and attributes
                    out creationData, out creationHash,         // Not used here
                    out creationTicket);

                // 
                // Print out text-versions of the public key just created
                // 
                Console.WriteLine("New public key\n" + keyPublic.ToString());

                // 
                // Use the key to sign some data
                // 
                byte[] message = Encoding.Unicode.GetBytes("ABC");
                TpmHash dataToSign = TpmHash.FromData(TpmAlgId.Sha1, message);

                // 
                // A different structure is returned for each signing scheme, 
                // so cast the interface to our signature type (see third argument).
                // 
                // As an alternative, 'signature' can be of type ISignatureUnion and
                // cast to SignatureRssa whenever a signature specific type is needed.
                // 
                var signature = tpm[keyAuth].Sign(keyHandle,                       // Handle of signing key
                                                  dataToSign.HashData,             // Data to sign
                                                  new SchemeRsassa(TpmAlgId.Sha1), // Default scheme
                                                  TpmHashCheck.NullHashCheck()) as SignatureRsassa;
                // 
                // Print the signature.
                // 
                Console.WriteLine("Signature: " + BitConverter.ToString(signature.sig));

                // 
                // Use the TPM library to validate the signature
                // 
                bool sigOk = keyPublic.VerifySignatureOverData(message, signature);
                if (!sigOk)
                {
                    throw new Exception("Signature did not validate.");
                }

                Console.WriteLine("Verified signature with TPM2lib (software implementation).");

                // 
                // Load the public key into another slot in the TPM and then 
                // use the TPM to validate the signature
                // 
                TpmHandle pubHandle = tpm.LoadExternal(null, keyPublic, TpmHandle.RhOwner);
                tpm.VerifySignature(pubHandle, dataToSign.HashData, signature);
                Console.WriteLine("Verified signature with TPM.");

                // 
                // The default behavior of Tpm2Lib is to create an exception if the 
                // signature does not validate. If an error is expected the library can 
                // be notified of this, or the exception can be turned into a value that
                // can be later queried. The following are examples of this.
                // 
                signature.sig[0] ^= 1;
                tpm._ExpectError(TpmRc.Signature).VerifySignature(pubHandle, dataToSign.HashData, signature);

                tpm._AllowErrors().VerifySignature(pubHandle, dataToSign.HashData, signature);
                if (tpm._GetLastResponseCode() != TpmRc.Signature)
                {
                    throw new Exception("TPM returned unexpected return code.");
                }

                Console.WriteLine("Verified that invalid signature causes TPM_RC_SIGNATURE return code.");

                // 
                // Clean up of used handles.
                // 
                tpm.FlushContext(keyHandle);
                tpm.FlushContext(pubHandle);

                // 
                // (Note that serialization is not supported on WinRT)
                // 
                // Demonstrate the use of XML persistence by saving keyPublic to 
                // a file and making a copy by reading it back into a new object
                // 
                // NOTE: 12-JAN-2016: May be removing support for policy
                //       serialization. We'd like to get feedback on whether
                //       this is a desirable feature and should be retained.
                //
                // {
                //     const string fileName = "sample.xml";
                //     string xmlVersionOfObject = keyPublic.GetXml();
                //     keyPublic.XmlSerializeToFile(fileName);
                //     var copyOfPublic = TpmStructureBase.XmlDeserializeFromFile<TpmPublic>(fileName);
                //     
                //     // 
                //     // Demonstrate Tpm2Lib support of TPM-structure equality operators
                //     // 
                //     if (copyOfPublic != keyPublic)
                //     {
                //         Console.WriteLine("Library bug persisting data.");
                //     }
                // }
                //

                //
                // Clean up.
                // 
                tpm.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred: {0}", e.Message);
            }

            Console.WriteLine("Press Any Key to continue.");
            Console.ReadLine();
        }
Exemple #9
0
        /// <summary>
        /// This sample illustrates the use of the resource manager built into 
        /// Tpm2Lib.  Using the resource manager relieves the programmer of the 
        /// (sometimes burdensome) chore of juggling a small number of TPM slots
        /// </summary>
        /// <param name="tpm">Reference to the TPM object.</param>
        static void ResourceManager(Tpm2 tpm)
        {
            //
            // The Tbs device class has a built-in resource manager. We create an
            // instance of the Tbs device class, but hook it up to the TCP device
            // created above. We also tell the Tbs device class to clean the TPM
            // before we start using it.
            // This sample won't work on top of the default Windows resource manager
            // (TBS).
            // 
            var tbs = new Tbs(tpm._GetUnderlyingDevice(), false);
            var tbsTpm = new Tpm2(tbs.CreateTbsContext());

            //
            // Make more sessions than the TPM has room for
            // 
            const int count = 32;
            var sessions = new AuthSession[count];
            for (int j = 0; j < count; j++)
            {
                sessions[j] = tbsTpm.StartAuthSessionEx(TpmSe.Policy, TpmAlgId.Sha1);
            }

            Console.WriteLine("Created {0} sessions.", count);

            //
            // And now use them. The resource manager will use ContextLoad and 
            // ContextSave to bring them into the TPM
            // 
            for (int j = 0; j < count; j++)
            {
                tbsTpm.PolicyAuthValue(sessions[j].Handle);
            }

            Console.WriteLine("Used {0} sessions.", count);

            //
            // And now clean up
            // 
            for (int j = 0; j < count; j++)
            {
                tbsTpm.FlushContext(sessions[j].Handle);
            }

            Console.WriteLine("Cleaned up.");

            //
            // Dispose of the Tbs device object.
            // 
            tbsTpm.Dispose();
        }
Exemple #10
0
        public string GetHardwareDeviceId()
        {
            TpmHandle srkHandle = new TpmHandle(SRK_HANDLE);
            string hardwareDeviceId = "";
            Byte[] name;
            Byte[] qualifiedName;

            try
            {
                // Open the TPM
                Tpm2Device tpmDevice = new TbsDevice();
                tpmDevice.Connect();
                var tpm = new Tpm2(tpmDevice);

                // Read the URI from the TPM
                TpmPublic srk = tpm.ReadPublic(srkHandle, out name, out qualifiedName);

                // Dispose of the TPM
                tpm.Dispose();
            }
            catch
            {
                return hardwareDeviceId;
            }

            // Calculate the hardware device id for this logical device
            byte[] deviceId = CryptoLib.HashData(TpmAlgId.Sha256, BitConverter.GetBytes(logicalDeviceId), name);

            // Produce the output string
            foreach (byte n in deviceId)
            {
                hardwareDeviceId += n.ToString("x2");
            }
            return hardwareDeviceId;
        }
Exemple #11
0
        private string GetHeldData()
        {
            TpmHandle nvUriHandle = new TpmHandle(AIOTH_PERSISTED_URI_INDEX + logicalDeviceId);
            Byte[] nvData;
            string iotHubUri = "";

            try
            {
                // Open the TPM
                Tpm2Device tpmDevice = new TbsDevice();
                tpmDevice.Connect();
                var tpm = new Tpm2(tpmDevice);

                // Read the URI from the TPM
                Byte[] name;
                NvPublic nvPublic = tpm.NvReadPublic(nvUriHandle, out name);
                nvData = tpm.NvRead(nvUriHandle, nvUriHandle, nvPublic.dataSize, 0);

                // Dispose of the TPM
                tpm.Dispose();
            }
            catch
            {
                return iotHubUri;
            }

            // Convert the data to a srting for output
            iotHubUri = System.Text.Encoding.UTF8.GetString(nvData);
            return iotHubUri;
        }
Exemple #12
0
        public Byte[] SignHmac(Byte[] dataToSign)
        {
            TpmHandle hmacKeyHandle = new TpmHandle(AIOTH_PERSISTED_KEY_HANDLE + logicalDeviceId);
            int dataIndex = 0;
            Byte[] iterationBuffer;
            Byte[] hmac = { };

            if (dataToSign.Length <= 1024)
            {
                try
                {
                    // Open the TPM
                    Tpm2Device tpmDevice = new TbsDevice();
                    tpmDevice.Connect();
                    var tpm = new Tpm2(tpmDevice);

                    // Calculate the HMAC in one shot
                    hmac = tpm.Hmac(hmacKeyHandle, dataToSign, TpmAlgId.Sha256);

                    // Dispose of the TPM
                    tpm.Dispose();
                }
                catch
                {
                    return hmac;
                }
            }
            else
            {
                try
                {
                    // Open the TPM
                    Tpm2Device tpmDevice = new TbsDevice();
                    tpmDevice.Connect();
                    var tpm = new Tpm2(tpmDevice);

                    // Start the HMAC sequence
                    Byte[] hmacAuth = new byte[0];
                    TpmHandle hmacHandle = tpm.HmacStart(hmacKeyHandle, hmacAuth, TpmAlgId.Sha256);
                    while (dataToSign.Length > dataIndex + 1024)
                    {
                        // Repeat to update the hmac until we only hace <=1024 bytes left
                        iterationBuffer = new Byte[1024];
                        Array.Copy(dataToSign, dataIndex, iterationBuffer, 0, 1024);
                        tpm.SequenceUpdate(hmacHandle, iterationBuffer);
                        dataIndex += 1024;
                    }
                    // Finalize the hmac with the remainder of the data
                    iterationBuffer = new Byte[dataToSign.Length - dataIndex];
                    Array.Copy(dataToSign, dataIndex, iterationBuffer, 0, dataToSign.Length - dataIndex);
                    TkHashcheck nullChk;
                    hmac = tpm.SequenceComplete(hmacHandle, iterationBuffer, TpmHandle.RhNull, out nullChk);

                    // Dispose of the TPM
                    tpm.Dispose();
                }
                catch
                {
                    return hmac;
                }
            }

            return hmac;
        }