Inheritance: TpmStructureBase, INameUnion
Ejemplo n.º 1
0
        /// <summary>
        /// Create a simple bound but unseeded session.
        /// </summary>
        public AuthSession StartAuthSessionEx(
            TpmHandle boundEntity,
            TpmSe sessionType,
            TpmAlgId authHash,
            SessionAttr initialialAttrs = SessionAttr.ContinueSession,
            SymDef symDef = null,
            int nonceCallerSize = 0)
        {
            byte[] nonceTpm;
            var EmptySalt = new byte[0];

            if (nonceCallerSize == 0)
            {
                nonceCallerSize = CryptoLib.DigestSize(authHash);
            }

            AuthSession sess = StartAuthSession(TpmRh.Null, boundEntity,
                                                GetRandomBytes(nonceCallerSize),
                                                EmptySalt, sessionType,
                                                symDef ?? new SymDef(),
                                                authHash, out nonceTpm)
                               + initialialAttrs;

            _InitializeSession(sess);
            return sess;
        }
Ejemplo n.º 2
0
 public TpmPolicySecret(
     TpmHandle authorityHandle,
     byte[] authorityName,
     AuthValue theAuthVal,
     bool useNonceTpm,
     int expirationTime,
     byte[] cpHash,
     byte[] policyRef,
     string branchName = "") : base(useNonceTpm, expirationTime, cpHash, policyRef, branchName)
 {
     AuthVal         = theAuthVal;
     AuthorityHandle = authorityHandle;
     AuthorityName   = Globs.CopyData(authorityName);
 }
Ejemplo n.º 3
0
 public TpmPolicyNV(TpmHandle authorizationHandle, byte[] nvAccessAuth,
                    TpmHandle nvIndex, byte[] indexName,
                    byte[] operandB, ushort offset, Eo operation,
                    string branchName = "", string nodeId = null)
     : base(branchName, nodeId)
 {
     AuthorizationHandle = authorizationHandle;
     NvAccessAuth        = Globs.CopyData(nvAccessAuth);
     NvIndex             = nvIndex;
     OperandB            = Globs.CopyData(operandB);
     Offset    = offset;
     Operation = operation;
     IndexName = Globs.CopyData(indexName);
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Calculate the qualified name of an object presumed loaded under the provided ancestral chain
 /// in a given hierarchy.
 /// </summary>
 /// <param name="hierarchyHandle"></param>
 /// <param name="children"></param>
 /// <returns></returns>
 public static byte[] GetQualifiedName(TpmHandle hierarchyHandle, TpmPublic[] children)
 {
     byte[] runningName = Marshaller.GetTpmRepresentation(hierarchyHandle);
     foreach (TpmPublic pub in children)
     {
         byte[] thisName = pub.GetName();
         runningName = Globs.Concatenate
                       (
             Marshaller.GetTpmRepresentation(pub.nameAlg),
             CryptoLib.HashData(pub.nameAlg, new[] { runningName, thisName })
                       );
     }
     return(runningName);
 }
Ejemplo n.º 5
0
        TkVerified SignApproval(Tpm2 tpm, byte[] approvedPolicy, byte[] policyRef,
                                TpmHandle hSigKey, ISigSchemeUnion scheme = null)
        {
            byte[]    name, qname;
            TpmPublic pub = tpm.ReadPublic(hSigKey, out name, out qname);

            byte[] dataToSign = Globs.Concatenate(approvedPolicy, policyRef);
            byte[] aHash      = CryptoLib.HashData(pub.nameAlg, dataToSign);

            // Create an authorization certificate for the "approvedPolicy"
            var sig = tpm.Sign(hSigKey, aHash, scheme, new TkHashcheck());

            return(tpm.VerifySignature(hSigKey, aHash, sig));
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Sets parameters associated with the session.
 /// </summary>
 internal void Init(AuthSession Params)
 {
     SessionType = Params.SessionType;
     BindObject  = Params.BindObject;
     NonceCaller = Params.NonceCaller;
     NonceTpm    = Params.NonceTpm;
     Symmetric   = Params.Symmetric;
     AuthHash    = Params.AuthHash;
     AuthHandle  = Params.AuthHandle;
     // When salt is required, the session will have it set directly by the user
     if (Params.Salt != SaltNeeded)
     {
         Salt = null;
     }
 }
Ejemplo n.º 7
0
        internal ObjectContext GetContext(Tbs.TbsContext caller, TpmHandle callerHandle)
        {
            if (Tbs.SlotTypeFromHandle(callerHandle) == Tbs.SlotType.NoSlot)
            {
                // Indicates that this is a TPM resident object (NV-slot, primary-handle, PWAP-handle, etc.)
                var temp = new ObjectContext {
                    TheTpmHandle = callerHandle
                };
                return(temp);
            }
            ObjectContext x = ObjectContexts.Find(item => (item.Owner == caller) && item.OwnerHandle.handle == callerHandle.handle);

            // Note that x may be null
            return(x);
        }
Ejemplo n.º 8
0
        private void CleanTpm()
        {
            var loaded = new TpmHandle[3][];

            loaded[0] = GetLoadedEntities(Tpm, Ht.Transient);
            loaded[1] = GetLoadedEntities(Tpm, Ht.LoadedSession);
            loaded[2] = GetLoadedEntities(Tpm, TpmHelpers.GetEnumerator <Ht>("ActiveSession", "SavedSession"));
            foreach (TpmHandle[] arr in loaded)
            {
                foreach (TpmHandle h in arr)
                {
                    Tpm.FlushContext(h);
                }
            }
        }
Ejemplo n.º 9
0
        internal static SlotType SlotTypeFromHandle(TpmHandle h)
        {
            switch (h.GetType())
            {
            case Ht.Transient:
                return(SlotType.ObjectSlot);

            case Ht.PolicySession:
            case Ht.HmacSession:
                return(SlotType.SessionSlot);

            default:
                return(SlotType.NoSlot);
            }
        }
Ejemplo n.º 10
0
        public async Task <Tpm2CreateResponse> CreateAsync(
            TpmHandle parentHandle,
            SensitiveCreate inSensitive,
            TpmPublic inPublic,
            byte[] outsideInfo,
            PcrSelection[] creationPCR)
        {
            var inS = new Tpm2CreateRequest(parentHandle, inSensitive, inPublic, outsideInfo, creationPCR);
            TpmStructureBase outSBase = null;
            await Task.Run(() => DispatchMethod(TpmCc.Create, inS, typeof(Tpm2CreateResponse), out outSBase, 1, 0));

            var outS = (Tpm2CreateResponse)outSBase;

            return(outS);
        }
Ejemplo n.º 11
0
        public async Task <ISignatureUnion> SignAsync(
            TpmHandle keyHandle,
            byte[] digest,
            ISigSchemeUnion inScheme,
            TkHashcheck validation)
        {
            var inS = new Tpm2SignRequest(keyHandle, digest, inScheme, validation);
            TpmStructureBase outSBase = null;
            await Task.Run(() => DispatchMethod(TpmCc.Sign, inS,
                                                typeof(Tpm2SignResponse),
                                                out outSBase, 1, 0));

            var outS = (Tpm2SignResponse)outSBase;

            return(outS.signature);
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Create a simple bound but unseeded session.
        /// </summary>
        public AuthSession StartAuthSessionEx(
            TpmHandle boundEntity,
            TpmSe sessionType,
            TpmAlgId authHash,
            SessionAttr initialialAttrs = SessionAttr.ContinueSession,
            SymDef symmAlg      = null,
            int nonceCallerSize = 16)
        {
            byte[] nonceTpm;
            var    EmptySalt = new byte[0];

            AuthSession sess = StartAuthSession(TpmRh.Null, boundEntity,
                                                GetRandomBytes(nonceCallerSize),
                                                EmptySalt, sessionType,
                                                symmAlg ?? new SymDef(),
                                                authHash, out nonceTpm)
                               + initialialAttrs;

            _InitializeSession(sess);
            return(sess);
        }
Ejemplo n.º 15
0
        private void CheckConsistency(string message = "")
        {
            TpmHandle[] loadedObjects        = GetLoadedEntities(Tpm, Ht.Transient);
            TpmHandle[] loadedSessions       = GetLoadedEntities(Tpm, Ht.LoadedSession);
            TpmHandle[] contextSavedSessions = GetLoadedEntities(Tpm, TpmHelpers.GetEnumerator <Ht>("ActiveSession", "SavedSession"));

            int numLoadedObject = 0, numLoadedSession = 0, numSavedSession = 0;

            foreach (ObjectContext o in ContextManager.ObjectContexts)
            {
                if (o.TheSlotType == SlotType.ObjectSlot)
                {
                    if (!o.Loaded)
                    {
                        continue;
                    }
                    Debug.Assert(loadedObjects.Contains(o.TheTpmHandle));
                    numLoadedObject++;
                }

                if (o.TheSlotType == SlotType.SessionSlot)
                {
                    if (o.Loaded)
                    {
                        Debug.Assert(loadedSessions.Contains(o.TheTpmHandle));
                        numLoadedSession++;
                    }
                    else
                    {
                        TpmHandle translatedHandle = new TpmHandle(Ht.LoadedSession, o.Context.savedHandle.GetOffset());
                        Debug.Assert(contextSavedSessions.Contains(translatedHandle));
                        numSavedSession++;
                    }
                }
            }

            Debug.Assert(numLoadedObject == loadedObjects.Length);
            Debug.Assert(numLoadedSession == loadedSessions.Length);
            Debug.Assert(numSavedSession == contextSavedSessions.Length);
        }
Ejemplo n.º 16
0
        public async Task <Tpm2CreatePrimaryResponse> CreatePrimaryAsync(
            TpmHandle primaryHandle,
            SensitiveCreate inSensitive,
            TpmPublic inPublic,
            byte[] outsideInfo,
            PcrSelection[] creationPCR)
        {
            var inS = new Tpm2CreatePrimaryRequest {
                primaryHandle = primaryHandle,
                inSensitive   = inSensitive,
                inPublic      = inPublic,
                outsideInfo   = outsideInfo,
                creationPCR   = creationPCR
            };
            TpmStructureBase outSBase = null;
            await Task.Run(() =>
                           DispatchMethod(TpmCc.CreatePrimary, inS, typeof(Tpm2CreatePrimaryResponse), out outSBase, 1, 1));

            var outS = (Tpm2CreatePrimaryResponse)outSBase;

            return(outS);
        }
Ejemplo n.º 17
0
        internal ObjectContext CreateObjectContext(Tbs.TbsContext owner, TpmHandle tpmHandle)
        {
            Tbs.SlotType newSlotType = Tbs.SlotTypeFromHandle(tpmHandle);
            if (newSlotType == Tbs.SlotType.NoSlot)
            {
                throw new Exception("should not be here");
            }

            // Make a new slot context of the requisite type
            uint tbsHandle  = GetFreeHandle(owner, tpmHandle);
            var  newContext = new ObjectContext {
                OwnerHandle  = new TpmHandle(tbsHandle),
                TheTpmHandle = tpmHandle,
                TheSlotType  = newSlotType,
                LastUseCount = GetUseCount(),
                Loaded       = true,
                Owner        = owner
            };

            ObjectContexts.Add(newContext);
            return(newContext);
        }
Ejemplo n.º 18
0
        internal ObjectContext CreateObjectContext(Tbs.TbsContext owner, TpmHandle tpmHandle)
        {
            Tbs.SlotType newSlotType = Tbs.SlotTypeFromHandle(tpmHandle);
            if (newSlotType == Tbs.SlotType.NoSlot)
            {
                throw new Exception("CreateObjectContext: Should not be here");
            }

            // Make a new slot context of the requisite type
            uint tbsHandle = GetFreeHandle(owner, tpmHandle);
            var newContext = new ObjectContext {
                OwnerHandle = new TpmHandle(tbsHandle),
                TheTpmHandle = tpmHandle,
                TheSlotType = newSlotType,
                LastUseCount = GetUseCount(),
                Loaded = true,
                Owner = owner
            };

            ObjectContexts.Add(newContext);
            return newContext;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// This TBS returns a random handle value in the desired handle range (ugh).
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="tpmHandle"></param>
        /// <returns></returns>
        private uint GetFreeHandle(Tbs.TbsContext owner, TpmHandle tpmHandle)
        {
            Tbs.SlotType neededType = Tbs.SlotTypeFromHandle(tpmHandle);
            if (neededType == Tbs.SlotType.NoSlot)
            {
                return(tpmHandle.handle);
            }

            uint candidateHandle = tpmHandle.handle;
            int  numTries        = 0;

            while (numTries++ < 1000)
            {
                if (!HandleInUse(owner, candidateHandle))
                {
                    return(candidateHandle);
                }

                Ht  handleType = tpmHandle.GetType();
                var randomPos  = (uint)Globs.GetRandomInt((int)TpmHandle.GetRangeLength(tpmHandle.GetType()));
                candidateHandle = ((uint)handleType << 24) + randomPos;
            }
            throw new Exception("Too many TBS contexts");
        }
Ejemplo n.º 20
0
 // Constructs a new TpmHandle object using the numeric handle value from 'src',
 // and binds 'src' so that it receives all auth/name values updates that happen
 // on this object.
 internal TpmHandle(TpmHandle src, Bind bind) : this(src)
 {
     BoundHandle = src;
 }
Ejemplo n.º 21
0
 internal static bool IsNull(TpmHandle h)
 {
     return(h == null || h.handle == (uint)TpmRh.Null || h.handle == (uint)TpmRh.None);
 }
Ejemplo n.º 22
0
 public TkVerified()
 {
     hierarchy = new TpmHandle();
     digest = new byte[0];
 }
Ejemplo n.º 23
0
 public TpmHandleX(TpmHandle h)
 {
     Handle = h;
 }
Ejemplo n.º 24
0
 public NvPublic()
 {
     nvIndex = new TpmHandle();
     nameAlg = TpmAlgId.Null;
     attributes = new NvAttr();
     authPolicy = new byte[0];
 }
Ejemplo n.º 25
0
 public AuthCommand()
 {
     sessionHandle = new TpmHandle();
     nonce = new byte[0];
     sessionAttributes = new SessionAttr();
     hmac = new byte[0];
 }
Ejemplo n.º 26
0
 public TkAuth()
 {
     tag = new TpmSt();
     hierarchy = new TpmHandle();
     digest = new byte[0];
 }
Ejemplo n.º 27
0
 ///<param name = "the_hierarchy">the hierarchy</param>
 ///<param name = "the_digest">This shall be the HMAC produced using a proof value of hierarchy.</param>
 public TkHashcheck(
 TpmHandle the_hierarchy,
 byte[] the_digest
 )
 {
     this.hierarchy = the_hierarchy;
     this.digest = the_digest;
 }
Ejemplo n.º 28
0
 public TkHashcheck()
 {
     hierarchy = new TpmHandle();
     digest = new byte[0];
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Called from TpmPolicySecret.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicySecretCallback(TpmPolicySecret ace, out SessionBase authorizingSession, out TpmHandle authorizedEntityHandle, out bool flushAuthEntity)
 {
     if (PolicySecretCallback == null)
     {
         Globs.Throw("No policy secret callback installed.");
         authorizingSession = new AuthSession(new TpmHandle());
         authorizedEntityHandle = new TpmHandle();
         flushAuthEntity = false;
         return;
     }
     PolicySecretCallback(this, ace, out authorizingSession, out authorizedEntityHandle, out flushAuthEntity);
 }
Ejemplo n.º 30
0
 public async Task<Tpm2CreateResponse> CreateAsync(
     TpmHandle parentHandle,
     SensitiveCreate inSensitive,
     TpmPublic inPublic,
     byte[] outsideInfo,
     PcrSelection[] creationPCR)
 {
     var inS = new Tpm2CreateRequest {
         parentHandle = parentHandle,
         inSensitive = inSensitive,
         inPublic = inPublic,
         outsideInfo = outsideInfo,
         creationPCR = creationPCR
     };
     TpmStructureBase outSBase = null;
     await Task.Run(() => DispatchMethod(TpmCc.Create, inS, typeof (Tpm2CreateResponse), out outSBase, 1, 0));
     var outS = (Tpm2CreateResponse)outSBase;
     return outS;
 }
Ejemplo n.º 31
0
 public async Task<ISignatureUnion> SignAsync(
     TpmHandle keyHandle,
     byte[] digest,
     ISigSchemeUnion inScheme,
     TkHashcheck validation)
 {
     var inS = new Tpm2SignRequest {
         keyHandle = keyHandle,
         digest = digest,
         inScheme = inScheme,
         validation = validation
     };
     TpmStructureBase outSBase = null;
     await Task.Run(() => DispatchMethod(TpmCc.Sign, inS, typeof (Tpm2SignResponse), out outSBase, 1, 0));
     var outS = (Tpm2SignResponse)outSBase;
     return outS.signature;
 }
Ejemplo n.º 32
0
 ///<param name = "the_nvIndex">the handle of the data area</param>
 ///<param name = "the_nameAlg">hash algorithm used to compute the name of the Index and used for the authPolicy</param>
 ///<param name = "the_attributes">the Index attributes</param>
 ///<param name = "the_authPolicy">optional access policy for the Index The policy is computed using the nameAlg NOTE Shall be the Empty Policy if no authorization policy is present.</param>
 ///<param name = "the_dataSize">the size of the data area The maximum size is implementation-dependent. The minimum maximum size is platform-specific.</param>
 public NvPublic(
 TpmHandle the_nvIndex,
 TpmAlgId the_nameAlg,
 NvAttr the_attributes,
 byte[] the_authPolicy,
 ushort the_dataSize
 )
 {
     this.nvIndex = the_nvIndex;
     this.nameAlg = the_nameAlg;
     this.attributes = the_attributes;
     this.authPolicy = the_authPolicy;
     this.dataSize = the_dataSize;
 }
Ejemplo n.º 33
0
 ///<param name = "the_handle">an array of handles</param>
 public HandleArray(
 TpmHandle[] the_handle
 )
 {
     this.handle = the_handle;
 }
Ejemplo n.º 34
0
 public Pwap()
 {
     Handle = new TpmHandle(TpmRh.TpmRsPw);
 }
Ejemplo n.º 35
0
        internal void Print(string name, string type, Object o)
        {
            if (o == null)
            {
                // E.g. inPrivate null SomeStruct
                AddLine(B, "{0}@{1}#{2}", name, "null", type);
                return;
            }

            // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
            if (o is TpmStructureBase)
            {
                string ss = type;
                if (ss.StartsWith("I"))
                {
                    // If the member is an interface, also print the type of entity being dumped
                    string intType = o.GetType().ToString();
                    intType = intType.Substring(intType.LastIndexOf('.') + 1);

                    type = intType;
                }
                if (o is TpmHandle)
                {
                    TpmHandle tpmHandle  = o as TpmHandle;
                    string    handleName = tpmHandle.GetType().ToString();
                    if (tpmHandle.GetType() == Ht.Permanent)
                    {
                        handleName += " -" + ((TpmRh)tpmHandle.handle).ToString();
                    }
                    name = string.Format("({0})", handleName);
                }
                // Print name and type but not the contents (printed recursively later)
                AddLine(B, "{0}@-#{1}", name, type);
                // Recurse
                Indent++;
                ((TpmStructureBase)o).ToStringInternal(this);
                Indent--;
                return;
            }

            // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
            if (o is Enum)
            {
                var    en = (Enum)o;
                string s  = Enum.Format(en.GetType(), en, "g");
                s = s.Replace(',', '|');
                // name   Elem1|Elem2
                AddLine(B, "{0}@{1}#{2}", name, s, type);
                return;
            }

            if (o is ValueType)
            {
                //checked that this actually works with Int64, etc.
                var val = o is UInt64 ? (Int64)Convert.ToUInt64(o) : Convert.ToInt64(o);

                string hexString = Convert.ToString(val, 16);

                // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                AddLine(B, "{0}@{1} (0x{2})#{3}", name, o.ToString(), hexString, type);
                return;
            }

            // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
            if (o is Array)
            {
                var  a           = (Array)o;
                Type elementType = o.GetType().GetElementType();
                if (elementType == typeof(byte))
                {
                    // Byte arrays as special -
                    string hexString  = "0x" + Globs.HexFromByteArray((byte[])a, 8);
                    string typeString = String.Format("byte[{0}]", a.Length);
                    AddLine(B, "{0}@{1}#{2}", name, hexString, typeString);
                    return;
                }
                // ReSharper disable once RedundantIfElseBlock
                else
                {
                    B.AppendFormat("{0}Array - {1}[{2}]\n", Spaces(), type, a.Length);
                    Indent++;
                    for (int j = 0; j < a.Length; j++)
                    {
                        Object elem = a.GetValue(j);
                        // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                        Print(elem.GetType().ToString(), j.ToString(), elem);
                    }
                    Indent--;
                    return;
                }
            }
            Globs.Throw <NotImplementedException>("Print: Unknown type " + o.GetType());
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Called from TpmPolicySecret.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicySecretCallback(TpmPolicySecret ace, out SessionBase authorizingSession, out TpmHandle authorizedEntityHandle, out bool flushAuthEntity)
 {
     if (PolicySecretCallback == null)
     {
         Globs.Throw("No policy secret callback installed.");
         authorizingSession     = new AuthSession(new TpmHandle());
         authorizedEntityHandle = new TpmHandle();
         flushAuthEntity        = false;
         return;
     }
     PolicySecretCallback(this, ace, out authorizingSession, out authorizedEntityHandle, out flushAuthEntity);
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Called from TpmPolicyNV.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicyNvCallback(TpmPolicyNV ace, out TpmHandle authHandle, out TpmHandle nvHandle, out SessionBase authSession)
 {
     if (PolicyNVCallback == null)
     {
         Globs.Throw("No policyNV callback installed.");
         authHandle = new TpmHandle();
         nvHandle = new TpmHandle();
         authSession = new AuthSession(new TpmHandle());
         return;
     }
     PolicyNVCallback(this, ace, out authSession, out authHandle, out nvHandle);
 }
Ejemplo n.º 38
0
 ///<param name = "the_sessionHandle">the session handle</param>
 ///<param name = "the_nonce">the session nonce, may be the Empty Buffer</param>
 ///<param name = "the_sessionAttributes">the session attributes</param>
 ///<param name = "the_hmac">either an HMAC, a password, or an EmptyAuth</param>
 public AuthCommand(
 TpmHandle the_sessionHandle,
 byte[] the_nonce,
 SessionAttr the_sessionAttributes,
 byte[] the_hmac
 )
 {
     this.sessionHandle = the_sessionHandle;
     this.nonce = the_nonce;
     this.sessionAttributes = the_sessionAttributes;
     this.hmac = the_hmac;
 }
Ejemplo n.º 39
0
 ///<param name = "the_hierarchy">the hierarchy containing keyName</param>
 ///<param name = "the_digest">This shall be the HMAC produced using a proof value of hierarchy.</param>
 public TkVerified(
 TpmHandle the_hierarchy,
 byte[] the_digest
 )
 {
     this.hierarchy = the_hierarchy;
     this.digest = the_digest;
 }
Ejemplo n.º 40
0
 ///<param name = "the_tag">ticket structure tag</param>
 ///<param name = "the_hierarchy">the hierarchy of the object used to produce the ticket</param>
 ///<param name = "the_digest">This shall be the HMAC produced using a proof value of hierarchy.</param>
 public TkAuth(
 TpmSt the_tag,
 TpmHandle the_hierarchy,
 byte[] the_digest
 )
 {
     this.tag = the_tag;
     this.hierarchy = the_hierarchy;
     this.digest = the_digest;
 }
Ejemplo n.º 41
0
 public Pwap(byte[] authVal)
 {
     Handle      = new TpmHandle(TpmRh.TpmRsPw);
     Handle.Auth = authVal;
 }
Ejemplo n.º 42
0
 /// <summary>
 /// This callback function provides authorization in plain text
 /// </summary>
 static public void PolicySecretCallback(
     PolicyTree policyTree,
     TpmPolicySecret ace,
     out SessionBase authorizingSession,
     out TpmHandle authorizedEntityHandle,
     out bool flushAuthEntity)
 {
     authorizingSession = _publicAuthorizationValue;
     authorizedEntityHandle = _publicSealedObjectHandle;
     flushAuthEntity = false;
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Called from TpmPolicyNV.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicyNvCallback(TpmPolicyNV ace, out TpmHandle authHandle, out TpmHandle nvHandle, out SessionBase authSession)
 {
     if (PolicyNVCallback == null)
     {
         Globs.Throw("No policyNV callback installed.");
         authHandle  = new TpmHandle();
         nvHandle    = new TpmHandle();
         authSession = new AuthSession(new TpmHandle());
         return;
     }
     PolicyNVCallback(this, ace, out authSession, out authHandle, out nvHandle);
 }
Ejemplo n.º 44
0
 public TkAuth(TkAuth the_TkAuth)
 {
     if((Object) the_TkAuth == null ) throw new ArgumentException(Globs.GetResourceString("parmError"));
     tag = the_TkAuth.tag;
     hierarchy = the_TkAuth.hierarchy;
     digest = the_TkAuth.digest;
 }
Ejemplo n.º 45
0
 public TkVerified(TkVerified the_TkVerified)
 {
     if((Object) the_TkVerified == null ) throw new ArgumentException(Globs.GetResourceString("parmError"));
     hierarchy = the_TkVerified.hierarchy;
     digest = the_TkVerified.digest;
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Some policies can be evaluated solely from public parts of the policy.
        /// Others needs a private keyholder to sign some data. Tpm2Lib provides 
        /// a callback facility for these cases.  
        /// 
        /// This second sample illustrates the use of callbacks to provide authData.
        /// </summary>
        /// <param name="tpm">Reference to the TPM object to use.</param>
        static void PolicyEvaluationWithCallback2(Tpm2 tpm)
        {
            Console.WriteLine("Policy evaluation with callback sample 2.");

            //
            // 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.PolicySecret,
                                        TpmCc.PolicyGetDigest,
                                        TpmCc.PolicyRestart
            };
            foreach (var commandCode in usedCommands)
            {
                if (!tpm.Helpers.IsImplemented(commandCode))
                {
                    Console.WriteLine("Cancel Policy evaluation callback 2 sample, because command {0} is not implemented by TPM.", commandCode);
                    return;
                }
            }

            //
            // Create an object with an AuthValue. The type of object is immaterial
            // (it can even be the owner). In order to construct the policy we will 
            // need the name and to prove that we know the AuthVal.
            // 
            _publicAuthorizationValue = AuthValue.FromRandom(10);
            var dataToSeal = new byte[] { 1, 2, 3, 4 };
            _publicSealedObjectHandle = CreateSealedPrimaryObject(tpm,
                                                                  dataToSeal,
                                                                  _publicAuthorizationValue, 
                                                                  null);
            byte[] objectName = _publicSealedObjectHandle.Name;

            var policy = new PolicyTree(TpmAlgId.Sha256);

            policy.Create(
                new PolicyAce[]
                    {
                            new TpmPolicySecret(objectName,     // Name of the obj that we will prove authData
                                                true,           // Include nonceTpm
                                                new byte[0],    // Not bound to a cpHash
                                                new byte[0],    // Null policyRef
                                                0),             // Never expires (in this session)
                            "leaf"                              // Name for this ACE
                    });

            TpmHash expectedHash = policy.GetPolicyDigest();

            //
            // We are about to ask for the session to be evaluated, but in order
            // to process TpmPolicySecret the caller will have to prove knowledge of 
            // the authValue associated with objectName. In this first version we
            // do this with PWAP.
            // 
            policy.SetPolicySecretCallback(PolicySecretCallback);
            AuthSession authSession = tpm.StartAuthSessionEx(TpmSe.Policy, TpmAlgId.Sha256);
            authSession.RunPolicy(tpm, policy, "leaf");

            //
            // The policy evaluated.  But is the digest what we expect?
            // 
            byte[] digestIs = tpm.PolicyGetDigest(authSession.Handle);
            if (expectedHash != digestIs)
            {
                throw new Exception("Incorrect PolicyDigest");
            }

            //
            // And now do the same thing but with an HMAC session.
            // 
            _sharedTpm = tpm;
            tpm.PolicyRestart(authSession.Handle);
            policy.SetPolicySecretCallback(PolicySecretCallback2);
            authSession.RunPolicy(tpm, policy, "leaf");
            _sharedTpm = null;

            //
            // The policy evaluated. But is the digest what we expect?
            // 
            digestIs = tpm.PolicyGetDigest(authSession.Handle);
            if (expectedHash != digestIs)
            {
                throw new Exception("Incorrect PolicyDigest");
            }
            Console.WriteLine("TpmPolicySignature evaluated.");

            tpm.FlushContext(authSession.Handle);
        }
Ejemplo n.º 47
0
 public ParametrizedHandle(TpmHandle h)
 {
     Handle = h;
     Params = new ArrayList();
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Updates TBS context database for commands that either fill or empty slots.
 /// </summary>
 /// <param name="caller"></param>
 /// <param name="command"></param>
 /// <param name="responseHandles"></param>
 /// <param name="inputObjects"></param>
 private void ProcessUpdatedTpmState(TbsContext caller, CommandInfo command, TpmHandle[] responseHandles, ObjectContext[] inputObjects)
 {
     switch (command.CommandCode)
     {
         // Commands that fill a slot (apart from contextLoad, which is more complex)
         case TpmCc.Load:
         case TpmCc.LoadExternal:
         case TpmCc.CreatePrimary:
         case TpmCc.HmacStart:
         case TpmCc.HashSequenceStart:
         case TpmCc.StartAuthSession:
             var t = new TpmHandle(responseHandles[0].handle);
             // ReSharper disable once UnusedVariable
             ObjectContext context2 = ContextManager.CreateObjectContext(caller, t);
             break;
         case TpmCc.ContextLoad:
         case TpmCc.ContextSave:
             throw new Exception("ProcessUpdatedTpmState: Should not be here");
         case TpmCc.FlushContext:
         case TpmCc.SequenceComplete:
             ContextManager.Remove(inputObjects[0]);
             break;
         case TpmCc.EventSequenceComplete:
             ContextManager.Remove(inputObjects[1]);
             break;
     }
 }
Ejemplo n.º 49
0
 public TpmiRhNvIndex(TpmHandle h) : base(h, TpmHandle.Bind.ByRef)
 {
 }
Ejemplo n.º 50
0
 private void CleanTpm()
 {
     var loaded = new TpmHandle[3][];
     loaded[0] = GetLoadedEntities(Tpm, Ht.Transient);
     loaded[1] = GetLoadedEntities(Tpm, Ht.LoadedSession);
     loaded[2] = GetLoadedEntities(Tpm, TpmHelpers.GetEnumerator<Ht>("ActiveSession", "SavedSession"));
     foreach (TpmHandle[] arr in loaded)
     {
         foreach (TpmHandle h in arr)
         {
             Tpm.FlushContext(h);
         }
     }
 }
Ejemplo n.º 51
0
 /// <summary>
 /// Look up TBS ObjectContext records given the handles in the inHandles input parms.
 /// </summary>
 /// <param name="caller"></param>
 /// <param name="inHandles"></param>
 /// <returns></returns>
 private ObjectContext[] GetReferencedObjects(TbsContext caller, TpmHandle[] inHandles)
 {
     var neededContexts = new ObjectContext[inHandles.Length];
     for (int j = 0; j < inHandles.Length; j++)
     {
         neededContexts[j] = ContextManager.GetContext(caller, inHandles[j]);
         if (neededContexts[j] == null)
         {
             return null;
         }
     }
     return neededContexts;
 }
Ejemplo n.º 52
0
 /// <summary>
 /// Modifies the handles and sessions arrays so that they contain the translated handles.
 /// </summary>
 /// <param name="handles"></param>
 /// <param name="sessions"></param>
 /// <param name="theObjects"></param>
 /// <param name="theSessions"></param>
 private void ReplaceHandlesIn(TpmHandle[] handles, SessionIn[] sessions, ObjectContext[] theObjects, ObjectContext[] theSessions)
 {
     for (int j = 0; j < handles.Length; j++)
     {
         handles[j] = theObjects[j].TheTpmHandle;
     }
     for (int j = 0; j < sessions.Length; j++)
     {
         sessions[j].handle = theSessions[j].TheTpmHandle;
     }
 }
Ejemplo n.º 53
0
 /// <summary>
 /// Called from TpmPolicyNV.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicyNvCallback(TpmPolicyNV ace, out TpmHandle authHandle, out TpmHandle nvHandle, out SessionBase authSession)
 {
     if (PolicyNVCallback == null)
     {
         throw new Exception("No policyNV callback installed.");
     }
     PolicyNVCallback(this, ace, out authSession, out authHandle, out nvHandle);
 }
Ejemplo n.º 54
0
 internal static SlotType SlotTypeFromHandle(TpmHandle h)
 {
     switch (h.GetType())
     {
         case Ht.Transient:
             return SlotType.ObjectSlot;
         case Ht.PolicySession:
         case Ht.HmacSession:
             return SlotType.SessionSlot;
         default:
             return SlotType.NoSlot;
     }
 }
Ejemplo n.º 55
0
 /// <summary>
 /// Called from TpmPolicySecret.
 /// </summary>
 /// <returns></returns>
 internal void ExecutePolicySecretCallback(TpmPolicySecret ace, out SessionBase authorizingSession, out TpmHandle authorizedEntityHandle, out bool flushAuthEntity)
 {
     if (PolicySecretCallback == null)
     {
         throw new Exception("No policy secret callback installed.");
     }
     PolicySecretCallback(this, ace, out authorizingSession, out authorizedEntityHandle, out flushAuthEntity);
 }
Ejemplo n.º 56
0
        private void CheckConsistency(string message = "")
        {
            TpmHandle[] loadedObjects = GetLoadedEntities(Tpm, Ht.Transient);
            TpmHandle[] loadedSessions = GetLoadedEntities(Tpm, Ht.LoadedSession);
            TpmHandle[] contextSavedSessions = GetLoadedEntities(Tpm, TpmHelpers.GetEnumerator<Ht>("ActiveSession", "SavedSession"));

            int numLoadedObject = 0, numLoadedSession = 0, numSavedSession = 0;
            foreach (ObjectContext o in ContextManager.ObjectContexts)
            {
                if (o.TheSlotType == SlotType.ObjectSlot)
                {
                    if (!o.Loaded)
                    {
                        continue;
                    }
                    Debug.Assert(loadedObjects.Contains(o.TheTpmHandle));
                    numLoadedObject++;
                }

                if (o.TheSlotType == SlotType.SessionSlot)
                {
                    if (o.Loaded)
                    {
                        Debug.Assert(loadedSessions.Contains(o.TheTpmHandle));
                        numLoadedSession++;
                    }
                    else
                    {
                        TpmHandle translatedHandle = new TpmHandle(Ht.LoadedSession, o.Context.savedHandle.GetOffset());
                        Debug.Assert(contextSavedSessions.Contains(translatedHandle));
                        numSavedSession++;
                    }
                }
            }

            Debug.Assert(numLoadedObject == loadedObjects.Length);
            Debug.Assert(numLoadedSession == loadedSessions.Length);
            Debug.Assert(numSavedSession == contextSavedSessions.Length);
        }
Ejemplo n.º 57
0
 /// <summary>
 /// This callback function provides authorization in the form of an HMAC session
 /// </summary>
 static public void PolicySecretCallback2(
     PolicyTree policyTree,
     TpmPolicySecret ace,
     out SessionBase authorizingSession,
     out TpmHandle authorizedEntityHandle,
     out bool flushAuthEntity)
 {
     AuthSession s0 = _sharedTpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha1);
     authorizingSession = s0;
     authorizedEntityHandle = _publicSealedObjectHandle;
     flushAuthEntity = true;
 }
Ejemplo n.º 58
0
 public TkHashcheck(TkHashcheck the_TkHashcheck)
 {
     if((Object) the_TkHashcheck == null ) throw new ArgumentException(Globs.GetResourceString("parmError"));
     hierarchy = the_TkHashcheck.hierarchy;
     digest = the_TkHashcheck.digest;
 }