/// <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[_nullAuth].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(true); tpm[_nullAuth].PpCommands(TpmHandle.RhPlatform, new TpmCc[0], new TpmCc[0]); tpm._AssertPhysicalPresence(false); Console.WriteLine("Physical presence commands tested."); }
/// <summary> /// Illustrates various cases of automatic authorization handling. /// </summary> static void AutomaticAuth(Tpm2 tpm) { TpmHandle primHandle = CreateRsaPrimaryKey(tpm); TpmPublic keyPublic; TpmHandle keyHandle = CreateSigningDecryptionKey(tpm, primHandle, out keyPublic); byte[] message = Globs.GetRandomBytes(32); IAsymSchemeUnion decScheme = new SchemeOaep(TpmAlgId.Sha1); ISigSchemeUnion sigScheme = new SchemeRsassa(TpmAlgId.Sha1); byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, new byte[0]); Console.WriteLine("Automatic authorization of a decryption key."); // // An auth session is added automatically when TPM object is not in strict mode. // byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, new byte[0]); byte[] nonceTpm; Console.WriteLine("Session object construction."); // // If a session with specific properties is required, an AuthSession object // can be built from the session handle returned by the TPM2_StartAuthSession // command concatenated, if necessary, with session flags and unencrypted salt // value (not used in this example). // AuthSession auditSess = tpm.StartAuthSession( TpmRh.Null, // no salt TpmRh.Null, // no bind object Globs.GetRandomBytes(16), // nonceCaller new byte[0], // no salt TpmSe.Hmac, // session type new SymDef(), // no encryption/decryption TpmAlgId.Sha256, // authHash out nonceTpm) + (SessionAttr.ContinueSession | SessionAttr.Audit); /* * Alternatively one of the StartAuthSessionEx helpers can be used). E.g. * * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256, * SessionAttr.ContinueSession | SessionAttr.Audit); */ // // TSS.Net specific call to verify TPM auditing correctness. // tpm._SetCommandAuditAlgorithm(TpmAlgId.Sha256); Console.WriteLine("Automatic authorization using explicitly created session object."); // // Appropriate auth value is added automatically into the provided session. // byte[] decrypted2 = tpm[auditSess]._Audit() .RsaDecrypt(keyHandle, encrypted, decScheme, new byte[0]); ISignatureUnion signature; Attest attest; // // A session is added automatically to authorize usage of the permanent // handle TpmRh.Endorsement. // // Note that if auth value of TpmRh.Endorsement is not empty, you need to // explicitly assign it to the tpm.EndorsementAuth property of the given // Tpm2 object. // attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, new byte[0], new NullSigScheme(), out signature); // // But if the corresponding auth value stored in the Tpm2 object is invalid, ... // AuthValue endorsementAuth = tpm.EndorsementAuth; tpm.EndorsementAuth = Globs.ByteArray(16, 0xde); // // ... the command will fail. // tpm._ExpectError(TpmRc.BadAuth) .GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, new byte[0], new NullSigScheme(), out signature); // // Restore correct auth value. // tpm.EndorsementAuth = endorsementAuth; // // Verify that decryption worked correctly. // Debug.Assert(Globs.ArraysAreEqual(decrypted1, decrypted2)); // // Verify that auditing worked correctly. // SessionAuditInfo info = (SessionAuditInfo)attest.attested; Debug.Assert(Globs.ArraysAreEqual(info.sessionDigest, tpm._GetAuditHash().HashData)); Console.WriteLine("Auth value tracking by TSS.Net."); // // Change auth value of the decryption key. // TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, primHandle, AuthValue.FromRandom(16)); TpmHandle newKeyHandle = tpm.Load(primHandle, newKeyPrivate, keyPublic); // // Allow non-exclusive usage of the audit session. // auditSess.Attrs &= ~SessionAttr.AuditExclusive; // // Correct auth value (corresponding to newKeyHandle, and different from // the one used for keyHandle) will be added to auditSess. // decrypted1 = tpm[auditSess]._Audit() .RsaDecrypt(newKeyHandle, encrypted, decScheme, new byte[0]); Console.WriteLine("Automatic authorization with multiple sessions."); // // Now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle). // attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, new byte[0], sigScheme, out signature); // // Verify that the previous command worked correctly. // bool sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest), signature, TpmAlgId.Sha1); Debug.Assert(sigOk); // // In the following example the first session is generated based on session // type indicator (Auth.Pw), and the second one is added automatically. // attest = tpm[Auth.Pw].GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, new byte[0], sigScheme, out signature); // // Verify that the previous command worked correctly. // sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest), signature, TpmAlgId.Sha1); Debug.Assert(sigOk); // // Release TPM resources that we do not need anymore. // tpm.FlushContext(newKeyHandle); tpm.FlushContext(auditSess); // // The following example works correctly only when TPM resource management // is not enabled (e.g. with TPM simulator, or when actual TPM is in raw mode). // if (!tpm._GetUnderlyingDevice().HasRM()) { Console.WriteLine("Using session type indicators."); // // Deplete TPM's active session storage // List<AuthSession> landfill = new List<AuthSession>(); for (;;) { tpm._AllowErrors(); AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256, SessionAttr.ContinueSession); if (!tpm._LastCommandSucceeded()) { break; } landfill.Add(s); } // // Check if session type indicators are processed correctly // tpm[Auth.Hmac]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); // // Password authorization protocol session uses a predefined handle value, // so it must work even when there are no free session slots in the TPM. // tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); // // Check if default session type defined by the TPM device is processed correctly. // bool needHmac = tpm._GetUnderlyingDevice().NeedsHMAC; tpm._GetUnderlyingDevice().NeedsHMAC = true; tpm._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); tpm._GetUnderlyingDevice().NeedsHMAC = false; tpm.RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), new byte[0]); tpm._GetUnderlyingDevice().NeedsHMAC = needHmac; landfill.ForEach(s => tpm.FlushContext(s)); } // // Release TPM resources. // tpm.FlushContext(keyHandle); tpm.FlushContext(primHandle); Console.WriteLine("Done."); }
/// <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(); }