Beispiel #1
0
        /// <summary>
        /// Handles a HMAC generation request from the server
        /// </summary>
        /// <param name="subsystem"></param>
        /// <param name="requestContext"></param>
        private void HandleGenerateHMACRequest(TPMClientSubsystem subsystem, RequestContext <GenerateHMACRequest, GenerateHMACResponse> requestContext)
        {
            TPMSession session = MyClientContext.TPMClient.FindSession(requestContext.Request.TpmSessionIdentifier);

            GenerateHMACResponse response = requestContext.CreateResponse();

            if (session == null)
            {
                _logger.WarnFormat("Received HMAC request for tpm session with id #{0}, but this id is not associated with an active session!",
                                   requestContext.Request.TpmSessionIdentifier);

                response.Succeeded = false;
                response.SetKnownErrorCode(GenerateHMACResponse.ErrorCodeEnum.TPMSessionNotFound);
                response.Execute();
                return;
            }

            _logger.DebugFormat("Requesting password: {0}", requestContext.Request.KeyInfo.KeyType);
            ProtectedPasswordStorage pw = session.RequestSecret(requestContext.Request.KeyInfo);

            if (pw == null)
            {
                response.Succeeded = false;
                response.SetKnownErrorCode(GenerateHMACResponse.ErrorCodeEnum.HMACSecretMissing);
                response.Execute();
                return;
            }

            HMACProvider hmacProvider = new HMACProvider(pw);

            response.Succeeded   = true;
            response.TpmAuthData = hmacProvider.Hash(requestContext.Request.HMACDataProviders);

            response.Execute();
        }
Beispiel #2
0
        public static ProtectedPasswordStorage ReadPassword(string hintText)
        {
            Console.Write(hintText);

            ConsoleKeyInfo           consoleKeyInfo;
            ProtectedPasswordStorage pws = new ProtectedPasswordStorage();


            while (true)
            {
                consoleKeyInfo = Console.ReadKey(true);
                if (consoleKeyInfo.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    return(pws);
                }
                else if (consoleKeyInfo.Key == ConsoleKey.Escape)
                {
                    Console.WriteLine();
                    return(null);
                }
                else
                {
                    pws.AppendPasswordChar(consoleKeyInfo.KeyChar);
                }
            }
        }
        public FrontEndConnection SetupConnection()
        {
            if (File.Exists(_certificateFile) == false)
            {
                throw new FileNotFoundException(string.Format("Certificate file '{0}' could not be found", _certificateFile));
            }


            X509Certificate2 cert;

            try
            {
                cert = new X509Certificate2(_certificateFile);
            }
            catch (CryptographicException)
            {
                //maybe the certificate is password protected?
                ProtectedPasswordStorage pw =
                    _settings.RequestSecret(string.Format("Enter encryption secret for certificate '{0}'",
                                                          Path.GetFileName(_certificateFile)));

                if (pw == null)
                {
                    throw new ArgumentException(string.Format("Could not get secret for certificate '{0}'",
                                                              _certificateFile));
                }

                //FIXME: Mono implementation of this ctor does not work
                cert = new X509Certificate2(_certificateFile, pw.ExportSecureString());
            }

            return(new SslConnection(_host, _port, cert, _overwriteAuthenticationTargetHost));
        }
Beispiel #4
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();
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Creates a new counter if possible.
        /// Creating a counter requires the owner password and also the secret_counter secret
        /// </summary>
        /// <param name="label">4 bytes to label the counter</param>
        /// <returns></returns>
        public CounterContext CreateCounter(byte[] label)
        {
            if (label.Length != 4)
            {
                throw new ArgumentException("label needs to be of size 4");
            }

            ProtectedPasswordStorage counterSecret = _tpmSession.RequestSecret(new HMACKeyInfo(HMACKeyInfo.HMACKeyType.CounterSecret, new Parameters()));

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

            counterSecret.DecryptHash();

            Parameters createCounterParams = new Parameters();

            createCounterParams.AddPrimitiveType("secret", counterSecret.HashValue);
            createCounterParams.AddPrimitiveType("label", label);

            return(new CounterContext(_tpmSession,
                                      _tpmSession.DoTPMCommandRequest(new TPMCommandRequest(TPMCommandNames.TPM_CMD_CreateCounter, createCounterParams))
                                      .Parameters.GetValueOf <uint>("counter_id")
                                      ));
        }
Beispiel #6
0
        public static ProtectedPasswordStorage ReadPassword(string hintText, TPMConsole console, bool retypePw)
        {
            console.Out.Write(hintText);

            ConsoleKeyInfo consoleKeyInfo;

            ProtectedPasswordStorage[] pws;

            if (retypePw)
            {
                pws = new ProtectedPasswordStorage[] { new ProtectedPasswordStorage(), new ProtectedPasswordStorage() }
            }
            ;
            else
            {
                pws = new ProtectedPasswordStorage[] { new ProtectedPasswordStorage() }
            };

            for (int i = 0; i < pws.Length; i++)
            {
                ProtectedPasswordStorage pw = pws[i];

                if (i == 1)
                {
                    console.Out.Write("Retype password:"******"Error: Passwords do not match!");
                return(null);
            }
        }
    }
Beispiel #7
0
        public static ProtectedPasswordStorage mycallback(HMACKeyInfo keyInfo)
        {
            // We use the empty string as password ...
            ProtectedPasswordStorage pws = new ProtectedPasswordStorage();

            pws.AppendPasswordChar('i');
            pws.AppendPasswordChar('a');
            pws.AppendPasswordChar('i');
            pws.AppendPasswordChar('k');
            return(pws);
        }
Beispiel #8
0
        static ProtectedPasswordStorage RequestSecret(HMACKeyInfo keyInfo)
        {
            if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.SrkSecret)
            {
                ProtectedPasswordStorage secret = new ProtectedPasswordStorage();
                secret.WellKnown();
                return(secret);
            }

            return(ConsoleUtils.ReadPassword(String.Format("Please enter Passwd for key {0}: ",
                                                           keyInfo.Parameters.GetValueOf <string>("identifier"))));
        }
Beispiel #9
0
        static ProtectedPasswordStorage RequestSecret(HMACKeyInfo keyInfo)
        {
            if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.SrkSecret)
            {
                ProtectedPasswordStorage secret = new ProtectedPasswordStorage();
                secret.WellKnown();
                return(secret);
            }

            ProtectedPasswordStorage pws = new ProtectedPasswordStorage();

            pws.AppendPasswordChar('I');
            pws.AppendPasswordChar('A');
            pws.AppendPasswordChar('I');
            pws.AppendPasswordChar('K');

            return(pws);
        }
Beispiel #10
0
        public static void Main(string[] args)
        {
            // Establish Connections
            IDictionary <string, TPMSession> sessions =
                XMLConfiguration.EstablischConnection(base_path + "ClientConfigXml/UnixSocketDeviceLin.xml");

            // Create one keystore per opened session
            //foreach (TPMSession tpmSes in sessions.Values)
            //	tpmSes.Keystore = new InMemoryKeystore();

            TPMSession sessionToUse = sessions["local0"];

            //	sessionToUse.SetRequestSecretCallback(RequestSecret);

            ProtectedPasswordStorage pws = new ProtectedPasswordStorage();

            pws.WellKnown();

            sessionToUse.AdministrationClient.TakeOwnership(ConsoleUtils.ReadPassword("Owner Password: "******"PCRS = " + sessionToUse.CapabilityClient.GetPCRCount());
        }
        public void TakeOwnership(ProtectedPasswordStorage ownerSecret, ProtectedPasswordStorage srkSecret)
        {
            _tpmSession.SetValue("secret_" + TPMSession.PARAM_AUTH_OWNER, ownerSecret);
            _tpmSession.SetValue("secret_" + TPMSession.PARAM_AUTH_SRK, srkSecret);


            IAsymmetricBlockCipher ekEncryptor = _tpmSession.EndorsementKeyHandling.PublicKey.CreateRSAEncrypter();

            ownerSecret.DecryptHash();
            byte[] encOwnerSecret = ekEncryptor.ProcessBlock(ownerSecret.HashValue, 0, ownerSecret.HashValue.Length);
            ownerSecret.ClearHash();

            srkSecret.DecryptHash();
            byte[] encSrkSecret = ekEncryptor.ProcessBlock(srkSecret.HashValue, 0, srkSecret.HashValue.Length);
            srkSecret.ClearHash();

            Parameters parameters = new Parameters();

            parameters.AddPrimitiveType(PARAM_OWNERAUTH, encOwnerSecret);
            parameters.AddPrimitiveType(PARAM_SRKAUTH, encSrkSecret);

            /*TPMCommandResponse response = */ BuildDoVerifyRequest(TPMCommandNames.TPM_CMD_TakeOwnership, parameters);
        }
Beispiel #12
0
 /// <summary>
 /// Constructs a new SealBlockCipher with the specified arguments and caches the specified seal auth value
 /// </summary>
 /// <param name="keyHandle"></param>
 /// <param name="session"></param>
 /// <param name="sealAuth"></param>
 public SealBlockCipher(ClientKeyHandle keyHandle, TPMSession session, TPMPCRSelection pcrSelection, ProtectedPasswordStorage sealAuth)
     : this(keyHandle, session, pcrSelection)
 {
     _session.SetValue("secret_seal_" + _keyHandle.FriendlyName + "_" + _myId.ToString(), sealAuth);
 }
Beispiel #13
0
        /// <summary>
        /// If not cached, the desired secret is requested from the user
        /// </summary>
        /// <param name="keyInfo"></param>
        /// <returns></returns>
        public ProtectedPasswordStorage RequestSecret(HMACKeyInfo keyInfo)
        {
            string dictKey = null;

            if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.OwnerSecret)
            {
                dictKey = PARAM_AUTH_OWNER;
            }
            else if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.SrkSecret)
            {
                dictKey = PARAM_AUTH_SRK;
            }
            else if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.KeyUsageSecret)
            {
                string friendlyName             = keyInfo.Parameters.GetValueOf <string>("identifier");
                bool   identifierIsFriendlyName = keyInfo.Parameters.GetValueOf <bool>("identifierIsFriendlyName", false);

                if (!identifierIsFriendlyName)
                {
                    if (_keystore.ContainsIdentifier(friendlyName) == false)
                    {
                        throw new ArgumentException(string.Format("Requests for secret for key not in keystore! identifier: {0}",
                                                                  friendlyName));
                    }

                    friendlyName = _keystore.IdentifierToFriendlyName(friendlyName);
                }

                dictKey = "usage_" + friendlyName;
            }
            else if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.SealAuth)
            {
                string friendlyName = keyInfo.Parameters.GetValueOf <string>("identifier");

                bool identifierIsFriendlyName = keyInfo.Parameters.GetValueOf <bool>("identifierIsFriendlyName", false);

                if (!identifierIsFriendlyName)
                {
                    if (_keystore.ContainsIdentifier(friendlyName) == false)
                    {
                        throw new ArgumentException(string.Format("Requests for secret for key not in keystore! identifier: {0}",
                                                                  friendlyName));
                    }

                    friendlyName = _keystore.IdentifierToFriendlyName(friendlyName);
                }

                dictKey = "seal_" + friendlyName;
            }
            else if (keyInfo.KeyType == HMACKeyInfo.HMACKeyType.CounterSecret)
            {
                dictKey = "counter";
            }
            else
            {
                throw new NotSupportedException(string.Format("The key type '{0}' is not supported", keyInfo.KeyType));
            }



            ProtectedPasswordStorage pw = GetValue <ProtectedPasswordStorage>("secret_" + dictKey, null);

            if (pw == null)
            {
                _logger.DebugFormat("Secret for dictkey '{0}' was not found in cache, requesting from user", dictKey);
                ProtectedPasswordStorage password = RaiseRequestSecret(keyInfo);
                SetValue("secret_" + dictKey, password);
                return(password);
            }
            else
            {
                _logger.DebugFormat("Secret for dictkey '{0}' was found in cache", dictKey);
                return(pw);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Creates an IAsymmetricBlockCipher for sealing for this key. This is only valid for storage keys
 /// </summary>
 /// <param name="pcrSelection"> </param>
 /// <returns></returns>
 public IAsymmetricBlockCipher CreateSealBlockCipher(TPMPCRSelection pcrSelection, ProtectedPasswordStorage sealAuth)
 {
     return(new SealBlockCipher(this, _tpmSession, pcrSelection, sealAuth));
 }
Beispiel #15
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();
                }
            }
        }
Beispiel #16
0
        public override void Execute(string[] commandline)
        {
            if (commandline.Length < 2)
            {
                _console.Out.WriteLine("Error: [local_session_alias] not specified");
                return;
            }
            else if (commandline.Length < 3)
            {
                _console.Out.WriteLine("Error: [command] not specified");
                return;
            }

            ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null);

            if (ctx == null)
            {
                _console.Out.WriteLine("No active connection was found");
                return;
            }

            string localAlias = commandline[1];
            string keyCommand = commandline[2];

            IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null);

            if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false)
            {
                _console.Out.WriteLine("Error: Specified local alias was not found");
                return;
            }


            if (keyCommand == "clear")
            {
                List <string> toRemove = new List <string>();

                foreach (string key in tpmSessions[localAlias].ListValueKeys())
                {
                    if (key.StartsWith("secret_"))
                    {
                        toRemove.Add(key);
                    }
                }

                foreach (string key in toRemove)
                {
                    tpmSessions[localAlias].ClearValue(key);
                }
            }
            else if (keyCommand == "remove")
            {
                IDictionary <string, string> arguments = null;

                if (commandline.Length >= 4)
                {
                    arguments = _console.SplitArguments(commandline[3], 0);
                }

                if (commandline.Length < 4 || arguments.ContainsKey("type") == false)
                {
                    _console.Out.WriteLine("Error: No type to remove specified");
                    return;
                }

                tpmSessions[localAlias].ClearValue("secret_" + arguments["type"]);
            }
            else if (keyCommand == "add")
            {
                if (commandline.Length < 4)
                {
                    _console.Out.WriteLine("Error: No arguments specified");
                    return;
                }

                IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0);

                if (arguments.ContainsKey("type") == false)
                {
                    _console.Out.WriteLine("Error: No type specified");
                    return;
                }

                string      dictKey = arguments["type"];
                HMACKeyInfo keyInfo;
                Parameters  hmacKeyInfoParams = new Parameters();
                if (dictKey == "owner")
                {
                    dictKey = TPMSession.PARAM_AUTH_OWNER;
                    keyInfo = new HMACKeyInfo(HMACKeyInfo.HMACKeyType.OwnerSecret, hmacKeyInfoParams);
                }
                else if (dictKey == "srk")
                {
                    dictKey = TPMSession.PARAM_AUTH_SRK;
                    keyInfo = new HMACKeyInfo(HMACKeyInfo.HMACKeyType.SrkSecret, hmacKeyInfoParams);
                }
                else if (dictKey == "key_usage")
                {
                    if (arguments.ContainsKey("name") == false)
                    {
                        _console.Out.WriteLine("Error: key_usage requires name of key");
                        return;
                    }

                    dictKey = "usage_" + arguments["name"];
                    hmacKeyInfoParams.AddPrimitiveType("identifier", arguments["name"]);
                    keyInfo = new HMACKeyInfo(HMACKeyInfo.HMACKeyType.KeyUsageSecret, hmacKeyInfoParams);
                }
                else if (dictKey == "seal")
                {
                    if (arguments.ContainsKey("name") == false)
                    {
                        _console.Out.WriteLine("Error: seal requires name of key");
                        return;
                    }

                    dictKey = "seal_" + arguments["name"];
                    hmacKeyInfoParams.AddPrimitiveType("identifier", arguments["name"]);
                    keyInfo = new HMACKeyInfo(HMACKeyInfo.HMACKeyType.SealAuth, hmacKeyInfoParams);
                }
                else if (dictKey == "counter")
                {
                    dictKey = "counter";
                    keyInfo = new HMACKeyInfo(HMACKeyInfo.HMACKeyType.CounterSecret, new Parameters());
                }
                else
                {
                    _console.Out.WriteLine("Error: Unknown secret type");
                    return;
                }


                ProtectedPasswordStorage pw;

                if (arguments.ContainsKey("secret"))
                {
                    pw = new ProtectedPasswordStorage();
                    foreach (char c in arguments["secret"])
                    {
                        pw.AppendPasswordChar(c);
                    }
                }
                else
                {
                    tpmSessions[localAlias].ClearValue("secret_" + dictKey);
                    pw = tpmSessions[localAlias].RequestSecret(keyInfo);
                }

                pw.Hash();
                tpmSessions[localAlias].SetValue("secret_" + dictKey, pw);
            }
            else
            {
                _console.Out.WriteLine("Error, unknown command '{0}'", commandline[2]);
            }
        }
        public override void Execute(string[] commandline)
        {
            if (commandline.Length < 2)
            {
                _console.Out.WriteLine("Error: [local_alias] not specified");
            }
            else if (commandline.Length < 3)
            {
                _console.Out.WriteLine("Error: [admin_subcommand] not specified");
            }

            ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null);

            if (ctx == null)
            {
                _console.Out.WriteLine("No active connection was found");
                return;
            }

            string localAlias   = commandline[1];
            string adminCommand = commandline[2];

            IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null);

            if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false)
            {
                _console.Out.WriteLine("Error: Specified local alias was not found");
                return;
            }



            if (adminCommand == "take_ownership")
            {
                ProtectedPasswordStorage ownerAuth;
                if (commandline.Length >= 4)
                {
                    ownerAuth = new ProtectedPasswordStorage();
                    foreach (char c in commandline[3])
                    {
                        ownerAuth.AppendPasswordChar(c);
                    }
                }
                else
                {
                    ownerAuth = Utils.ReadPassword("Enter new owner password:"******"Enter new srk password:"******"Request aborted");
                    return;
                }

                ownerAuth.Hash();
                srkAuth.Hash();
                tpmSessions[localAlias].AdministrationClient.TakeOwnership(ownerAuth, srkAuth);
            }
            else if (adminCommand == "owner_clear")
            {
                tpmSessions[localAlias].AdministrationClient.ClearOwner();
            }
            else
            {
                _console.Out.WriteLine("Error, unknown admin_subcommand '{0}'", adminCommand);
            }
        }
Beispiel #18
0
        public override void Execute(string[] commandline)
        {
            if (commandline.Length < 2)
            {
                _console.Out.WriteLine("Error: [local_session_alias] not specified");
                return;
            }
            else if (commandline.Length < 3)
            {
                _console.Out.WriteLine("Error: [command] not specified");
                return;
            }

            ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null);

            if (ctx == null)
            {
                _console.Out.WriteLine("No active connection was found");
                return;
            }

            string localAlias = commandline[1];
            string keyCommand = commandline[2];

            IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null);

            if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false)
            {
                _console.Out.WriteLine("Error: Specified local alias was not found");
                return;
            }


            if (keyCommand == "keystore_open")
            {
                if (commandline.Length < 4)
                {
                    _console.Out.WriteLine("Error: keystore_open requires some arguments, check help for further information");
                    return;
                }

                if (tpmSessions[localAlias].Keystore != null)
                {
                    _console.Out.WriteLine("Error: There is already an open keystore!");
                    return;
                }

                string[] sArguments = commandline[3].Split(',');
                IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 1);

                TPMKeystoreProvider keystore = TPMKeystoreProviders.Create(sArguments[0], arguments);
                tpmSessions[localAlias].Keystore = keystore;
            }
            else if (keyCommand == "keystore_close")
            {
                TPMKeystoreProvider keystore = tpmSessions[localAlias].Keystore;

                if (keystore != null)
                {
                    keystore.Dispose();
                    tpmSessions[localAlias].Keystore = keystore;
                }
            }
            else if (keyCommand == "keystore_list")
            {
                TPMKeystoreProvider keystore = tpmSessions[localAlias].Keystore;

                if (keystore == null)
                {
                    _console.Out.WriteLine("Error: No keystore opened");
                    return;
                }

                _console.Out.WriteLine("The keystore contains #{0} keys", keystore.EnumerateFriendlyNames().Length);
                _console.Out.WriteLine();
                foreach (string friendlyName in keystore.EnumerateFriendlyNames())
                {
                    string parent = "<SRK>";

                    KeyValuePair <string, string>?parentKey = keystore.FindParentKeyByFriendlyName(friendlyName);
                    if (parentKey != null)
                    {
                        parent = parentKey.Value.Key;
                    }

                    _console.Out.WriteLine("{0}   ({1})   parent: {2}", friendlyName,
                                           keystore.FriendlyNameToIdentifier(friendlyName), parent);
                }
            }
            else if (keyCommand == "create")
            {
                if (tpmSessions[localAlias].Keystore == null)
                {
                    _console.Out.WriteLine("Error: No keystore was opened");
                    return;
                }

                IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0);

                if (arguments.ContainsKey("name") == false)
                {
                    _console.Out.WriteLine("Error: No name specified");
                    return;
                }

                if (arguments.ContainsKey("parent") == false)
                {
                    _console.Out.WriteLine("Error: No parent key specified");
                    return;
                }

                ClientKeyHandle keyHandle;
                if (arguments["parent"] == "srk")
                {
                    keyHandle = tpmSessions[localAlias].KeyClient.GetSrkKeyHandle();
                }
                else
                {
                    keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["parent"]);
                }

                if (keyHandle == null)
                {
                    _console.Out.WriteLine("Error: Key with name '{0}' not found", arguments["parent"]);
                    return;
                }


                if (arguments.ContainsKey("key_usage") == false)
                {
                    _console.Out.WriteLine("Error: key_usage not defined");
                    return;
                }

                TPMKeyUsage keyUsage;

                switch (arguments["key_usage"])
                {
                case "sign":
                    keyUsage = TPMKeyUsage.TPM_KEY_SIGNING;
                    break;

                case "bind":
                    keyUsage = TPMKeyUsage.TPM_KEY_BIND;
                    break;

                case "storage":
                    keyUsage = TPMKeyUsage.TPM_KEY_STORAGE;
                    break;

                default:
                    _console.Out.WriteLine("Error: Invalid key_usage '{0}'", arguments["key_usage"]);
                    return;
                }

                if (arguments.ContainsKey("key_length") == false)
                {
                    _console.Out.WriteLine("Error: key_length not defined!");
                    return;
                }

                uint keyLength = 0;
                if (uint.TryParse(arguments["key_length"], out keyLength) == false)
                {
                    _console.Out.WriteLine("Error: Could not parse key_length");
                    return;
                }

                TPMKeyFlags keyFlags = TPMKeyFlags.None;

                if (arguments.ContainsKey("key_flags"))
                {
                    switch (arguments["key_flags"])
                    {
                    case "none":
                        keyFlags = TPMKeyFlags.None;
                        break;

                    case "migratable":
                        keyFlags = TPMKeyFlags.Migratable;
                        break;
                    }
                }

                //Make sure that key usage auth and if required migration auth is in the secret cache
                Parameters hmacParams = new Parameters();
                hmacParams.AddPrimitiveType("identifierIsFriendlyName", true);
                hmacParams.AddPrimitiveType("identifier", arguments["name"]);
                ProtectedPasswordStorage usageAuth = tpmSessions[localAlias].RequestSecret(
                    new HMACKeyInfo(HMACKeyInfo.HMACKeyType.KeyUsageSecret, hmacParams));

                if (usageAuth != null)
                {
                    tpmSessions[localAlias].SetValue("secret_usage_" + arguments["name"], usageAuth);
                }

                if ((keyFlags & TPMKeyFlags.Migratable) == TPMKeyFlags.Migratable)
                {
                    ProtectedPasswordStorage migrationAuth = tpmSessions[localAlias].RequestSecret(
                        new HMACKeyInfo(HMACKeyInfo.HMACKeyType.KeyMigrationSecret, hmacParams));

                    if (migrationAuth != null)
                    {
                        tpmSessions[localAlias].SetValue("secret_migration_" + arguments["name"], migrationAuth);
                    }
                }


                /*ClientKeyHandle newKey =*/ keyHandle.CreateKey(arguments["name"], keyLength, keyUsage, keyFlags);
            }
            else
            {
                _console.Out.WriteLine("Error, unknown command '{0}'", commandline[2]);
            }
        }