Exemple #1
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();
                }
            }
        }
Exemple #2
0
 public QuoteSigner(TPMSession tpmSession, ClientKeyHandle keyHandle,
                    TPMPCRSelection pcrSelection)
 {
     _tpmSession   = tpmSession;
     _keyHandle    = keyHandle;
     _pcrSelection = pcrSelection;
 }
Exemple #3
0
 /// <summary>
 /// Cosntructs a new SealBlockCipher with the specified arguments, the seal auth is requested from the user
 /// on first use
 /// </summary>
 /// <param name="keyHandle"></param>
 /// <param name="session"></param>
 public SealBlockCipher(ClientKeyHandle keyHandle, TPMSession session, TPMPCRSelection pcrSelection)
 {
     _keyHandle    = keyHandle;
     _session      = session;
     _myId         = session.GetFreeId();
     _pcrSelection = pcrSelection;
     _keyInfo      = _keyHandle.KeyInfo;
 }
Exemple #4
0
        /// <summary>
        /// Creates an ISigner for quoting using this key
        /// </summary>
        /// <param name="pcrSelection"></param>
        /// <returns></returns>
        public ISigner CreateQuoter(TPMPCRSelection pcrSelection)
        {
            TPMKey keyInfo = KeyInfo;

            if (keyInfo.AlgorithmParams.AlgorithmId == TPMAlgorithmId.TPM_ALG_RSA &&
                keyInfo.AlgorithmParams.SigScheme == TPMSigScheme.TPM_SS_RSASSAPKCS1v15_SHA1)
            {
                return(new QuoteSigner(_tpmSession, this, pcrSelection));
            }
            else
            {
                throw new NotSupportedException(string.Format("Quoter not supported for '{0}-{1}'", keyInfo.AlgorithmParams.AlgorithmId,
                                                              keyInfo.AlgorithmParams.SigScheme));
            }
        }
Exemple #5
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 #6
0
        public TPMPCRSelection CreateEmptyPCRSelection()
        {
            uint pcrCount = CapabilityClient.GetPCRCount();

            for (ushort i = (ushort)(pcrCount / 8); i > 0; i--)
            {
                if (CapabilityClient.SupportsSizeOfPcr(i))
                {
                    return(TPMPCRSelection.CreatePCRSelection((uint)(i * 8)));
                }
            }

            //Normally v1.2 TPMs should support at least selectSize == 3 and
            //v1.1 TPMS should support at least selectSize == 2
            //For any reason this method here does not work on all TPMs (maybe a bug??)
            //so we fall back to selectSize == 2 which should be supported on both versions
            return(TPMPCRSelection.CreatePCRSelection(16));
            //throw new NotSupportedException("Could not find a valid selectSize parameter for this tpm");
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            string[] sealMe = { "Hallo", "IAIK!" };

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

            Console.WriteLine("Create Cipher Key");

            ClientKeyHandle myFirstSealKey =
                sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_seal_key", TPMKeyUsage.TPM_KEY_STORAGE);

            Console.WriteLine("Key: {0}\n{1}", myFirstSealKey.FriendlyName, myFirstSealKey.PublicKey);
            Console.WriteLine("---------------------------------\n");


            sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });

            TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection();

            pcrselect.PcrSelection[0] = true;
            pcrselect.PcrSelection[1] = true;
            pcrselect.PcrSelection[2] = true;

            Console.WriteLine("Create Cipher, init and cipher");
            IAsymmetricBlockCipher cipher = myFirstSealKey.CreateSealBlockCipher(pcrselect);

            cipher.Init(true, null);

            byte[][] cipherText = new byte[sealMe.Length][];
            int      i          = 0;

            foreach (string msg in sealMe)
            {
                byte[] block = System.Text.ASCIIEncoding.ASCII.GetBytes(msg);
                cipherText[i] = cipher.ProcessBlock(block, 0, block.Length);
                i++;
            }

            Console.WriteLine("Original vs. CiperText:");
            for (i = 0; i < sealMe.Length; i++)
            {
                Console.WriteLine("{0} --> {1}", sealMe[i], ByteHelper.ByteArrayToHexString(cipherText[i]));
            }
            Console.WriteLine("---------------------------------\n");

            Console.WriteLine("Init and decode");
            cipher.Init(false, null);
            byte[][] decode = new byte[sealMe.Length][];
            i = 0;
            foreach (byte[] msg in cipherText)
            {
                decode[i] = cipher.ProcessBlock(msg, 0, msg.Length);
                i++;
            }

            Console.WriteLine("Does it work?:");
            for (i = 0; i < sealMe.Length; i++)
            {
                Console.WriteLine("{0}: {1}", sealMe[i] == System.Text.ASCIIEncoding.ASCII.GetString(decode[i])?"Y":"N", System.Text.ASCIIEncoding.ASCII.GetString(decode[i]));
            }
            Console.WriteLine("---------------------------------\n");

            Console.WriteLine("Changing PCR Values");
            sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });

            Console.WriteLine("Decode, now an TPMRequest Exception should be thrown, with Error Code (0x18): TPM_WRONGPCRVAL");
            decode = new byte[sealMe.Length][];
            i      = 0;
            foreach (byte[] msg in cipherText)
            {
                try
                {
                    decode[i] = cipher.ProcessBlock(msg, 0, msg.Length);
                    Console.WriteLine("UUUUUPPPPSSSS, something went wrong!");
                }
                catch (TPMRequestException e)
                {
                    Console.WriteLine(e.ToString());
                }
                i++;
            }
        }
Exemple #8
0
 /// <summary>
 /// Performs a simple quote operation where only the TPMPCRSelection is returned
 /// </summary>
 /// <param name="pcrs"></param>
 /// <returns></returns>
 public TPMPCRComposite SimpleQuote(TPMPCRSelection pcrs)
 {
     return(Quote(pcrs, null).PCRSelection);
 }
Exemple #9
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);
 }
Exemple #10
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)
 {
     return(new SealBlockCipher(this, _tpmSession, pcrSelection));
 }
        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];

            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 (tpmSessions[localAlias].Keystore == null)
            {
                _console.Out.WriteLine("Error: No keystore was opened");
                return;
            }

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

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

//			if(arguments.ContainsKey("pcr") == false)
//			{
//				_console.Out.WriteLine("Error: no pcr values where specified");
//				return;
//			}

            if (arguments.ContainsKey("data_input") == false)
            {
                _console.Out.WriteLine("Error: no data input source specified");
                return;
            }

            DataInputMode dataInputMode;

            try
            {
                dataInputMode = (DataInputMode)Enum.Parse(typeof(DataInputMode), arguments["data_input"], true);
            }
            catch (Exception)
            {
                _console.Out.WriteLine("Error: Invalid data input source");
                return;
            }


            DataFormat inputDataFormat = DataFormat.Raw;

            if (arguments.ContainsKey("input_data_format"))
            {
                try
                {
                    inputDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), arguments["input_data_format"], true);
                }
                catch (Exception)
                {
                    _console.Out.WriteLine("Error: Invalid input data format");
                    return;
                }
            }


            if (dataInputMode == DataInputMode.File && arguments.ContainsKey("file") == false)
            {
                _console.Out.WriteLine("Error: data_input=file requires file argument!");
                return;
            }


            ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]);


            Stream inputStream = null;

            if (dataInputMode == DataInputMode.Console)
            {
                inputStream = new TextReaderStream(_console.In);
            }
            else if (dataInputMode == DataInputMode.Embedded)
            {
                if (commandline.Length <= 3)
                {
                    _console.Out.WriteLine("Error: no embedded data");
                    return;
                }

                StringBuilder embeddedData = new StringBuilder();
                for (int i = 3; i < commandline.Length; i++)
                {
                    embeddedData.Append(commandline[i]);
                    if (i + 1 < commandline.Length)
                    {
                        embeddedData.Append(" ");
                    }
                }

                inputStream = new TextReaderStream(new StringReader(embeddedData.ToString()));
            }
            else if (dataInputMode == DataInputMode.File)
            {
                inputStream = new FileStream(arguments["file"], FileMode.Open, FileAccess.Read);
            }

            if (inputDataFormat == DataFormat.Hex)
            {
                inputStream = new HexFilterStream(inputStream);
            }



            ISigner signatureGenerator = null;


            if (subCommand == "verify")
            {
                signatureGenerator = keyHandle.CreateSigner();
                signatureGenerator.Init(false, null);
            }
            else if (subCommand == "generate")
            {
                signatureGenerator = keyHandle.CreateSigner();
                signatureGenerator.Init(true, null);
            }
            else if (subCommand == "generate_quote" || subCommand == "verify_quote")
            {
                if (arguments.ContainsKey("pcr") == false)
                {
                    _console.Out.WriteLine("Error: No pcrs specified!");
                    return;
                }

                TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection();

                foreach (string pcr in arguments["pcr"].Split('|'))
                {
                    int pcrValue = int.Parse(pcr);
                    pcrSelection.PcrSelection.SetBit(pcrValue - 1, true);
                }

                signatureGenerator = keyHandle.CreateQuoter(pcrSelection);
                signatureGenerator.Init(subCommand == "generate_quote", null);
            }

            byte[] buffer = new byte[1024];
            int    read   = 0;

            do
            {
                read = inputStream.Read(buffer, 0, buffer.Length);

                signatureGenerator.BlockUpdate(buffer, 0, read);
            }while(read > 0);

            _console.Out.WriteLine(ByteHelper.ByteArrayToHexString(signatureGenerator.GenerateSignature()));
            _console.Out.WriteLine();
            inputStream.Dispose();
        }
Exemple #12
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];

            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 (tpmSessions[localAlias].Keystore == null)
            {
                _console.Out.WriteLine("Error: No keystore was opened");
                return;
            }

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

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

//			if(arguments.ContainsKey("pcr") == false)
//			{
//				_console.Out.WriteLine("Error: no pcr values where specified");
//				return;
//			}

            if (arguments.ContainsKey("data_input") == false)
            {
                _console.Out.WriteLine("Error: no data input source specified");
                return;
            }

            DataInputMode dataInputMode;

            try
            {
                dataInputMode = (DataInputMode)Enum.Parse(typeof(DataInputMode), arguments["data_input"], true);
            }
            catch (Exception)
            {
                _console.Out.WriteLine("Error: Invalid data input source");
                return;
            }

            DataOutputMode dataOutputMode;

            try
            {
                dataOutputMode = (DataOutputMode)Enum.Parse(typeof(DataOutputMode), arguments["data_output"], true);
            }
            catch (Exception)
            {
                _console.Out.WriteLine("Error: Invalid data output destination");
                return;
            }

            DataFormat inputDataFormat = DataFormat.Raw;

            if (arguments.ContainsKey("input_data_format"))
            {
                try
                {
                    inputDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), arguments["input_data_format"], true);
                }
                catch (Exception)
                {
                    _console.Out.WriteLine("Error: Invalid input data format");
                    return;
                }
            }

            DataFormat outputDataFormat = DataFormat.Raw;

            if (arguments.ContainsKey("output_data_format"))
            {
                try
                {
                    outputDataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), arguments["output_data_format"], true);
                }
                catch (Exception)
                {
                    _console.Out.WriteLine("Error: Invalid output data format");
                    return;
                }
            }


            if (dataInputMode == DataInputMode.File && arguments.ContainsKey("file") == false)
            {
                _console.Out.WriteLine("Error: data_input=file requires file argument!");
                return;
            }


            if (dataOutputMode == DataOutputMode.File && arguments.ContainsKey("output_file") == false)
            {
                _console.Out.WriteLine("Error: data_output=file requires output_file argument!");
                return;
            }

            TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection();

            if (arguments.ContainsKey("pcr"))
            {
                foreach (string pcr in arguments["pcr"].Split('|'))
                {
                    int pcrValue = int.Parse(pcr);

                    pcrSelection.PcrSelection.SetBit(pcrValue - 1, true);
                }
            }

            ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]);


            Stream inputStream = null;

            if (dataInputMode == DataInputMode.Console)
            {
                inputStream = new TextReaderStream(_console.In);
            }
            else if (dataInputMode == DataInputMode.Embedded)
            {
                if (commandline.Length <= 3)
                {
                    _console.Out.WriteLine("Error: no embedded data");
                    return;
                }

                StringBuilder embeddedData = new StringBuilder();
                for (int i = 3; i < commandline.Length; i++)
                {
                    embeddedData.Append(commandline[i]);
                    if (i + 1 < commandline.Length)
                    {
                        embeddedData.Append(" ");
                    }
                }

                inputStream = new TextReaderStream(new StringReader(embeddedData.ToString()));
            }
            else if (dataInputMode == DataInputMode.File)
            {
                inputStream = new FileStream(arguments["file"], FileMode.Open, FileAccess.Read);
            }

            if (inputDataFormat == DataFormat.Hex)
            {
                inputStream = new HexFilterStream(inputStream);
            }

            Stream outputStream = null;

            if (dataOutputMode == DataOutputMode.Console)
            {
                outputStream = new HexFilterStream(new TextWriterStream(_console.Out));
            }
            else if (dataOutputMode == DataOutputMode.File)
            {
                if (outputDataFormat == DataFormat.Hex)
                {
                    outputStream = new HexFilterStream(new FileStream(arguments["output_file"], FileMode.OpenOrCreate, FileAccess.Write));
                }
                else
                {
                    outputStream = new FileStream(arguments["output_file"], FileMode.OpenOrCreate, FileAccess.Write);
                }
            }


            IAsymmetricBlockCipher sealCipher = keyHandle.CreateSealBlockCipher(pcrSelection);

            sealCipher.Init(true, null);

            int read;

            byte[] buffer = new byte[sealCipher.GetInputBlockSize()];
            do
            {
                read = inputStream.Read(buffer, 0, buffer.Length);

                if (read > 0)
                {
                    byte[] encrypted = sealCipher.ProcessBlock(buffer, 0, read);
                    outputStream.Write(encrypted, 0, encrypted.Length);
                }
            }while(read > 0);

            _console.Out.WriteLine();
            outputStream.Dispose();
            inputStream.Dispose();
        }
Exemple #13
0
 public TPMPCRSelectionCore(TPMPCRSelection pcrSelection)
 {
     _pcrSelection = pcrSelection.PcrSelection;
 }
Exemple #14
0
 public TPMPCRInfoCore(TPMPCRSelection pcrSelection)
 {
     _pcrSelection = pcrSelection;
 }
        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: [pcr_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 pcrCommand = 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 (pcrCommand == "report")
            {
                uint pcrCount = tpmSessions[localAlias].CapabilityClient.GetPCRCount();

                for (uint i = 0; i < pcrCount; i++)
                {
                    _console.Out.WriteLine("#{0}: {1}", i, ByteHelper.ByteArrayToHexString(tpmSessions[localAlias].IntegrityClient.PCRValue(i)));
                }
            }
            else if (pcrCommand == "extend")
            {
                if (commandline.Length < 4)
                {
                    _console.Out.WriteLine("Error: 'extend' requires some arguments");
                    return;
                }
                IDictionary <string, string> arguments = _console.SplitArguments(commandline[3], 0);

                if (arguments.ContainsKey("pcr") == false)
                {
                    _console.Out.WriteLine("Error: 'extend' requires parameter 'pcr' to be specified");
                    return;
                }

                uint pcr = 0;

                if (uint.TryParse(arguments["pcr"], out pcr) == false)
                {
                    _console.Out.WriteLine("Error: 'pcr' could not be parsed, is it a valid pcr specified?");
                    return;
                }

                if (arguments.ContainsKey("data_input") == false)
                {
                    _console.Out.WriteLine("Error: 'extend' requires parameter 'data_input' to be specified");
                    return;
                }

                TPMSessionSealCommand.DataInputMode dataInput =
                    (TPMSessionSealCommand.DataInputMode)Enum.Parse(typeof(TPMSessionSealCommand.DataInputMode), arguments["data_input"], true);

                if (dataInput != TPMSessionSealCommand.DataInputMode.Embedded &&
                    dataInput != TPMSessionSealCommand.DataInputMode.File)
                {
                    _console.Out.WriteLine("Error: 'data_input' has an invalid value");
                    return;
                }

                byte[] digest;

                if (dataInput == TPMSessionSealCommand.DataInputMode.File &&
                    arguments.ContainsKey("file") == false)
                {
                    _console.Out.WriteLine("Error: file-data_input require 'file' argument to be specified");
                    return;
                }
                else if (dataInput == TPMSessionSealCommand.DataInputMode.File)
                {
                    FileInfo myFile = new FileInfo(arguments["file"]);
                    using (FileStream src = myFile.OpenRead())
                    {
                        digest = new HashProvider().Hash(
                            new HashStreamDataProvider(src, null, null, false));
                    }
                }
                else if (dataInput == TPMSessionSealCommand.DataInputMode.Embedded)
                {
                    using (Stream src = new HexFilterStream(new TextReaderStream(new StringReader(commandline[4]))))
                    {
                        digest = new byte[20];
                        if (src.Length != 20)
                        {
                            throw new ArgumentException("Error: The embedded digest must be 20 bytes long");
                        }

                        src.Read(digest, 0, 20);
                    }
                }
                else
                {
                    throw new ArgumentException(String.Format("data input mode '{0}' is not supported", dataInput));
                }

                _console.Out.WriteLine("Doing extension with digest: '{0}'", ByteHelper.ByteArrayToHexString(digest));

                byte[] newDigest = tpmSessions[localAlias].IntegrityClient.Extend(pcr, digest);
                _console.Out.WriteLine("Extension successful, new pcr value:  {0}", ByteHelper.ByteArrayToHexString(newDigest));
            }
            else if (pcrCommand == "quote")
            {
                if (commandline.Length < 4)
                {
                    _console.Out.WriteLine("Error: 'quote' requires some arguments");
                    return;
                }

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

                if (arguments.ContainsKey("pcr") == false)
                {
                    _console.Out.WriteLine("Error: 'quote' requires parameter 'pcr' to be specified");
                    return;
                }

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

                ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]);

                TPMPCRSelection pcrSelection = tpmSessions[localAlias].CreateEmptyPCRSelection();

                foreach (string pcr in arguments["pcr"].Split('|'))
                {
                    int pcrValue = int.Parse(pcr);
                    pcrSelection.PcrSelection.SetBit(pcrValue - 1, true);
                }

                TPMPCRComposite quoted = keyHandle.SimpleQuote(pcrSelection);

                IList <int> selectedPCRs = quoted.PCRSelection.SelectedPCRs;

                for (int i = 0; i < selectedPCRs.Count; i++)
                {
                    _console.Out.WriteLine("#{0}: {1}", selectedPCRs[i], ByteHelper.ByteArrayToHexString(quoted.PCRValues[i]));
                }
            }
            else
            {
                _console.Out.WriteLine("Error, unknown pcr_subcommand '{0}'", commandline[1]);
            }
        }
Exemple #16
0
        public static void Main(string[] args)
        {
            string quoteMe = "Hallo IAIK!";

            byte[] quoteMeBytes = System.Text.Encoding.ASCII.GetBytes(quoteMe);

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

            ClientKeyHandle myFirstQuoteKey =
                sessionToUse.KeyClient.GetSrkKeyHandle().CreateKey("my_first_quote_key", TPMKeyUsage.TPM_KEY_SIGNING);

            sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });

            TPMPCRSelection pcrselect = sessionToUse.CreateEmptyPCRSelection();

            pcrselect.PcrSelection[0] = true;
            pcrselect.PcrSelection[1] = true;
            pcrselect.PcrSelection[2] = true;

            ISigner signer = myFirstQuoteKey.CreateQuoter(pcrselect);

            signer.Init(true, null);
            signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length);

            byte[] quote = signer.GenerateSignature();

            Console.WriteLine("Quote of \"Hallo IAIK\" is:\n" + ByteHelper.ByteArrayToHexString(quote));

            Console.WriteLine();
            Console.WriteLine("Now we would verify this quote.");

            signer.Reset();
            signer.Init(false, null);
            signer.BlockUpdate(quoteMeBytes, 0, quoteMeBytes.Length);

            if (signer.VerifySignature(quote) == true)
            {
                Console.WriteLine("Quote is OK!");
            }
            else
            {
                Console.WriteLine("UUUUPPPPSSS something went wrong!");
            }


            Console.WriteLine("Extending PCRs, Quote should fail now!");

            sessionToUse.IntegrityClient.Extend(0, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(1, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
            sessionToUse.IntegrityClient.Extend(2, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });

            if (signer.VerifySignature(quote) == true)
            {
                Console.WriteLine("UUUUPPPPSSS something went wrong!");
            }
            else
            {
                Console.WriteLine("Quote is NOT OK, that's the way it should be.");
            }
        }
Exemple #17
0
        public static void Main(String[] args)
        {
            using (EzQuoteMain main = new EzQuoteMain())
            {
                /*foreach (String tpm_name in main.ctx_.TPMClient.TPMDevices)
                 * {
                 *      Console.WriteLine("TPM DEVICE {0}", tpm_name);
                 *
                 * }*/

                TPMSession tpm0 = main.ctx_.TPMClient.SelectTPMDevice("ibm0");

                IDictionary <string, string> opts = new Dictionary <string, string>();
                opts.Add("file", "/tmp/mystore");
                tpm0.Keystore = TPMKeystoreProviders.Create("SQLiteKeystore", opts);
                tpm0.SetRequestSecretCallback(mycallback);

                /*
                 * ProtectedPasswordStorage pws = new ProtectedPasswordStorage();
                 * pws.AppendPasswordChar('i');
                 * pws.AppendPasswordChar('a');
                 * pws.AppendPasswordChar('i');
                 * pws.AppendPasswordChar('k');
                 *
                 * tpm0.AdministrationClient.TakeOwnership(pws, pws);
                 */

                ClientKeyHandle kh_srk  = tpm0.KeyClient.GetSrkKeyHandle();
                ClientKeyHandle kh_sig1 = kh_srk.CreateKey("sigkey5" + tpm0.CreateRNG().Next(), 2048, TPMKeyUsage.TPM_KEY_SIGNING,
                                                           TPMKeyFlags.None);

                TPMPCRSelection pcrs = tpm0.CreateEmptyPCRSelection();
                pcrs.PcrSelection.SetBit(0, true);
                pcrs.PcrSelection.SetBit(1, true);
                pcrs.PcrSelection.SetBit(16, true);

                foreach (int pcr in pcrs.SelectedPCRs)
                {
                    Console.Write(" PCR {0:D2}: 0x");
                    foreach (byte b in tpm0.IntegrityClient.PCRValue((uint)pcr))
                    {
                        Console.Write("{0:X2}", b);
                    }
                    Console.WriteLine();
                }

                ISigner signer = kh_sig1.CreateQuoter(pcrs);
                signer.Init(true, null);
                signer.Update((byte)'i');
                signer.Update((byte)'a');
                signer.Update((byte)'i');
                signer.Update((byte)'k');
                byte[] signature = signer.GenerateSignature();

                Console.Write("QUOTE: ");
                foreach (byte b in signature)
                {
                    Console.Write(" {0:X2}", b);
                }
                Console.WriteLine();

                ISigner verifier = kh_sig1.CreateQuoter(pcrs);
                verifier.Init(false, null);
                verifier.Update((byte)'i');
                verifier.Update((byte)'a');
                verifier.Update((byte)'i');
                verifier.Update((byte)'k');
                if (verifier.VerifySignature(signature))
                {
                    Console.WriteLine("JO IT WORKED");
                }
                else
                {
                    Console.WriteLine("NA IT FAILED");
                }
            }
        }
Exemple #18
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));
 }