예제 #1
0
        void DuplicateImportRsaSample(Tpm2 tpm, TestContext testCtx)
        {
            TpmAlgId nameAlg = Substrate.Random(TpmCfg.HashAlgs);
            var      policy  = new PolicyTree(nameAlg);

            policy.SetPolicyRoot(new TpmPolicyCommand(TpmCc.Duplicate));

            var inPub = new TpmPublic(nameAlg,
                                      ObjectAttr.Sign | ObjectAttr.AdminWithPolicy | ObjectAttr.SensitiveDataOrigin,
                                      policy.GetPolicyDigest(),
                                      new RsaParms(new SymDefObject(),
                                                   new SchemeRsassa(Substrate.Random(TpmCfg.HashAlgs)),
                                                   Substrate.Random(TpmCfg.RsaKeySizes), 0),
                                      new Tpm2bPublicKeyRsa());

            TpmHandle hKey = Substrate.CreateAndLoad(tpm, inPub, out TpmPublic pub);

            // Duplicate
            TpmPrivate priv = TpmHelper.GetPlaintextPrivate(tpm, hKey, policy);

            tpm.FlushContext(hKey);

            // Import
            TpmPrivate privImp = tpm.Import(Substrate.LoadRsaPrimary(tpm), null, pub, priv, null, new SymDefObject());
        } // SimpleDuplicateImportRsaSample
예제 #2
0
        } // SimpleDuplicateImportRsaSample

        TssObject ImportExternalRsaKey(Tpm2 tpm, TpmHandle hParent,
                                       int keySizeInBits, IAsymSchemeUnion scheme,
                                       byte[] publicPart, byte[] privatePart,
                                       ObjectAttr keyAttrs,
                                       byte[] authVal = null, byte[] policyDigest = null)
        {
            TpmAlgId sigHashAlg = TpmHelper.GetSchemeHash(scheme),
                     nameAlg    = sigHashAlg;

            // TPM signing key template with the actual public key bits
            var inPub = new TpmPublic(nameAlg,
                                      keyAttrs,
                                      policyDigest,
                                      new RsaParms(new SymDefObject(), scheme as IAsymSchemeUnion,
                                                   (ushort)keySizeInBits, 0),
                                      new Tpm2bPublicKeyRsa(publicPart));

            // Wrap the key in a TSS helper class
            TssObject swKey = TssObject.Create(inPub, authVal, privatePart);

            // Get a key duplication blob in TPM 2.0 compatibale format
            TpmPrivate dupBlob = swKey.GetPlaintextDuplicationBlob();

            // Importing a duplication blob creates a new TPM private key blob protected
            // with its new parent key.
            swKey.Private = tpm.Import(hParent, null, swKey.Public, dupBlob, null, new SymDefObject());

            return(swKey);
        } // ImportExternalRsaKey
예제 #3
0
        private static string CalculateHmacStringTpm(string value)
        {
            byte[] valueByteArray = Encoding.UTF8.GetBytes(value);

            byte[] hmacByteArray = TpmHelper.CalculateHmac(valueByteArray);
            return(Convert.ToBase64String(hmacByteArray));
        }
예제 #4
0
        static void Main(string[] args)
        {
            string secret             = "";
            string stringToBeCyphered = "LaMiaStringaDaCifrare";

            while (true)
            {
                Console.WriteLine("Premere: \nW per scrivere il segreto,\nR per leggere il segreto da TPM,\nH per calcolare HMAC,\nT per calcolare HMAC con TPM\n");
                var operation = Console.ReadKey(true);

                if (operation.Key == ConsoleKey.W)
                {
                    Console.WriteLine("Inserire il segreto da memorizzare:");

                    secret = Console.ReadLine();

                    Console.WriteLine($"Salvataggio stringa: {secret}");

                    byte[] b = Encoding.ASCII.GetBytes(secret);

                    // Salvataggio della chiave come valore nel TPM
                    // TpmHelper.SaveValueIntoTpm(2500, b, b.Length);


                    TpmHelper.SaveHmacKey(secret);
                }

                if (operation.Key == ConsoleKey.R)
                {
                    byte[] c = TpmHelper.ReadValueFromTpm(2500, 150);
                    secret = Encoding.ASCII.GetString(c);
                    secret = secret.Trim('\0');
                    Console.WriteLine("La stringa memorizzata nel TPM è:");
                    Console.WriteLine(secret);
                }

                if (operation.Key == ConsoleKey.H)
                {
                    secret = "HeeFfpsSelN8c5zIJuZn7mQ28MBGIAoqp8Nf94N2eGM=";
                    string crypted = CalculateHmacString(stringToBeCyphered, secret);
                    Console.WriteLine("La stringa cifrata con System.Security.Cryptography è:");
                    Console.WriteLine(crypted);
                }

                if (operation.Key == ConsoleKey.T)
                {
                    string crypted = CalculateHmacStringTpm(stringToBeCyphered);
                    Console.WriteLine("La stringa cifrata con Tpm è:");
                    Console.WriteLine(crypted);
                }
            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("----------------------------------------");
            Console.WriteLine();
            Console.WriteLine("          Device provisioning");
            Console.WriteLine();
            Console.WriteLine("----------------------------------------");

            Console.WriteLine();
            Console.WriteLine("Note: Run this software with administrative rights.");
            Console.WriteLine();
            Console.WriteLine("Please insert the device Shared Key and press ENTER");


            string sharedKey = Console.ReadLine();

            try
            {
                TpmHelper.SaveHmacKey(sharedKey);
                Console.WriteLine();

                Console.WriteLine("Shared key written succesfully.");
            }
            catch (TpmException tpmException)
            {
                if (tpmException.ErrorString == "NvDefined")
                {
                    Console.WriteLine("Another Shared key seems to be already saved, would you like to replace the current Shared Key?");
                    Console.WriteLine("Press Y to overwrite, other buttons to abort");
                    var key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.Y)
                    {
                        TpmHelper.CleanOldHmacKey();
                        TpmHelper.SaveHmacKey(sharedKey);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();

                Console.WriteLine($"Shared key saving throws an exception: {ex.Message}");
            }

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }
예제 #6
0
 MakePartialCert(TpmPublic pub, string issuer = null, string subject    = null,
                 DateTime?notBefore           = null, DateTime?notAfter = null)
 {
     return(MakePartialCert(pub.objectAttributes, pub.type, TpmHelper.GetSchemeHash(pub), issuer, subject, notBefore, notAfter));
 }
예제 #7
0
        void TestAutomaticAuth(Tpm2 tpm, TestContext testCtx)
        {
            TpmHandle hPrim = Substrate.LoadRsaPrimary(tpm);

            // Make an RSA encryption key.
            var    decScheme = new SchemeOaep(Substrate.Random(TpmCfg.HashAlgs));
            var    sigScheme = new SchemeRsassa(Substrate.Random(TpmCfg.HashAlgs));
            ushort keyLength = Substrate.RandomRsaKeySize(decScheme.hashAlg);
            var    inPub     = new TpmPublic(Substrate.Random(TpmCfg.HashAlgs),
                                             ObjectAttr.Decrypt | ObjectAttr.Sign
                                             | ObjectAttr.FixedParent | ObjectAttr.FixedTPM
                                             | ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin,
                                             null,
                                             new RsaParms(new SymDefObject(), null, keyLength, 0),
                                             new Tpm2bPublicKeyRsa());

            TpmPublic  keyPublic;
            TpmPrivate keyPrivate = Substrate.Create(tpm, hPrim, inPub, out keyPublic);

            TpmHandle keyHandle = null;

            tpm._Behavior.Strict = true;
            try
            {
                // No auth session is added automatically when TPM object is in strict mode.
                tpm._ExpectError(TpmRc.AuthMissing)
                .Load(hPrim, keyPrivate, keyPublic);

                // Now explicitly request an auth session of appropriate type
                keyHandle = tpm[Auth.Default].Load(hPrim, keyPrivate, keyPublic);
            }
            finally
            {
                tpm._Behavior.Strict = false;
            }

            byte[] message = Substrate.RandBytes(1, TpmHelper.MaxOaepMsgSize(keyLength, decScheme.hashAlg));

            byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, null);

            // An auth session is added automatically when TPM object is not in strict mode.
            byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, null);

            TpmAlgId auditHashAlg = Substrate.Random(TpmCfg.HashAlgs);

            byte[] nonceTpm;

            // AuthSession object can be built from session handle 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
                Substrate.RandomNonce(auditHashAlg),     // nonceCaller
                null,                                    // no salt
                TpmSe.Hmac,                              // session type
                new SymDef(),                            // no encryption/decryption
                auditHashAlg,                            // authHash
                out nonceTpm)
                                    + (SessionAttr.ContinueSession | SessionAttr.Audit);

            /*
             * Alternatively one of the StartAuthSessionEx helpers can be used)
             * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, auditHashAlg, null,
             *                                                SessionAttr.ContinueSession | SessionAttr.Audit);
             */

            // TSS-specific call to verify TPM auditing correctness.
            tpm._SetCommandAuditAlgorithm(auditHashAlg);

            // Appropriate auth value is added automatically into the provided session
            byte[] decrypted2 = tpm[auditSess]._Audit()
                                .RsaDecrypt(keyHandle, encrypted, decScheme, null);

            ISignatureUnion sig;
            Attest          attest;

            // A session is added automatically to authorize TpmRh.Endorsement usage.
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess,
                                               null, new NullSigScheme(), out sig);

            // 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,
                                   null, new NullSigScheme(), out sig);
            // Restore correct auth value.
            tpm.EndorsementAuth = endorsementAuth;

            // Verify that both decryption and auditing worked correctly.
            SessionAuditInfo info = (SessionAuditInfo)attest.attested;

            byte[] auditDigest = tpm._GetAuditHash();
            testCtx.AssertEqual("AuditSessionDigest", info.sessionDigest, auditDigest);
            testCtx.AssertEqual("Decryption", decrypted1, decrypted2);

            // Change auth value of the decryption key.
            TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, hPrim,
                                                            Substrate.RandomAuth(keyPublic.nameAlg));
            TpmHandle newKeyHandle = tpm.Load(hPrim, newKeyPrivate, keyPublic);

            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, null);

            // And now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle).
            attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess,
                                               null, sigScheme, out sig);
            bool sigOk = keyPublic.VerifySignatureOverData(
                Marshaller.GetTpmRepresentation(attest), sig);

            testCtx.Assert("AuditSessionSignatute.1", sigOk);

            // Here 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,
                                                        null, sigScheme, out sig);

            // Verify that auditing worked correctly.
            sigOk = keyPublic.VerifySignatureOverData(
                Marshaller.GetTpmRepresentation(attest), sig);
            testCtx.Assert("AuditSessionSignatute.2", sigOk);

            tpm.FlushContext(newKeyHandle);
            tpm.FlushContext(auditSess);

            if (!TestCfg.HasTRM)
            {
                // Deplete TPM's active session storage
                List <AuthSession> landfill = new List <AuthSession>();

                for (;;)
                {
                    tpm._AllowErrors();
                    AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, Substrate.Random(TpmCfg.HashAlgs),
                                                           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, null, null);
                tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, null, null);

                // 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, null, null);
                tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory)
                .RsaDecrypt(keyHandle, encrypted, null, null);

                tpm._GetUnderlyingDevice().NeedsHMAC = false;
                tpm.RsaDecrypt(keyHandle, encrypted, null, null);
                tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, null, null);

                tpm._GetUnderlyingDevice().NeedsHMAC = needHmac;

                landfill.ForEach(s => tpm.FlushContext(s));
            }
            tpm.FlushContext(keyHandle);
        } // TestAutomaticAuth
예제 #8
0
        void TestCertifyX509Impl(Tpm2 tpm, TestContext testCtx,
                                 TpmPublic subjectTemplate, TpmPublic sigKeyTemplate,
                                 PolicyTree policy, string testLabel)
        {
            var partialCert      = X509Helpers.MakePartialCert(subjectTemplate);
            var partialCertBytes = partialCert.GetDerEncoded();

            // If you want to paste in your own hex put it here and s
            //var partialCertBytes = Globs.ByteArrayFromHex("01020304");

            // Certify RSA with RSA
            TpmPublic certifyingKeyPub, keyToBeCertifiedPub;
            TpmHandle hSigKey     = Substrate.CreatePrimary(tpm, sigKeyTemplate, out certifyingKeyPub);
            TpmHandle hSubjectKey = Substrate.CreatePrimary(tpm, subjectTemplate, out keyToBeCertifiedPub);

            AuthSession sess = tpm.StartAuthSessionEx(TpmSe.Policy, TpmAlgId.Sha256);

            sess.RunPolicy(tpm, policy);

            ISignatureUnion sig;

            byte[] tbsHash;
            byte[] addedTo = tpm[sess].CertifyX509(hSubjectKey, hSigKey,
                                                   null, new NullSigScheme(), partialCertBytes,
                                                   out tbsHash, out sig);

            tpm.FlushContext(sess);
            tpm.FlushContext(hSubjectKey);

            var             addedToCert  = AddedToCertificate.FromDerEncoding(addedTo);
            X509Certificate returnedCert = X509Helpers.AssembleCertificate(partialCert, addedToCert,
                                                                           sig is SignatureRsa ? ((SignatureRsa)sig).GetTpmRepresentation()
                                                        : ((SignatureEcc)sig).GetTpmRepresentation());

            // Does the expected hash match the returned hash?
            var tbsBytes        = returnedCert.GetTbsCertificate();
            var expectedTbsHash = TpmHash.FromData(TpmAlgId.Sha256, tbsBytes);

            Debug.Assert(Globs.ArraysAreEqual(expectedTbsHash.HashData, tbsHash));

            // Is the cert properly signed?
            if (TpmHelper.GetScheme(sigKeyTemplate).GetUnionSelector() != TpmAlgId.Rsapss)
            {
                // Software crypto layer does not support PSS
                bool sigOk = certifyingKeyPub.VerifySignatureOverHash(tbsHash, sig);
                if (sigKeyTemplate.type == TpmAlgId.Ecc)
                {
#if !__NETCOREAPP2__
                    // No ECC in .Net Core
                    testCtx.Assert("Sign" + testLabel, sigOk);
#endif
                }
                else
                {
                    testCtx.Assert("Sign" + testLabel, sigOk);
                }
            }
            tpm.VerifySignature(hSigKey, tbsHash, sig);

            tpm.FlushContext(hSigKey);
        }