示例#1
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
示例#2
0
        public void WithValidParams_CopyOnlyPropertiesToNewObject()
        {
            var source = ObjectAttr.GetDefault();
            var target = source.CopyOnlyPropertiesToNew <ObjectAttr>(nameof(ObjectAttr.Name));

            Assert.AreEqual(source.Name, target.Name);
        }
示例#3
0
        public void CopyWithAttributeToNew()
        {
            var source = ObjectAttr.Get();
            var target = source.CopyOnlyPropertiesToNew <ObjectAttr>(new[] { nameof(ObjectAttr.Name) });

            Assert.AreEqual(source.Name, target.Name);
        }
示例#4
0
        internal static X509KeyUsage GetKeyUsage(ObjectAttr keyAttrs)
        {
            int usage = 0;

            if (keyAttrs.HasFlag(ObjectAttr.Sign))
            {
                usage |= X509KeyUsage.DigitalSignature;
            }
            if (keyAttrs.HasFlag(ObjectAttr.Decrypt))
            {
                if (keyAttrs.HasFlag(ObjectAttr.Restricted))
                {
                    usage |= X509KeyUsage.KeyEncipherment;
                }
                else
                {
                    usage |= X509KeyUsage.DataEncipherment;
                }
            }
            if (keyAttrs.HasFlag(ObjectAttr.FixedTPM))
            {
                usage |= X509KeyUsage.NonRepudiation;
            }
            return(new X509KeyUsage(usage));
        }
示例#5
0
        void ExternalKeyImportSample(Tpm2 tpm, TestContext testCtx)
        {
            // Create a software key (external to any TPM).
            int keySize        = 2048;
            var externalRsaKey = new RawRsa(keySize);

            // When an external key comes from a cert, one would need to extract the key size and
            // byte buffers representing public and private parts of the key from the cert, an use
            // them directly in the call to ImportExternalRsaKey() below (i.e. no RawRsa object is
            // necessary).

            // Signing scheme to use (it may come from the key's cert)
            TpmAlgId sigHashAlg = Substrate.Random(TpmCfg.HashAlgs);
            var      sigScheme  = new SchemeRsassa(sigHashAlg);

            // An arbitrary external key would not have TPM key attributes associated with it.
            // Yet some of them may be inferred from the cert based on the declared key purpose
            // (ObjectAttr.Sign below). The others are defined by the intended TPM key usage
            // scenarios, e.g. ObjectAttr.UserWithAuth tells TPM to allow key usage authorization
            // using an auth value (random byte buffer) in a password or an HMAC session.
            ObjectAttr keyAttrs = ObjectAttr.Sign | ObjectAttr.UserWithAuth;

            // Generate an auth value for the imported matching in strength the signing scheme
            byte[] authVal = Substrate.RandomAuth(sigHashAlg);

            // We need a storage key to use as a parent of the imported key.
            // The following helper creates an RSA primary storage key.
            TpmHandle hParent = Substrate.CreateRsaPrimary(tpm);

            TssObject importedKey = ImportExternalRsaKey(tpm, hParent,
                                                         keySize, sigScheme,
                                                         externalRsaKey.Public, externalRsaKey.Private,
                                                         keyAttrs, authVal);

            // Now we can load the newly imported key into the TPM, ...
            TpmHandle hImportedKey = tpm.Load(hParent, importedKey.Private, importedKey.Public);

            // ... let the TSS know the auth value associated with this handle, ...
            hImportedKey.SetAuth(authVal);

            // ... and use it to sign something to check if import was OK
            TpmHash         toSign = TpmHash.FromRandom(sigHashAlg);
            ISignatureUnion sig    = tpm.Sign(hImportedKey, toSign, null, new TkHashcheck());

            // Verify that the signature is correct using the public part of the imported key
            bool sigOk = importedKey.Public.VerifySignatureOverHash(toSign, sig);

            testCtx.Assert("Signature.OK", sigOk);

            // Cleanup
            tpm.FlushContext(hImportedKey);
            // The parent key handle can be flushed immediately after it was used in the Load() command
            tpm.FlushContext(hParent);

            // Imported private/public key pair (in the TssObject) can be stored on disk, in the cloud,
            // etc. (no additional protection is necessary), and loaded into the TPM as above whenever
            // the key is needed.

            // Alternatively the key can be persisted in the TPM using the EvictControl() command
        } // ExternalKeyImportSample
示例#6
0
        public void CopyWithAttr()
        {
            var source = ObjectAttr.Get();
            var target = new ObjectAttr();

            source.CopyPropertiesTo(target);
            Assert.AreEqual(source.Name, target.Name);
            Assert.AreEqual(source.IsActive, target.IsActive);
        }
示例#7
0
        public void WithValidObjectAttr_CopyOnlyPropertiesToTarget()
        {
            var source = ObjectAttr.GetDefault();
            var target = new ObjectAttr();

            source.CopyOnlyPropertiesTo(target);

            Assert.AreEqual(source.Name, target.Name);
            Assert.AreEqual(source.IsActive, target.IsActive);
        }
示例#8
0
文件: Program.cs 项目: fars/TSS.MSR
        /// <summary>
        /// Create a sealed-object primary that can be accessed with the given policy. SHA256 is assumed.
        /// </summary>
        /// <param name="tpm"></param>
        /// <param name="dataToSeal"></param>
        /// <param name="authValue"></param>
        /// <param name="policy"></param>
        /// <returns></returns>
        private static TpmHandle CreateSealedPrimaryObject(Tpm2 tpm, byte[] dataToSeal, byte[] authValue, byte[] policy)
        {
            ObjectAttr attrs = ObjectAttr.FixedTPM | ObjectAttr.FixedParent;

            if (authValue != null)
            {
                attrs |= ObjectAttr.UserWithAuth;
            }

            byte[] policyVal      = policy ?? new byte[0];
            var    sealedInPublic = new TpmPublic(TpmAlgId.Sha256,
                                                  attrs,
                                                  policyVal,
                                                  new KeyedhashParms(new NullSchemeKeyedhash()),
                                                  new Tpm2bDigestKeyedhash());

            //
            // Envelope for sealed data and auth
            //
            byte[] authVal           = authValue ?? new byte[0];
            var    sealedInSensitive = new SensitiveCreate(authVal, dataToSeal);

            TkCreation creationTicket;

            byte[]       creationHashSealed;
            TpmPublic    sealedPublic;
            CreationData sealedCreationData;

            //
            // 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();

            //
            // Ask the TPM to create a primary containing the "sealed" data
            //
            TpmHandle primHandle = tpm[ownerAuth].CreatePrimary(TpmHandle.RhOwner,
                                                                sealedInSensitive,
                                                                sealedInPublic,
                                                                new byte[0],
                                                                new PcrSelection[0],
                                                                out sealedPublic,
                                                                out sealedCreationData,
                                                                out creationHashSealed,
                                                                out creationTicket);

            return(primHandle);
        }
示例#9
0
        public void WithObjectWithCopyableAttribute_CopyPropertiesToNewObjectAttr()
        {
            var source = ObjectAttr.GetDefault();

            var destination = source.CopyPropertiesToNew <ObjectAttr>();

            Assert.IsNotNull(destination);
            Assert.AreSame(source.GetType(), destination.GetType());
            Assert.AreNotEqual(source.Id, destination.Id);
            Assert.AreEqual(source.Name, destination.Name);
            Assert.AreEqual(source.IsActive, destination.IsActive);
        }
示例#10
0
        MakePartialCert(ObjectAttr keyAttrs,
                        TpmAlgId keyType   = TpmAlgId.None, TpmAlgId schemeHash = TpmAlgId.None,
                        string issuer      = null, string subject    = null,
                        DateTime?notBefore = null, DateTime?notAfter = null)
        {
            AlgorithmIdentifier algID = null;

            if (keyType != TpmAlgId.None && schemeHash != TpmAlgId.None)
            {
                algID = GetAlgId(keyType, schemeHash);
            }
            return(MakePartialCert(GetKeyUsage(keyAttrs), algID, issuer, subject, notBefore, notAfter));
        }
        // Constructor helpers
        private void CacheEkAndSrk()
        {
            ObjectAttr ekObjectAttributes =
                ObjectAttr.FixedTPM | ObjectAttr.FixedParent | ObjectAttr.SensitiveDataOrigin |
                ObjectAttr.AdminWithPolicy | ObjectAttr.Restricted | ObjectAttr.Decrypt;

            var ekAuthPolicy = new byte[]
            {
                0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xb3, 0xf8,
                0x1a, 0x90, 0xcc, 0x8d, 0x46, 0xa5, 0xd7, 0x24,
                0xfd, 0x52, 0xd7, 0x6e, 0x06, 0x52, 0x0b, 0x64,
                0xf2, 0xa1, 0xda, 0x1b, 0x33, 0x14, 0x69, 0xaa
            };

            // Get the real EK ready
            TpmPublic ekTemplate = new TpmPublic(
                TpmAlgId.Sha256,
                ekObjectAttributes,
                ekAuthPolicy,
                new RsaParms(new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb),
                             new NullAsymScheme(),
                             2048,
                             0),
                new Tpm2bPublicKeyRsa(new Byte[2048 / 8]));

            _ekPub = ReadOrCreatePersistedKey(
                new TpmHandle(TPM_20_EK_HANDLE),
                new TpmHandle(TpmHandle.RhEndorsement),
                ekTemplate);

            ObjectAttr srkObjectAttributes =
                ObjectAttr.FixedTPM | ObjectAttr.FixedParent | ObjectAttr.SensitiveDataOrigin |
                ObjectAttr.UserWithAuth | ObjectAttr.NoDA | ObjectAttr.Restricted | ObjectAttr.Decrypt;

            // Get the real SRK ready
            TpmPublic srkTemplate = new TpmPublic(
                TpmAlgId.Sha256,
                srkObjectAttributes,
                Array.Empty <byte>(),
                new RsaParms(new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb),
                             new NullAsymScheme(),
                             2048,
                             0),
                new Tpm2bPublicKeyRsa(new Byte[2048 / 8]));

            _srkPub = ReadOrCreatePersistedKey(
                new TpmHandle(TPM_20_SRK_HANDLE),
                new TpmHandle(TpmHandle.RhOwner),
                srkTemplate);
        }
示例#12
0
        void TestCertifyX509(Tpm2 tpm, TestContext testCtx)
        {
            if (!TpmCfg.IsImplemented(TpmCc.CertifyX509))
            {
                Substrate.WriteToLog("TestCertifyX509 skipped", ConsoleColor.DarkCyan);
                return;
            }

            ObjectAttr attr = ObjectAttr.Restricted | ObjectAttr.Sign
                              | ObjectAttr.FixedParent | ObjectAttr.FixedTPM
                              | ObjectAttr.UserWithAuth | ObjectAttr.AdminWithPolicy
                              | ObjectAttr.SensitiveDataOrigin;

            var policy = new PolicyTree(TpmAlgId.Sha256);

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

            var keyTemplateRsa = new TpmPublic(TpmAlgId.Sha256, attr, policy.GetPolicyDigest(),
                                               new RsaParms(new SymDefObject(), new SchemeRsassa(TpmAlgId.Sha256), 2048, 0),
                                               new Tpm2bPublicKeyRsa()
                                               );
            var keyTemplateEcc = new TpmPublic(TpmAlgId.Sha256, attr, policy.GetPolicyDigest(),
                                               new EccParms(new SymDefObject(), new SchemeEcdsa(TpmAlgId.Sha256),
                                                            EccCurve.NistP256, new NullKdfScheme()),
                                               new EccPoint()
                                               );
            var keyTemplatePss = new TpmPublic(TpmAlgId.Sha256, attr, policy.GetPolicyDigest(),
                                               new RsaParms(new SymDefObject(), new SchemeRsapss(TpmAlgId.Sha256), 2048, 0),
                                               new Tpm2bPublicKeyRsa()
                                               );

            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplateRsa, policy, "RsaWithRsa.1");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplateEcc, policy, "RsaWithEcc.1");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplateEcc, policy, "EccWithEcc.1");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplateRsa, policy, "EccWithRsa.1");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplatePss, policy, "RsaWithPss.1");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplatePss, policy, "EccWithPss.1");

            attr &= ~(ObjectAttr.Restricted | ObjectAttr.FixedParent | ObjectAttr.FixedTPM);
            keyTemplateRsa.objectAttributes = attr;
            keyTemplateEcc.objectAttributes = attr;
            keyTemplatePss.objectAttributes = attr;
            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplateRsa, policy, "RsaWithRsa.2");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplateEcc, policy, "RsaWithEcc.2");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplateEcc, policy, "EccWithEcc.2");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplateRsa, policy, "EccWithRsa.2");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateRsa, keyTemplatePss, policy, "RsaWithPss.2");
            TestCertifyX509Impl(tpm, testCtx, keyTemplateEcc, keyTemplatePss, policy, "EccWithPss.2");
        } // TestCertifyX509
示例#13
0
        /// <summary>
        /// Create a non-migratable RSA primary with the specified use-auth value and key size.
        /// </summary>
        /// <param name="parentAuth"></param>
        /// <param name="keyLen"></param>
        /// <param name="restricted"></param>
        /// <param name="useAuth"></param>
        /// <param name="parentHandle"></param>
        /// <param name="policy"></param>
        /// <returns></returns>
        public async Task <Tpm2CreateResponse> CreateRsaSigningAsync(
            TpmHandle parentHandle,
            AuthValue parentAuth,
            int keyLen,
            bool restricted,
            AuthValue useAuth,
            TpmHash policy = null)
        {
            ObjectAttr attr = ObjectAttr.Sign | ObjectAttr.FixedParent | ObjectAttr.FixedTPM | // Non-duplicatable
                              ObjectAttr.SensitiveDataOrigin | ObjectAttr.UserWithAuth;        // Authorize with auth-data

            if (restricted)
            {
                attr |= ObjectAttr.Restricted;
            }

            var thePolicy = new byte[0];

            if ((Object)policy != null)
            {
                thePolicy = policy;
                attr     |= ObjectAttr.AdminWithPolicy;
            }

            var signKeyPubTemplate = new TpmPublic(H.NameHash,
                                                   attr,
                                                   thePolicy,
                                                   new RsaParms(new SymDefObject(),
                                                                // Key type and sig scheme
                                                                H.RsaSigScheme,
                                                                (ushort)keyLen,
                                                                0),
                                                   new Tpm2bPublicKeyRsa());

            // Auth-data for new key
            var sensCreate = new SensitiveCreate(useAuth, new byte[0]);

            // Create the key
            var newKey = await H.Tpm[parentAuth].CreateAsync(parentHandle,
                                                             sensCreate,
                                                             signKeyPubTemplate,
                                                             new byte[0],
                                                             new PcrSelection[0]);

            return(newKey);
        }
示例#14
0
        internal async Task <Tpm2CreatePrimaryResponse> CreatePrimaryRsaAsyncInternal(
            int keyLen,
            byte[] useAuth,
            byte[] policyAuth,
            PcrSelection[] pcrSel)
        {
            ObjectAttr attr = ObjectAttr.Restricted | ObjectAttr.Decrypt
                              | ObjectAttr.FixedParent | ObjectAttr.FixedTPM
                              | ObjectAttr.SensitiveDataOrigin;

            var theUseAuth = new byte[0];

            if (useAuth != null)
            {
                theUseAuth = useAuth;
                attr      |= ObjectAttr.UserWithAuth;
            }
            var thePolicyAuth = new byte[0];

            if (policyAuth != null)
            {
                thePolicyAuth = policyAuth;
                attr         |= ObjectAttr.AdminWithPolicy;
            }
            var theSelection = new PcrSelection[0];

            if (pcrSel != null)
            {
                theSelection = pcrSel;
            }

            var sensCreate = new SensitiveCreate(theUseAuth, new byte[0]);
            var parms      = new TpmPublic(H.NameHash,
                                           attr,
                                           thePolicyAuth,
                                           new RsaParms(new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb),
                                                        new NullAsymScheme(),
                                                        (ushort)keyLen,
                                                        0),
                                           new Tpm2bPublicKeyRsa());

            byte[] outsideInfo = Globs.GetRandomBytes(8);
            return(await H.Tpm.CreatePrimaryAsync(TpmRh.Owner, sensCreate,
                                                  parms, outsideInfo, theSelection));
        }
示例#15
0
        public static List <ObjectAttr> GetPropertyValues(Object objGetter)
        {
            List <ObjectAttr> ListObjectAttr = new List <ObjectAttr>();
            Type t = objGetter.GetType();

            PropertyInfo[] props = t.GetProperties();
            foreach (var prop in props)
            {
                if (prop.GetIndexParameters().Length == 0)
                {
                    ObjectAttr obj = new ObjectAttr {
                        type = prop.PropertyType, FieldName = prop.Name, Value = prop.GetValue(objGetter)
                    };
                    ListObjectAttr.Add(obj);
                }
            }
            return(ListObjectAttr);
        }
            } // class PrivateKeyBlob


            // Trailing parameters are used to populate TpmPublic generated for the key from the blob.
            public static TpmPrivate CspToTpm(byte[] cspPrivateBlob, out TpmPublic tpmPub,
                                              TpmAlgId nameAlg        = TpmAlgId.Sha1,
                                              ObjectAttr keyAttrs     = ObjectAttr.Decrypt | ObjectAttr.UserWithAuth,
                                              IAsymSchemeUnion scheme = null,
                                              SymDefObject symDef     = null)
            {
                if (scheme == null)
                {
                    scheme = new NullAsymScheme();
                }
                if (symDef == null)
                {
                    symDef = new SymDefObject();
                }

                var m          = new Marshaller(cspPrivateBlob, DataRepresentation.LittleEndian);
                var cspPrivate = m.Get <Csp.PrivateKeyBlob>();
                var keyAlg     = cspPrivate.publicKeyStruc.aiKeyAlg;

                if (keyAlg != Csp.AlgId.CAlgRsaKeyX && keyAlg != Csp.AlgId.CAlgRsaSign)
                {
                    Globs.Throw <NotSupportedException>("CSP blobs for keys of type " + keyAlg.ToString("X") + " are not supported");
                    tpmPub = new TpmPublic();
                    return(new TpmPrivate());
                }

                var rsaPriv = new Tpm2bPrivateKeyRsa(Globs.ReverseByteOrder(cspPrivate.prime1));
                var sens    = new Sensitive(new byte[0], new byte[0], rsaPriv);

                tpmPub = new TpmPublic(nameAlg, keyAttrs, new byte[0],
                                       new RsaParms(symDef,
                                                    scheme,
                                                    (ushort)cspPrivate.rsaPubKey.bitlen,
                                                    cspPrivate.rsaPubKey.pubexp),
                                       new Tpm2bPublicKeyRsa(Globs.ReverseByteOrder(cspPrivate.modulus)));

                return(new TpmPrivate(sens.GetTpm2BRepresentation()));
            }
示例#17
0
 ///<param name = "the_nameAlg">algorithm used for computing the Name of the object NOTE	The "+" indicates that the instance of a TPMT_PUBLIC may have a "+" to indicate that the nameAlg may be TPM_ALG_NULL.</param>
 ///<param name = "the_objectAttributes">attributes that, along with type, determine the manipulations of this object</param>
 ///<param name = "the_authPolicy">optional policy for using this key The policy is computed using the nameAlg of the object. NOTE Shall be the Empty Policy if no authorization policy is present.</param>
 ///<param name = "the_parameters">the algorithm or structure details(One of KeyedhashParms, SymcipherParms, RsaParms, EccParms, AsymParms)</param>
 ///<param name = "the_unique">the unique identifier of the structure For an asymmetric key, this would be the public key.(One of Tpm2bDigestKeyedhash, Tpm2bDigestSymcipher, Tpm2bPublicKeyRsa, EccPoint)</param>
 public TpmPublic(
 TpmAlgId the_nameAlg,
 ObjectAttr the_objectAttributes,
 byte[] the_authPolicy,
 IPublicParmsUnion the_parameters,
 IPublicIdUnion the_unique
 )
 {
     this.nameAlg = the_nameAlg;
     this.objectAttributes = the_objectAttributes;
     this.authPolicy = the_authPolicy;
     this.parameters = the_parameters;
     this.unique = the_unique;
 }
示例#18
0
 public void WithNullObjectAttr_CopyPropertiesToTarget()
 {
     Assert.Throws <ArgumentNullException>(() => ObjectAttr.GetDefault().CopyPropertiesTo(null));
 }
示例#19
0
 public TpmPublic()
 {
     nameAlg = TpmAlgId.Null;
     objectAttributes = new ObjectAttr();
     authPolicy = new byte[0];
 }