Exemple #1
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;
        }
Exemple #2
0
        /// <summary>
        /// Seals data to the specified pcr selection,
        /// create a valid pcr selection with session.CreateEmptyPCRSelection
        /// </summary>
        /// <param name="pcrSelection"></param>
        /// <param name="data">Data to seal</param>
        /// <returns></returns>
        public byte[] Seal(TPMPCRSelection pcrSelection, byte[] data)
        {
            Parameters paramsSeal = new Parameters();

            paramsSeal.AddPrimitiveType("in_data", data);
            paramsSeal.AddPrimitiveType("key", _keyIdentifier);
            paramsSeal.AddValue("pcr_selection", pcrSelection);

            Parameters paramsSecret = new Parameters();

            paramsSecret.AddPrimitiveType("identifier", KeyIdentifier);
            ProtectedPasswordStorage authSeal = _tpmSession.RequestSecret(new HMACKeyInfo(HMACKeyInfo.HMACKeyType.SealAuth, paramsSecret));

            if (authSeal.Hashed == false)
            {
                authSeal.Hash();
            }

            authSeal.DecryptHash();
            paramsSeal.AddPrimitiveType("data_auth", authSeal.HashValue);

            try
            {
                TPMCommandResponse sealResponse = BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_Seal, paramsSeal);
                return(sealResponse.Parameters.GetValueOf <byte[]>("data"));
            }
            finally
            {
                if (authSeal != null)
                {
                    authSeal.ClearHash();
                }
            }
        }
        /// <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");
            }
        }
        /// <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;
            }
        }
Exemple #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");
        }
Exemple #6
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);
        }
Exemple #7
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!");
        }
Exemple #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
            }
        }
Exemple #9
0
        public override void Read(Stream src)
        {
            base.Read(src);

            if (Succeeded)
            {
                _commandResponse = new TPMCommandResponse(src);
            }
        }
Exemple #10
0
        /// <summary>
        /// Unbinds the specified data, the encrypted data needs to be
        /// of type TPMBoundData
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Returns the decrypted data</returns>
        public byte[] Unbind(byte[] data)
        {
            Parameters paramsUnbind = new Parameters();

            paramsUnbind.AddPrimitiveType("in_data", data);
            paramsUnbind.AddPrimitiveType("key", _keyIdentifier);

            TPMCommandResponse unbindResponse = BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_Unbind, paramsUnbind);

            return(unbindResponse.Parameters.GetValueOf <byte[]>("data"));
        }
Exemple #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);
        }
Exemple #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");
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Unseals the specified data
        /// </summary>
        /// <param name="data">Data to seal</param>
        /// <returns></returns>
        public byte[] Unseal(byte[] data)
        {
            Parameters paramsSeal = new Parameters();

            paramsSeal.AddPrimitiveType("in_data", data);
            paramsSeal.AddPrimitiveType("key", _keyIdentifier);

            Parameters paramsSecret = new Parameters();

            paramsSecret.AddPrimitiveType("identifier", KeyIdentifier);


            TPMCommandResponse unsealResponse = BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_Unseal, paramsSeal);

            return(unsealResponse.Parameters.GetValueOf <byte[]>("data"));
        }
Exemple #14
0
        /// <summary>
        /// Cryptographically reports the selected PCR values and returns
        /// the TPMPCRComposite and the generated signature. If no
        /// external data is supplied a random nonce is generated on the server.
        /// The length of externalData is defined by the hashing algorithm used by the TPM
        /// </summary>
        /// <param name="pcrs"></param>
        /// <param name="externalData">Nonce used for the quoting operation,
        /// use CreateCompatibleHashAlgorithm or CreateCompatibleHashProvider to generate a hash value
        /// with the correct length</param>
        /// <returns></returns>
        public QuoteResponse Quote(TPMPCRSelection pcrs, byte[] externalData)
        {
            Parameters quoteParameters = new Parameters();

            quoteParameters.AddPrimitiveType("key", _keyIdentifier);
            quoteParameters.AddValue("targetPCR", pcrs);

            if (externalData != null)
            {
                quoteParameters.AddPrimitiveType("externalData", externalData);
            }

            TPMCommandResponse response = BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_Quote, quoteParameters);

            return(new QuoteResponse(response.Parameters.GetValueOf <TPMPCRComposite>("pcrData"),
                                     response.Parameters.GetValueOf <byte[]>("sig")));
        }
Exemple #15
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);
        }
Exemple #16
0
        public override TPMCommandResponse Process()
        {
            TPMBlob requestBlob = new TPMBlob();

            requestBlob.WriteCmdHeader(TPMCmdTags.TPM_TAG_RQU_COMMAND, TPMOrdinals.TPM_ORD_PcrRead);
            requestBlob.WriteUInt32((uint)_register);
            requestBlob.WriteCmdSize();

            TPMBlob    responseBlob  = TransmitMe(requestBlob);
            Parameters responseParam = new Parameters();


            byte[] val = responseBlob.ReadBytes(20);

            responseParam.AddPrimitiveType("pcrnum", _register);
            responseParam.AddPrimitiveType("value", val);


            TPMCommandResponse response = new TPMCommandResponse(true, TPMCommandNames.TPM_CMD_PCRRead, responseParam);

            return(response);
        }
Exemple #17
0
        public override void Init(Parameters param, TPMProvider tpmProvider, TPMWrapper tpmWrapper)
        {
            base.Init(param, tpmProvider, tpmWrapper);


            _digest         = null;
            _responseDigest = null;
            _inData         = param.GetValueOf <byte[]>("in_data");
            _pcrInfo        = new TPMPCRInfoCore(new TPMPCRSelectionCore(param.GetValueOf <TPMPCRSelection>("pcr_selection")));

            _pcrInfo.CalculateDigests((TPMPCRInfoCore.GetPCRValueDelegate) delegate(uint pcrNum)
            {
                //TODO: Use TPM_Quote to determine pcr values once it's available

                Parameters pcrParams = new Parameters();
                pcrParams.AddPrimitiveType("pcrnum", pcrNum);
                TPMCommandResponse pcrResponse = _tpmWrapper.Process(new TPMCommandRequest(TPMCommandNames.TPM_CMD_PCRRead, pcrParams));
                if (!pcrResponse.Status)
                {
                    throw new TPMResponseException("An unknown error occured on performing pcrread");
                }
                return(pcrResponse.Parameters.GetValueOf <byte[]>("value"));
            });
        }
Exemple #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);
        }
Exemple #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");
            }
        }
Exemple #20
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));
        }
Exemple #21
0
        public ClientKeyHandle CreateKey(string friendlyName, uint keyLength, TPMKeyUsage keyUsage, TPMKeyFlags keyFlags)
        {
            Parameters paramsCreateWrapKey = new Parameters();

            paramsCreateWrapKey.AddPrimitiveType("parent", KeyIdentifier);
            paramsCreateWrapKey.AddPrimitiveType("key_usage", keyUsage);
            paramsCreateWrapKey.AddPrimitiveType("key_flags", keyFlags);
            paramsCreateWrapKey.AddPrimitiveType("key_length", keyLength);
            paramsCreateWrapKey.AddPrimitiveType("exponent", new byte[0]);
            paramsCreateWrapKey.AddPrimitiveType("num_primes", (uint)0);

            if (keyUsage == TPMKeyUsage.TPM_KEY_SIGNING)
            {
                paramsCreateWrapKey.AddPrimitiveType("enc_scheme", TPMEncScheme.TPM_ES_NONE);
                paramsCreateWrapKey.AddPrimitiveType("sig_scheme", TPMSigScheme.TPM_SS_RSASSAPKCS1v15_SHA1);
            }
            else
            {
                paramsCreateWrapKey.AddPrimitiveType("enc_scheme", TPMEncScheme.TPM_ES_RSAESOAEP_SHA1_MGF1);
                paramsCreateWrapKey.AddPrimitiveType("sig_scheme", TPMSigScheme.TPM_SS_NONE);
            }

            Parameters parameters = new Parameters();

            parameters.AddPrimitiveType("identifierIsFriendlyName", true);
            parameters.AddPrimitiveType("identifier", friendlyName);

            ProtectedPasswordStorage authUsage = _tpmSession.RequestSecret(
                new HMACKeyInfo(HMACKeyInfo.HMACKeyType.KeyUsageSecret, parameters));

            if (authUsage.Hashed == false)
            {
                authUsage.Hash();
            }

            authUsage.DecryptHash();
            paramsCreateWrapKey.AddPrimitiveType("usage_auth", authUsage.HashValue);

            ProtectedPasswordStorage authMigration = null;

            if ((keyFlags & TPMKeyFlags.Migratable) == TPMKeyFlags.Migratable)
            {
                authMigration = _tpmSession.RequestSecret(
                    new HMACKeyInfo(HMACKeyInfo.HMACKeyType.KeyMigrationSecret, parameters));
                authMigration.DecryptHash();
                paramsCreateWrapKey.AddPrimitiveType("migration_auth", authMigration.HashValue);
            }
            else
            {
                paramsCreateWrapKey.AddPrimitiveType("migration_auth", new byte[20]);
            }

            try
            {
                TPMCommandResponse responseCreateWrapKey =
                    BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_CreateWrapKey, paramsCreateWrapKey);

                _tpmSession.Keystore.AddKey(
                    friendlyName,
                    responseCreateWrapKey.Parameters.GetValueOf <string>("key_identifier"),
                    this.FriendlyName,
                    responseCreateWrapKey.Parameters.GetValueOf <byte[]>("key_data"));

                return(new ClientKeyHandle(friendlyName, responseCreateWrapKey.Parameters.GetValueOf <string>("key_identifier"), _tpmSession));
            }
            finally
            {
                if (authMigration != null)
                {
                    authMigration.ClearHash();
                }

                if (authUsage != null)
                {
                    authUsage.ClearHash();
                }
            }
        }