Example #1
0
        /// <summary>
        /// Performs the actual swap-in operation
        /// </summary>
        /// <param name="item"></param>
        protected override void SwappedIn(AuthHandleItem item)
        {
            //uint oldHandle = item.AuthHandle.Handle;
            if (item.Status != AuthHandleItem.AuthHandleStatus.SwappedOut)
            {
                throw new ArgumentException("Invalid auth handle state for swap in operation");
            }

            using (new LockContext(_authHandles, "AuthHandleManager::SwappedIn"))
            {
                if (AvailableSessionSlots <= LoadedSessions)
                {
                    SwapOut();
                }


                Parameters swapInParameters = new Parameters();
                swapInParameters.AddValue("handle", item.AuthHandle);
                swapInParameters.AddPrimitiveType("context_blob", item.AuthHandle.ContextBlob);

                TPMCommandRequest swapInRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_LoadContext, swapInParameters);

                TPMCommandResponse swapInResponse = _tpmContext.TPM.Process(swapInRequest);
                if (swapInResponse.Status == false)
                {
                    throw new TPMRequestException("Unknown error while swap in operation");
                }

                item.AuthHandle.Handle = swapInResponse.Parameters.GetValueOf <ITPMHandle>("handle").Handle;
                item.Status            = AuthHandleItem.AuthHandleStatus.SwappedIn;
            }
        }
Example #2
0
        /// <summary>
        /// Performs the actual swap-out operation
        /// </summary>
        /// <param name="item"></param>
        protected override void SwappedOut(AuthHandleItem item)
        {
            if (item.Status != AuthHandleItem.AuthHandleStatus.SwappedIn)
            {
                throw new ArgumentException("Invalid auth handle state for swap out operation");
            }

            using (new LockContext(_authHandles, "AuthHandleManager::SwappedOut"))
            {
                Parameters swapOutParameters = new Parameters();
                swapOutParameters.AddValue("handle", item.AuthHandle);
                TPMCommandRequest swapOutRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_SaveContext, swapOutParameters);

                TPMCommandResponse swapOutResponse = _tpmContext.TPM.Process(swapOutRequest);

                if (swapOutResponse.Status == false)
                {
                    throw new TPMRequestException("Unknown error while swap out operation");
                }


                item.Status = AuthHandleItem.AuthHandleStatus.SwappedOut;
                item.AuthHandle.ContextBlob = swapOutResponse.Parameters.GetValueOf <byte[]>("context_blob");
            }
        }
Example #3
0
        private static void ReadPCRs(TPMWrapper tpm)
        {
            uint i = 0;

            ILog log = LogManager.GetLogger("ReadPCRs");

            Parameters param = new Parameters();

            param.AddPrimitiveType("capArea", CapabilityData.TPMCapabilityArea.TPM_CAP_PROPERTY);
            param.AddPrimitiveType("subCap", CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_PCR);
            TPMCommandRequest  request  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetCapability, param);
            TPMCommandResponse response = tpm.Process(request);

            uint maxPcrs = response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_PCR);

            for (i = 0; i < maxPcrs; ++i)
            {
                param = new Parameters();
                param.AddPrimitiveType("pcrnum", i);
                TPMCommandRequest  req  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_PCRRead, param);
                TPMCommandResponse resp = tpm.Process(req);

                byte[] val = resp.Parameters.GetValueOf <byte[]>("value");

                log.InfoFormat("Answer for PCR {0} is: 0x{1}", resp.Parameters.GetValueOf <UInt32>("pcrnum"),
                               ByteHelper.ByteArrayToHexString(val));
            }

//			TPMCommandRequest req = new TPMCommandRequest(TPMCommandNames.TPM_CMD_PCRRead, null);
//			TPMCommand com = TPMCommandFactory.Create(req);
//			com.Init(param, tpm);
//			com.Process();
            //Console.WriteLine ("Hello World!");
        }
Example #4
0
        /// <summary>
        /// Performs the actual swap-in operation
        /// </summary>
        /// <param name="item"></param>
        protected override void SwappedIn(KeyHandleItem item)
        {
            if (item.Status != KeyHandleItem.KeyHandleStatus.SwappedOut)
            {
                throw new ArgumentException("Invalid key handle state for swap in operation");
            }

            if (AvailableKeySlots <= LoadedKeys)
            {
                SwapOut();
            }


            Parameters swapInParameters = new Parameters();

            swapInParameters.AddValue("handle", item.KeyHandle);
            swapInParameters.AddPrimitiveType("context_blob", item.KeyHandle.ContextBlob);

            TPMCommandRequest swapInRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_LoadContext, swapInParameters);

            TPMCommandResponse swapInResponse = _tpmContext.TPM.Process(swapInRequest);

            if (swapInResponse.Status == false)
            {
                throw new TPMRequestException("Keymanager: Unknown error while swap in operation");
            }

            item.KeyHandle.Handle = swapInResponse.Parameters.GetValueOf <ITPMHandle>("handle").Handle;
        }
Example #5
0
        /// <summary>
        /// Performs the actual swap-out operation
        /// </summary>
        /// <param name="item"></param>
        protected override void SwappedOut(KeyHandleItem item)
        {
            if (item.Status != KeyHandleItem.KeyHandleStatus.SwappedIn)
            {
                throw new ArgumentException("Invalid auth handle state for swap out operation");
            }

            Parameters swapOutParameters = new Parameters();

            swapOutParameters.AddValue("handle", item.KeyHandle);
            TPMCommandRequest swapOutRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_SaveContext, swapOutParameters);

            TPMCommandResponse swapOutResponse = _tpmContext.TPM.Process(swapOutRequest);

            if (swapOutResponse.Status == false)
            {
                throw new TPMRequestException("Unknown error while swap out operation");
            }

            //For key handles the tpm does not release the memory after save context
            TPMCommandRequest  flushRequest  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_FlushSpecific, swapOutParameters);
            TPMCommandResponse flushResponse = _tpmContext.TPM.Process(flushRequest);

            if (flushResponse.Status == false)
            {
                throw new TPMRequestException("Unknown error while swap out (flush) operation");
            }



            item.Status = KeyHandleItem.KeyHandleStatus.SwappedOut;
            item.KeyHandle.ContextBlob = swapOutResponse.Parameters.GetValueOf <byte[]>("context_blob");
        }
Example #6
0
        public override void Read(Stream src)
        {
            base.Read(src);

            _tpmIdentifier  = StreamHelper.ReadInt32(src);
            _commandRequest = new TPMCommandRequest(src);
        }
Example #7
0
        private static AuthHandle EstablishOIAP(TPMWrapper tpm)
        {
            ILog log = LogManager.GetLogger("EstablishOIAP");

            for (int i = 0; i < 2; i++)
            {
                TPMCommandRequest  request  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_OIAP, new Parameters());
                TPMCommandResponse response = tpm.Process(request);

                AuthHandle myAuthHandle = response.Parameters.GetValueOf <AuthHandle> ("auth_handle");

//				Parameters parameters = new Parameters ();
                //				parameters.AddValue ("handle", myAuthHandle);
                //				TPMCommandRequest requestFlush = new TPMCommandRequest (TPMCommandNames.TPM_CMD_FLUSH_SPECIFIC, parameters);
                //				tpm.Process (requestFlush);

                //return myAuthHandle;
            }

            Parameters listHandlesParameters = new Parameters();

            listHandlesParameters.AddPrimitiveType("capArea", CapabilityData.TPMCapabilityArea.TPM_CAP_HANDLE);
            listHandlesParameters.AddPrimitiveType("handle_type", TPMResourceType.TPM_RT_AUTH);

            TPMCommandRequest  listHandlesRequest  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetCapability, listHandlesParameters);
            TPMCommandResponse listHandlesResponse = tpm.Process(listHandlesRequest);

            HandleList loadedKeyHandles = listHandlesResponse.Parameters.GetValueOf <HandleList> ("handles");



            return(null);
        }
Example #8
0
        /// <summary>
        /// Reads the configured tpm devices from the configuration and
        /// sets up the corresponding tpm contexts
        /// </summary>
        private void SetupTPMContexts()
        {
            IConnectionsConfiguration connectionConfig = (IConnectionsConfiguration)ConfigurationManager.GetSection("connections");

            foreach (Iaik.Tc.TPM.Configuration.DotNetConfiguration.TPMDevice device in connectionConfig.TpmDevices)
            {
                try
                {
                    _logger.InfoFormat("Setting up tpm context '{0}'", device.TPMName);
                    TPMWrapper tpmDevice = new TPMWrapper();
                    tpmDevice.Init(device.TPMType, device.Parameters);
                    TPMContext tpmContext = new TPMContext(device.TPMName, tpmDevice);
                    _tpmContexts.Add(device.TPMName, tpmContext);

                    _logger.InfoFormat("Flushing device '{0}'", device.TPMName);
                    foreach (TPMResourceType resourceType in new TPMResourceType[] {
                        TPMResourceType.TPM_RT_AUTH, TPMResourceType.TPM_RT_KEY
                    })
                    {
                        Parameters listLoadedHandlesParameters = new Parameters();
                        listLoadedHandlesParameters.AddPrimitiveType("capArea", CapabilityData.TPMCapabilityArea.TPM_CAP_HANDLE);
                        listLoadedHandlesParameters.AddPrimitiveType("handle_type", resourceType);
                        TPMCommandRequest listLoadedHandlesRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetCapability,
                                                                                           listLoadedHandlesParameters);
                        TPMCommandResponse response = tpmDevice.Process(listLoadedHandlesRequest);

                        if (response.Status == false)
                        {
                            throw new Exception("An unknown tpm exception while flushing occured");
                        }

                        foreach (uint handle in response.Parameters.GetValueOf <HandleList> ("handles"))
                        {
                            Parameters flushParameters = new Parameters();
                            flushParameters.AddValue("handle", HandleFactory.Create(resourceType, handle));
                            TPMCommandRequest  flushRequest  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_FlushSpecific, flushParameters);
                            TPMCommandResponse flushResponse = tpmDevice.Process(flushRequest);

                            if (flushResponse.Status == false)
                            {
                                throw new Exception("Something went wrong while flushing");
                            }
                        }
                    }

                    _logger.InfoFormat("Successfully setup tpm context '{0}' with type '{1}'", device.TPMName, device.TPMType);
                }
                catch (Exception ex)
                {
                    _logger.FatalFormat("Error setting up tpm device '{0}', the device will not be available ({1})", device.TPMName, ex);
                }

                ///Set the Assembly search order for incoming Parameters so that core classes are always at first
                Parameters.AssemblySearchOrder = new Assembly[] {
                    typeof(TPMWrapper).Assembly,                     //lib core
                    typeof(ITypedParameter).Assembly
                };                                                   //lib common
            }
        }
Example #9
0
        public TPMCommandResponse Process(TPMCommandRequest request, ICommandAuthorizationHelper commandAuthorizationHelper,
                                          IKeyManagerHelper keyManager)
        {
            TPMCommand command = TPMCommandFactory.Create(request.CommandIdentifier);

            command.SetCommandLockProvider(_commandLockProvider);
            command.SetKeyManager(keyManager);
            command.SetCommandAuthorizationHelper(commandAuthorizationHelper);
            command.Init(request.Parameters, _backend, this);
            return(command.Process());
        }
Example #10
0
        internal TPMCommandResponse DoTPMCommandRequest(TPMCommandRequest commandRequest)
        {
            TPMRequest request = new TPMRequest(_ctx);

            request.TPMIdentifier  = _sessionIdentifier;
            request.CommandRequest = commandRequest;

            TPMResponse response = request.TypedExecute();

            response.AssertTPMSuccess();
            return(response.CommandResponse);
        }
Example #11
0
        private TPMCommandResponse BuildDoVerifyRequest(string commandIdentifier, Parameters parameters)
        {
            TPMCommandRequest  versionRequest = new TPMCommandRequest(commandIdentifier, parameters);
            TPMCommandResponse response       = _tpmSession.DoTPMCommandRequest(versionRequest);

            if (response.Status == false)
            {
                throw new TPMRequestException("An unknown tpm error occured");
            }

            return(response);
        }
Example #12
0
        private static void ReadCapabilities(TPMWrapper tpm)
        {
            ILog log = LogManager.GetLogger("ReadCapabilities");

            // Read out each capability property
            foreach (CapabilityData.TPMSubCapProperty subCap in Enum.GetValues(typeof(CapabilityData.TPMSubCapProperty)))
            {
                Parameters param = new Parameters();
                param.AddPrimitiveType("capArea", CapabilityData.TPMCapabilityArea.TPM_CAP_PROPERTY);
                param.AddPrimitiveType("subCap", subCap);
                TPMCommandRequest  request  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetCapability, param);
                TPMCommandResponse response = tpm.Process(request);
                switch (subCap)
                {
                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_PCR:
                    log.InfoFormat("Number of PCRs is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_PCR));
                    break;

                //case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_DIR:
                //    log.InfoFormat("Number of DIR is {0} and should be 1 because command is deprecated", response.Parameters.GetValueOf<uint>(CapabilityData.PARAM_PROP_DIR));
                //    break;
                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_MANUFACTURER:
                    log.InfoFormat("Manufacturer ID is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_MANUFACTURER));
                    break;

                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_KEYS:
                    log.InfoFormat("Number of free keyslots is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_KEYS));
                    break;

                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_MAX_AUTHSESS:
                    log.InfoFormat("Number of max Auth Sessions is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_MAX_AUTHSESS));
                    break;

                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_MAX_TRANSESS:
                    log.InfoFormat("Number of max Trans Sessions is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_MAX_TRANSESS));
                    break;

                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_MAX_KEYS:
                    log.InfoFormat("Number of max keys (without EK and SRK) is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_MAX_KEYS));
                    break;

                case CapabilityData.TPMSubCapProperty.TPM_CAP_PROP_MAX_SESSIONS:
                    log.InfoFormat("Number of max Sessions is {0}", response.Parameters.GetValueOf <uint>(CapabilityData.PARAM_PROP_MAX_SESSIONS));
                    break;

                default:
                    throw new NotSupportedException("Defined cap or subcap are not supported");
                }
            }
        }
Example #13
0
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            _forEncryption = forEncryption;

            if (forEncryption)
            {
                _encryptor = _keyHandle.PublicKey.CreateRSAEncrypter();

                Parameters bindParameters = new Parameters();
                bindParameters.AddPrimitiveType("type", "request_prefix");
                TPMCommandRequest bindPrefixRequest = new TPMCommandRequest(
                    TPMCommandNames.TPM_CMD_Bind, bindParameters);
                _prefix = _session.DoTPMCommandRequest(bindPrefixRequest).Parameters.GetValueOf <byte[]>("prefix");
            }
        }
Example #14
0
        /// <summary>
        /// Really destroys the auth handle on the tpm AND in the local cache
        /// </summary>
        /// <param name="item">
        /// A <see cref="AuthHandleItem"/>
        /// </param>
        private void InternalDestroyHandle(AuthHandleItem item)
        {
            Parameters parameters = new Parameters();

            parameters.AddValue("handle", item.AuthHandle);
            parameters.AddPrimitiveType("ignore_tpm_error", true);
            TPMCommandRequest destroyHandleRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_FlushSpecific, parameters);

            TPMCommandResponse destroyHandleResponse = _tpmContext.TPM.Process(destroyHandleRequest);

            if (!destroyHandleResponse.Status)
            {
                throw new TPMRequestException("Error on flushing auth handle context, aborting");
            }

            _logger.DebugFormat("Authhandles before remove: {0}", _authHandles);
            InternalRemoveAuthHandle(item);
            _logger.DebugFormat("Authhandles after remove: {0}", _authHandles);
        }
Example #15
0
        public static TPMCommand Create(TPMCommandRequest request)
        {
            if (commands_.ContainsKey(request.CommandIdentifier))
            {
                ConstructorInfo ctorInfo = commands_[request.CommandIdentifier].GetConstructor(new Type[0]);
                if (ctorInfo == null)
                {
                    throw new ArgumentException(string.Format("Cannot create TpmCommand for command request with identifier '{0}'",
                                                              request.CommandIdentifier));
                }

                return((TPMCommand)ctorInfo.Invoke(new object[0]));
            }
            else
            {
                throw new NotSupportedException(string.Format("Cannot find TpmCommand for command request with identifier '{0}'",
                                                              request.CommandIdentifier));
            }
        }
Example #16
0
        /// <summary>
        /// Flushes all keys that belong to the specified context
        /// </summary>
        /// <param name="keyContext">context to check</param>
        public void UnloadKeysOfContext(object keyContext)
        {
            using (AcquireLock())
            {
                List <KeyHandleItem> keysToRemove = new List <KeyHandleItem>();
                foreach (KeyHandleItem item in _keyHandles)
                {
                    if (item.KeyContext.Equals(keyContext))
                    {
                        keysToRemove.Add(item);
                    }
                }

                foreach (KeyHandleItem item in keysToRemove)
                {
                    _keyHandles.RemoveKeyHandle(item);

                    //Flush the key
                    if (item.Status == KeyHandleItem.KeyHandleStatus.SwappedIn)
                    {
                        Parameters flushParams = new Parameters();
                        flushParams.AddValue("handle", item.KeyHandle);
                        TPMCommandRequest flushRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_FlushSpecific, flushParams);
                        _tpmContext.TPM.Process(flushRequest);
                    }
                    //Flush the context
                    else if (item.Status == KeyHandleItem.KeyHandleStatus.SwappedOut)
                    {
                        Parameters flushParams = new Parameters();
                        flushParams.AddValue("handle", new ContextHandle(item.KeyHandle.ContextBlob));
                        TPMCommandRequest flushRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_FlushSpecific, flushParams);
                        _tpmContext.TPM.Process(flushRequest);
                    }
                }
            }
        }
Example #17
0
        protected override TPMCommandResponse InternalProcess()
        {
            TPMBlob requestBlob = new TPMBlob();

            requestBlob.WriteCmdHeader(TPMCmdTags.TPM_TAG_RQU_AUTH1_COMMAND, TPMOrdinals.TPM_ORD_Quote);

            //key handle gets inserted later, it may be not available now
            requestBlob.WriteUInt32(0);
            requestBlob.Write(_nonce, 0, 20);
            _pcrSelection.WriteToTpmBlob(requestBlob);

            _keyManager.LoadKey(_params.GetValueOf <string>("key"));

            AuthorizeMe(requestBlob);

            using (_keyManager.AcquireLock())
            {
                requestBlob.SkipHeader();
                requestBlob.WriteUInt32(_keyManager.IdentifierToHandle(_params.GetValueOf <string>("key")).Handle);
                _responseBlob = TransmitMe(requestBlob);
            }

            CheckResponseAuthInfo();

            _responseBlob.SkipHeader();

            TPMPCRCompositeCore pcrComposite = TPMPCRCompositeCore.CreateFromTPMBlob(_responseBlob);
            uint sigSize = _responseBlob.ReadUInt32();

            byte[] signature = _responseBlob.ReadBytes((int)sigSize);

            // Do signature verification
            TPMQuoteInfoCore quoteInfo = TPMQuoteInfoCore.Create(new HashProvider().Hash(new HashTPMBlobWritableDataProvider(pcrComposite)), _nonce);

            byte[] signingData;
            using (TPMBlob blob = new TPMBlob())
            {
                quoteInfo.WriteToTpmBlob(blob);
                signingData = blob.ToArray();
            }

            Parameters pubKeyParams = new Parameters();

            pubKeyParams.AddPrimitiveType("key", _params.GetValueOf <string>("key"));
            TPMCommandRequest  pubKeyRequest  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_GetPubKey, pubKeyParams);
            TPMCommandResponse pubKeyResponse = _tpmWrapper.Process(pubKeyRequest,
                                                                    _commandAuthHelper, _keyManager);

            if (pubKeyResponse.Status == false)
            {
                _log.FatalFormat("TPM_Quote: Could not retrieve pubkey of key");
                return(new TPMCommandResponse(false, TPMCommandNames.TPM_CMD_Quote, new Parameters()));
            }

            TPMKey    keyInfo = TPMKeyCore.CreateFromBytes(_keyManager.GetKeyBlob(_params.GetValueOf <string>("key")));
            TPMPubkey pubkey  = pubKeyResponse.Parameters.GetValueOf <TPMPubkey>("pubkey");

            if (SignatureVerification.VerifySignature(keyInfo, pubkey, signingData, signature) == false)
            {
                throw new ArgumentException("The TPM_Quote signature could not be verified");
            }

            Parameters responseParams = new Parameters();

            responseParams.AddValue("pcrData", pcrComposite);
            responseParams.AddPrimitiveType("sig", signature);

            return(new TPMCommandResponse(true, TPMCommandNames.TPM_CMD_Quote, responseParams));
        }
Example #18
0
        /// <summary>
        /// Recursivly loads the specified key hierachy and returns the identifier of the parent key
        /// </summary>
        /// <param name="identifier">identifier of the key whos parent should be loaded</param>
        /// <param name="keyContext"></param>
        /// <param name="keystore"></param>
        /// <returns></returns>
        private string InternalLoadKey(string identifier, object keyContext, IKeyManagerHelper keymanagerHelper, ICommandAuthorizationHelper commandAuthHelper)
        {
            if (identifier == KeyHandle.KEY_SRK)
            {
                return(null);
            }

            //SRK
            if (identifier == null)
            {
                return(null);
            }

            if (keymanagerHelper.ContainsIdentifier(identifier) == false)
            {
                throw new ArgumentException(string.Format("Keystore does not contain key with identifier: '{0}'", identifier));
            }


            bool          reloadKey     = true;
            KeyHandleItem keyHandleItem = null;

            while (reloadKey)
            {
                using (AcquireLock())
                {
                    keyHandleItem = _keyHandles.FindKeyHandleItem(identifier, keyContext);


                    if (keyHandleItem == null)
                    {
                        //If no key handle with such an identifier exists, add a NotLoaded entry,
                        //so other threads can wait for that handle to become ready
                        _keyHandles.AddKeyHandle(new KeyHandleItem(new KeyHandle(identifier, 0),
                                                                   KeyHandleItem.KeyHandleStatus.NotLoaded, keyContext));
                    }
                }

                reloadKey = false;
                //The key is currently being loaded, wait till the loading process has finished/or failed
                if (keyHandleItem != null && keyHandleItem.Status == KeyHandleItem.KeyHandleStatus.NotLoaded)
                {
                    keyHandleItem.LoadedEvt.WaitOne();
                    reloadKey = true;
                }
            }

            //Key is already loaded/swaped out
            if (keyHandleItem != null)
            {
                IdentifierToHandle(identifier, keyContext, keymanagerHelper);
                return(identifier);
            }



            string parentKey = keymanagerHelper.FindParentKey(identifier);

            InternalLoadKey(parentKey, keyContext, keymanagerHelper, commandAuthHelper);

            Parameters paramLoadKey = new Parameters();

            // Load the key

            //SRK
            if (parentKey == null || parentKey == KeyHandle.KEY_SRK)
            {
                paramLoadKey.AddPrimitiveType("parent_key_srk", true);
            }
            else
            {
                paramLoadKey.AddPrimitiveType("parent_key_srk", false);
                //paramLoadKey.AddPrimitiveType("parent_handle", IdentifierToHandle(parentKey, keyContext, keymanagerHelper));
                paramLoadKey.AddPrimitiveType("parent_identifier", parentKey);
            }

            paramLoadKey.AddPrimitiveType("key_identifier", identifier);
            paramLoadKey.AddPrimitiveType("key_blob", keymanagerHelper.GetKeyBlob(identifier));

            TPMCommandRequest  requestLoadKey  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_LoadKey2, paramLoadKey);
            TPMCommandResponse responseLoadKey = _tpmContext.TPM.Process(requestLoadKey, commandAuthHelper, keymanagerHelper);

            if (responseLoadKey.Status == false)
            {
                KeyHandleItem keyHandleToRemove = _keyHandles.FindKeyHandleItem(identifier, keyContext);
                if (keyHandleToRemove != null)
                {
                    keyHandleItem.LoadedEvt.Set();
                    _keyHandles.RemoveKeyHandle(keyHandleToRemove);
                }
                throw new TPMRequestException("Unknown error on running TPM_LoadKey2");
            }

            using (AcquireLock())
            {
                //Make sure that a dummy (not loaded) keyhandleitem get removed
                KeyHandleItem keyHandleToRemove = _keyHandles.FindKeyHandleItem(identifier, keyContext);
                if (keyHandleToRemove != null)
                {
                    keyHandleToRemove.LoadedEvt.Set();
                    _keyHandles.RemoveKeyHandle(keyHandleToRemove);
                }

                KeyHandleItem item = new KeyHandleItem(responseLoadKey.Parameters.GetValueOf <KeyHandle>("handle"),
                                                       KeyHandleItem.KeyHandleStatus.SwappedIn, keyContext);
                _keyHandles.AddKeyHandle(item);

                AddNewItem(item);
            }

            return(parentKey);
        }
Example #19
0
        private AuthHandleItem CreateAuthHandle(IAuthorizableCommand cmd, AuthSessionNum authSession)
        {
            if (cmd.SupportsAuthType(AuthHandle.AuthType.OIAP))
            {
                TPMCommandRequest  oiapRequest  = new TPMCommandRequest(TPMCommandNames.TPM_CMD_OIAP, new Parameters());
                TPMCommandResponse oiapResponse = _tpmContext.TPM.Process(oiapRequest, cmd.CommandAuthHelper, cmd.KeyManager);
                if (oiapResponse.Status == false)
                {
                    throw new TPMRequestException("Unknown error while creating oiap auth handle");
                }

                AuthHandle     newAuthHandle  = oiapResponse.Parameters.GetValueOf <AuthHandle>("auth_handle");
                AuthHandleItem authHandleItem = new AuthHandleItem(newAuthHandle, AuthHandleItem.AuthHandleStatus.SwappedIn);
                authHandleItem.AssociatedCommand = new KeyValuePair <AuthSessionNum, IAuthorizableCommand>(authSession, cmd);

                using (new LockContext(_authHandles, "CreateAuthHandle OIAP"))
                {
                    _authHandles.AddAuthHandle(authHandleItem);
                    AddNewItem(authHandleItem);
                }

                return(authHandleItem);
            }
            else if (cmd.SupportsAuthType(AuthHandle.AuthType.OSAP))
            {
                Parameters parameters = new Parameters();
                parameters.AddPrimitiveType("entity_msb", TPMEntityTypeMSB.TPM_ET_XOR);
                parameters.AddPrimitiveType("entity_lsb", cmd.GetEntityType(authSession));
                string identifier = cmd.GetHandle(authSession);

                if (identifier == null)
                {
                    throw new TPMRequestException("Missing entity value for OSAP session");
                }

                parameters.AddPrimitiveType("entity_value", identifier);

                TPMCommandRequest osapRequest = new TPMCommandRequest(TPMCommandNames.TPM_CMD_OSAP, parameters);

                TPMCommandResponse osapResponse = _tpmContext.TPM.Process(osapRequest, cmd.CommandAuthHelper, cmd.KeyManager);
                if (osapResponse.Status == false)
                {
                    throw new TPMRequestException("Unknown error while creating osap auth handle");
                }

                AuthHandle     newAuthHandle  = osapResponse.Parameters.GetValueOf <AuthHandle>("auth_handle");
                AuthHandleItem authHandleItem = new AuthHandleItem(newAuthHandle, AuthHandleItem.AuthHandleStatus.SwappedIn);
                authHandleItem.AssociatedCommand = new KeyValuePair <AuthSessionNum, IAuthorizableCommand>(authSession, cmd);

                using (new LockContext(_authHandles, "CreateAuthHandle OSAP"))
                {
                    _authHandles.AddAuthHandle(authHandleItem);
                    AddNewItem(authHandleItem);
                }

                return(authHandleItem);
            }
            else
            {
                throw new NotSupportedException("Command does not support a suitable AuthType");
            }
        }
Example #20
0
 public TPMCommandResponse Process(TPMCommandRequest request)
 {
     return(Process(request, null, null));
 }