Coder Social home page Coder Social logo

microsoft / tss.msr Goto Github PK

View Code? Open in Web Editor NEW
409.0 47.0 155.0 48.32 MB

The TPM Software Stack from Microsoft Research

License: Other

C++ 21.54% C 24.94% Batchfile 0.21% Makefile 0.02% C# 24.44% Smalltalk 0.01% Java 14.24% TypeScript 7.23% Python 7.37%

tss.msr's Introduction

TSS.MSR

TPM 2.0 ecosystem

Trusted Platform Module (TPM) is a security component forming roots of trust in many PCs, servers and mobile devices. TPMs provide security functionality in the areas of:

  • Cryptographic key generation, protection, management, and use
  • Cryptographic device identity
  • Secure logging and log-reporting, i.e., attestation
  • Secure non-volatile storage
  • Other functions including hashing, random number generation, a secure clock, etc.

Microsoft Windows operating system relies on the TPM for a number of its security functions. Examples include BitLocker™ drive encryption, the Windows Virtual Smart Card feature, and the Platform Crypto Provider. Windows 10 requires TPM 2.0 to be enabled in all its desktop editions (Home, Pro, Enterprise, and Education) and in server editions running guarded fabric.

Both Windows and Linux operating systems expose low-level programmatic access to their TPM 2.0 devices. On Windows TPM 2.0 is available via TPM Base Services (TBS) API, and on Linux - via /dev/tpm0 or /dev/tpmrm0 device file abstractions. For the purposes of TPM 2.0 application development it is extremely convenient to use the TPM 2.0 simulator developed, open-sourced, and maintained on behalf of TCG by Microsoft.

TPM Software Stack (TSS) implementations from Microsoft

All flavors of TPM 2.0 devices mentioned in the previous section communicate with applications via a rather complex binary interface defined by the TCG's TPM 2.0 specification wrapped into OS/simulator specific protocols. Writing code for manual creation of the TPM 2.0 command buffers, parsing response buffers, building HMAC and policy sessions, verifying audit data, etc., is extremely tedious, time consuming, and error prone task.

In order to facilitate the development of applications and services using TPM 2.0, Microsoft has developed a series of TSS implementations for different programming languages. All these implementations provide complete representation of the TPM 2.0 API (commands, data structures, enumerations, unions) using the means of the corresponding languages, and some of them - additional functionality that greatly simplifies communications with TPM 2.0. All TSS.MSR implementations provide abstraction for Windows/Linux/Simulator TPM 2.0 devices.

TSS.Net and TSS.CPP are written in C# and C++ correspondingly, and are the richest TSS implementations in this collection. Besides complete abstraction of the TPM 2.0 interface, they implement additional functionality, such as:

  • automatic handling of HMAC and policy sessions;
  • expected audit, policy and cpHashes computation;
  • object oriented representation of the policy commands;
  • multiple helpers simplifying bridging between software crypto and TPM 2.0.

These implementations are for Java, Node.JS, and Python environments, and at the moment they provide complete abstraction of the TPM 2.0 interface without most of the additional capabilities of TSS.Net or TSS.CPP. Node.JS version is written in the TypeScript language.

TssCodeGen is the tool that parses TPM 2.0 specification documents and updates the TSS implementations in this repo so that all TPM 2.0 entity and command definitions match the contents of the specification. The tool can be easily extended to support other programming languages, as all language specific processing is highly localized and most of the logic is language independent.

This is the TSS.Net based framework used by the official TPM 2.0 compliance test suite and TPM 2.0 components of the Microsoft Windows HLK. See its README document for the details of the framework API and usage.

Along with it comes a sample test suite that not only demonstrates the framework usage, but also contains additional samples of the TPM 2.0 use cases, and is convenient for quick prototyping and testing of TPM 2.0 based scenarios.

System Requirements

TSS.Net is a cross-platform .NET Standard library and requires Visual Studio 2017 or above to build it. It can target one of the following .NET framework flavors: .NET 4.7.2, .NET Core 2.1 (for both Windows and Linux), .NET Standard 2.0, and .NET UWP 10.0. You can download the latest versions of the .NET Framework here.

TSS.Java uses Java SE 8 or above, TSS.JS requires Node.js 4.8.4 or higher, and TSS.Py supports Python 2.7 and 3.5+.

Platform Crypto Provider Toolkit

The TSS.MSR project also provides the TPM Platform Crypto Provider Toolkit. It contains sample code, utilities, and documentation for using TPM-related functionality on Windows 8.x/10 systems. It covers TPM-backed Crypto-Next-Gen (CNG) Platform Crypto Provider, and illustrates how attestation service providers can use the new Windows 8.x features. Both TPM 1.2 and TPM 2.0-based systems are supported.

See Also

Questions and Feedback

We hope that the TSS.MSR project will prove useful to both software developers and researchers in their development of security solutions and applications for the Windows operating system.

Feel free to use Issues section of this Github repo for any quetsions or problems.

For private feedback please use [email protected] (for all managed languages) or [email protected] mailing lists.

tss.msr's People

Contributors

advanced4 avatar alex-schwab avatar amarochk avatar anthonyvercolano avatar barnstee avatar baudev avatar bterlson avatar chrisfenner avatar cipop avatar danigian avatar dependabot[bot] avatar dmattoon avatar drakezul avatar gfs avatar juvazq avatar microsoft-github-policy-service[bot] avatar msftenhanceprovenance avatar msftgits avatar rgl avatar ronaldai avatar scovetta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tss.msr's Issues

Could not load file or assembly 'TSS.UWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

I'm trying to create DeviceClient but it keeps getting "Could not load file or assembly 'TSS.UWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'."

TpmDevice myDevice = new TpmDevice(0);
string hubUri = myDevice.GetHostName();
string deviceId = myDevice.GetDeviceId();
string sasToken = myDevice.GetSASToken();

var deviceClient = DeviceClient.Create(
hubUri,
AuthenticationMethodFactory.
CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt);

Can not Deserialize Quote

Hello,

I am trying to Serialize Quote and send it to remote party and Deserialize it on remote party.

So currently I am just trying to Serialize and Deserialize Quote on my local machine.

This is currently what I have

QuoteResponse quote = GenerateQuote_PCR(tpm, rmessage.startPCR, rmessage.endPCR, NonceExtracted);

cout << "serialization:" << endl;
string qserialized=quote.Serialize(SerializationType::Text);
cout << "serialization done" << endl;

QuoteResponse quoteDeserialized=QuoteResponse();

cout << "deserialization:" << endl;
quoteDeserialized.Deserialize(SerializationType::Text, qserialized);
cout << "deserialization done" << endl;

I checked if quote generated by GenerateQuote_PCR function is generated correctly.

this is the line that gives me error
quoteDeserialized.Deserialize(SerializationType::Text, qserialized);

Any help will be appreciated.

Thanks
Batyr

Running TSS Samples in Windows with real hardware TPM ( TPM_E_COMMAND_BLOCKED)

Running the TSS samples on Windows with the real hardware TPM is a challenge because, by default, Windows is restricting the TPM commands through Local Policy. Once you figure it out how to disable the local policy , the TPM commands are sent down to the TPM. BUT not ALL !! The Samples::ChildKeys() example is still failing with the error code TPM_E_COMMAND_BLOCKED. Has anyone managed to run this sample on real TPM ( not on the simulator) ?

Thread-saftey of TSS.NET

I'm new to TSS.NET (and TPM in general), and I'm wondering about the thread-safety guarantees provided by TSS.NET.

  1. Is it safe to execute (async or synch) operations on a single Tpm2 object from multiple threads?
  2. If not, is it safe to execute (async or synch) operations on a single Tpm2Device object from multiple threads (using a separate Tpm2 instance on every thread)?
  3. If not, is it safe to execute (async or synch) operations from multiple threads using a separate Tpm2Device instance per thread?

And as a bonus question: What's the current state of TSS.NET? Is it considered safe to use it in production? Does it work well under both Linux and Windows? Any limitations I should be aware of before I dig into TSS.NET deeper?

PolicySecret implementation Question

Is there a way to provide a HMAC authorization session to authorize the handle of the authorization object in TPM2_PolicySecret? It appears that TSS CPP currently uses/fabricates a PWAP session and sends the authValue of the authorization object in plain text when TPM2_PolicySecret is executed in a policy session. There doesn't appear to be an option to install a callback either provide authorization or authorization session to do it manually if required.
Is my understanding correct or am I missing something on how things work ?
This would make use of PolicySecret more secure if it is missing.

Thanks

Tpm in uwp error

there is error {TbsCommandBlocked}.By the way ,Is there a way to check the device support the tpm?
thanks.

Cannot run this lib on a raspberry pi

Hi,

I am attempting to use this lib (it came alongside the package Microsoft.Azure.Devices.Provisioning.Security.Tpm) on a Raspberry PI, but I get the following error.

image

Get error when try to create primary TMP

Hi @amarochk ,

When I run any sample (as administrator) in Windows 10, I get the following error in tpm.CreatePrimary

GetTpmAuth(LOCKOUT): error 0x80284015 (OWNERAUTH_NOT_FOUND)

Thanks for your help in advance.

Using TSS.NET with x509certificates?

If I generate a non-migratable RSA key pair in TPM, I get back a TpmPublic and TpmHandle representing the public and private keys respectively. Is it possible to use these keys in a self-signed x509certificate? Specifically, is it possible to put the public key in an x509certificate and sign it with the private key (TpmHandle)?

And then use the certificate for authentication -- specifically creating a RSACng (https://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacng(v=vs.110).aspx) with the TpmHandle? According to https://technet.microsoft.com/en-us/library/cc730763(v=ws.10).aspx, CNG (Cryptography Next Generation) should support TPM.

Thanks,
Alan

TPM ContextSave returns 0x80280400 (TPM_E_COMMAND_BLOCKED)

Hi,

I've been using the TSS.NET project against a hardware TPM. I create a primary key using CreatePrimary command and then ContextSave. I'm running the script from an adminitrator command line and keep getting the 0x80280400 (TPM_E_COMMAND_BLOCKED) error.

I've tried removing the block command using the Win32_TPM WMI object and setting the registry keys to ignore the default and local list.

When I run the Win32_TPM IsCommandBlocked(184) it tells me that the command isn't blocked anymore, but the TBS keeps failing with the same error. Is there something I'm doing wrong?
Thank you for your help.

Export wrapped keys from TSS.Net and import in TSS.CPP fails

Hi,

I am trying to serialize a signing key I create in a C#-application with TSS.Net and deserialize it in a C++ application (using TSS.CPP) to use it.
I am serializing the key with

        byte[] serializedPublic = publicKey.GetTpmRepresentation();

Deserializing this in C# works fine using:

      Marshaller.FromTpmRepresentation<TpmPublic>(serializedPublic);

Now I save the byte[] to disk. In the C++-application I read that byte[] and try to deserialize it with

       TPMT_PUBLIC publicKey;
       publicKey.FromBuf(wrappedPublic, TpmTypeId::TPMT_PUBLIC_ID);

The documentation is a little bit confusing at this point, so perhaps I am using the wrong methods.
However this fails, because in MarshallIn in line 111 I always get TpmTypeID::None when parsing the TPM_PUBLIC_PARMS of the key. So later in line 118

    newObj = TpmStructureBase::Factory(typeOfUnion, fInfo.ThisElementType, pUnion2);

an runtime_error("Factory only makes TPM structs and unions");) is thrown.
I am sure I am missing something or just calling the wrong methods.
Can you please help me to track down this issue?

TpmHandle.CreatePrimary throws BadAuth exception

Following the .NET example in Samples/Signing I am having an issue when using a physical TPM.

I look up the value of OwnerAuthFull in the registry at Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TPM\WMI\Admin and let's say the value is "foo/bar=". This is also displayed when I run Get-Tpm on the command line.

So I create the AuthValue by turning the string to bytes and create the AuthValue

var authValueRegistry = Encoding.ASCII.GetBytes( "foo/bar=" );
var ownerAuth = new AuthValue( authValueRegistry );

Then I get to creating a primary key with the example:

var keyHandle = tpm[ownerAuth].CreatePrimary(
					TpmRh.Owner,                            // In the owner-hierarchy
					new SensitiveCreate( keyAuth, null ),     // With this auth-value
					keyTemplate,                            // Describes key
					null,                                   // Extra data for creation ticket
					new PcrSelection[ 0 ],                    // Non-PCR-bound
					out keyPublic,                          // PubKey and attributes
					out creationData, out creationHash, out creationTicket );    // Not used here
				Console.WriteLine( "New public key\n" + keyPublic.ToString() );

Running this throws an exception with the message Error {BadAuth} was returned for command CreatePrimary

I'm not sure where to go with this to debug further, if it's usage error then I'll happily add some extra explantation to the example.

TSS.CPP Tpm2::NV_DefineSpace errors with code TPM_RC::BAD_AUTH (0xA2) for TpmTbsDevice

I have the following simple code:

auto device = TpmTbsDevice();

    if(!device.Connect())
    {
        return 1;
    }

    Tpm2 tpm(device);

    ByteVec nvAuth = { '1', '2', '3', '4' };

    TPM_HANDLE nvHandle = TPM_HANDLE::NVHandle(100);

    ByteVec policy = {};

    TPMS_NV_PUBLIC nvTemplate(nvHandle, TPM_ALG_ID::SHA256, TPMA_NV::AUTHWRITE, policy, 20);

    TPM_HANDLE ownerHandle = TPM_HANDLE::FromReservedHandle(TPM_RH::OWNER);
    // ownerHandle.setAuth(...)

    try
    {
        tpm.NV_DefineSpace(ownerHandle, nvAuth, nvTemplate);
    } 
    catch(system_error e)
    {

    }

Yet it fails with return code BAD_AUTH, indicating a failure when trying to authorize the command.

I've tried two ways of setting the Owner Authorization: First by retrieving it from Tbsi_Get_OwnerAuth, and second by changing the password to something trivial, such as "12345678" and setting the auth to that string. Both yield the same error.

I've even tried crafting my own command buffer and calling Tbsip_Submit_Command directly, which also gives me the same error.

Am I setting the auth incorrectly?

I'm testing this on Windows Server 2012 R2, with a TPM 2.0 family chip. The reported Manufacturer name is "IFX v5.50" from the TPM management console.

Allow connection to TPM simulator on arbitrary port

Hi,

I don't know how contributions work with this project, so I thought: let's just open it up as an issue.

(Talking about the TSS.Java, as I use it)

The Problem:
A TPM simulator can be run on a user-specified port. And thus, connection to local TPM simulators should be possible to do the same.

Solution:
This can be achieved by adding a version of localTpmSimulator() in the TpmFactory Class, which gets a port as a parameter and passes it to TpmDeviceTcp(host, port) constructor (line 25).

I'd really appreciate this. If you want, I could also simply open up a pull request.

Thanks and best regards,
Lucas

TSS.MSR for UWP

Hello Team,

I am getting TcpTpmDevice error while using one of your samples of .net () in UWP project.
Steps followed - 1. Copied all .cs files from TSS.NET to TSS.UWP
2. Successfully built TSS.UWP.
3. Created new universal project for windows 10 in VS2015
4. Added TSS.UWP in solution and took its reference in universal project
5. Copied Program.cs of Authorization sample project of TSS.NET and edited it according to UWP requirements.
6. Unsuccessful build.

Below are attached screenshots for reference. Please let me know if you get the solution.

uwp_exception

Thanks in advance.

'tag': is not a member of 'TpmCpp::TPMT_TK_HASHCHECK'

Hallo,
TSS.CPP doesn't compile due to the following errors:
error C2661: 'TpmCpp::_TPMT_TK_HASHCHECK::_TPMT_TK_HASHCHECK': no overloaded function takes 3 arguments
\tss.msr\tss.cpp\include\extensions\tpmt_tk_hashcheck.h(20): error C2039: 'tag': is not a member of 'TpmCpp::TPMT_TK_HASHCHECK'
\tss.msr\tss.cpp\include\extensions\tpmt_tk_hashcheck.h(7): note: see declaration of 'TpmCpp::TPMT_TK_HASHCHECK'

How to export public key?

In looking at the sample code for Signing, it looks like there may have once been code to export the public key. Was this code removed (as hinted to in the NOTE).

How do I get the public key into a usable format (xml, pem, x509, etc)?

// NOTE: 12-JAN-2016: May be removing support for policy
//       serialization. We'd like to get feedback on whether
//       this is a desirable feature and should be retained.
//
// {
//     const string fileName = "sample.xml";
//     string xmlVersionOfObject = keyPublic.GetXml();
//     keyPublic.XmlSerializeToFile(fileName);
//     var copyOfPublic = TpmStructureBase.XmlDeserializeFromFile<TpmPublic>(fileName);

[C++] RSA signature verification is hard-coded to SHA-1

The TSS.CPP implementation of RSA signature verification has SHA-1 hard-coded in the implementation of:

CRYPT_RESULT _cpri__ValidateSignatureRSA(RSA_KEY *key, TPM_ALG_ID scheme, TPM_ALG_ID hashAlg, UINT32 hInSize, BYTE *hIn, UINT32 sigInSize, BYTE *sigIn, UINT16 saltSize);

The hashAlg param is ignored, and instead NID_sha1 is always used for the OpenSSL call here:

int res = RSA_verify(NID_sha1, hIn, hInSize, sigIn, sigInSize, keyX);

  • Impact: TSS.CPP fails to verify any RSASSA signature with hash alg. other than SHA-1

  • To reproduce: Generate a TPM key with RSASSA-SHA256 (e.g. using the params below), sign (e.g. Quote()), verify (e.g. ValidateQuote()) --> FAILURE.

    TpmCpp::TPMS_RSA_PARMS(
        TpmCpp::TPMT_SYM_DEF_OBJECT::NullObject(),
        TpmCpp::TPMS_SCHEME_RSASSA(TpmCpp::TPM_ALG_ID::SHA256), 2048, 65537
    )
    

Tbsi_Get_OwnerAuth can't get real OwnerAuth

I'm trying to output the OwnerAuth in NV (Windows) sample as below:
byte[] ownerAuth;
if (GetOwnerAuthFromOS(out ownerAuth))
{
tpm.OwnerAuth = ownerAuth;
Console.WriteLine("OwnerAuth: {0}", BitConverter.ToString(ownerAuth));
}
I tried it on 2 of my computer, but it always return all zero value, while the actuall OwnerAuth is not null (read by get-tpm with power shell):
Running as Administrator. Deleting and re-creating NV entry.
OwnerAuth: 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00

It is a bug?

Verfiy signature on linux using .net

Hello, I'm trying to validate a quote on a linux machine, and as per the documentation there is a bug for hash verification on mono that throws algorithm is not supported. By looking deeper I guess the issue comes from this function in the mono implementation of RSACryptoServiceProvider:

private string GetHashNameFromOID (string oid) 
		{
			switch (oid) {
			case "1.3.14.3.2.26":
				return "SHA1";
			case "1.2.840.113549.2.5":
				return "MD5";
			case "2.16.840.1.101.3.4.2.1":
				return "SHA256";
			case "2.16.840.1.101.3.4.2.2":
				return "SHA384";
			case "2.16.840.1.101.3.4.2.3":
				return "SHA512";
			default:
				throw new CryptographicException (oid + " is an unsupported hash algorithm for RSA signing");
			}
}

So I guess there is a mismatch from the values representing the hash algorithm passed by the Tpm2lib to this one, which causes the error. So my question is, which part of the implementation I have to change, so that the value is recognized by the mono implementation of System.Security.Cryptography

Thank you

Minor updates to comments required in Samples:PolicySimplest()

The comments in the PolicySimpleTest() explaining the code is slightly confusing. The comments say that the policy being created is to ensure only TPM2_Sign can be performed but is really HMAC_Start. Later comments in the same function reference TPM2_ReadPublic as well, which I dont think is the intent ?

Would be nice to get that cleaned up.

fdefs.h has "using namespace std;" in it, causes issues

The following is on line 54/55 in TSS.CPP/Src/fdefs.h

using namespace std;
typedef unsigned char byte;

This causes issues throughout the library using this in C++17 as std::byte is now a thing. It can't resolve the typedef of byte here versus std::byte in the other files. This is on VS 2019 Professional v16.4.2.

Recommend removing using namespace std and changing the declarations that depend on this to avoid using this way in .h files.

Win10 AnnUpdate

Hi folks. I'm no expert on TPM because I never had an issue as important as the next Win10 update.
I probably shouldn't post this here, but since you're related to the subject... here's my question:

If my hardware doesn't support (nor has) a hardware-based TPM module: may I simulate it with one of your tools?

Otherwise, Win10 Anniversary Update won't install on my PC :(

Thanks in advance.

Mario.

TcpTpmDevice missing

In the example provided in the Azure doc i see the demo using the TcpTpmDevice class (TCP/socket communication to the TPM). Why is not present in this project? Here there are only the InprocTpm and TbsDevice implementation?

thanks,
Antonio

Decrypt and Sign with Storage Root Key

This method sample Samples::PrimaryKeys() gives me error
_void Samples::PrimaryKeys()
{
Announce("PrimaryKeys");

// To create a primary key the TPM must be provided with a template.
// This is for an RSA1024 signing key.
TPMT_PUBLIC templ(TPM_ALG_ID::SHA1,
                  TPMA_OBJECT::sign | TPMA_OBJECT::fixedParent | TPMA_OBJECT::fixedTPM
                    | TPMA_OBJECT::sensitiveDataOrigin | TPMA_OBJECT::userWithAuth,
                  null,  // No policy
                  TPMS_RSA_PARMS(null, TPMS_SCHEME_RSASSA(TPM_ALG_ID::SHA256), 1024, 65537),
                  TPM2B_PUBLIC_KEY_RSA());

.................................................
// Create the key
auto newPrimary = tpm.CreatePrimary(TPM_RH::OWNER, sensCreate, templ, null, pcrSelect);_

I feel that here we can creating a SRK but the public template is saying that it is for signing, which seems to be not right. I have noticed that SRK must have TPMA_OBJECT::decrypt.
It looks to me that signing key can only be created as Child key for SRK. Can anybody confirm my understanding ?

Support for TPMv1.2

Here's the issue.

In Microsoft's Dev Center, it is described that both v1.2 and 2.0 can be supported at the same time by using TBS_CONTEXT_PARAMS2 structure (which was described in C++).

However
TSS.MSR Java Library won't support versions other than 2.0. Although Microsoft's lower-layer library have a field for that (includeTpm12), we cannot specify it under version field in the class TBS_CONTEXT_PARAMS2 which is in TpmDeviceTbs.java file.

"version" and "params" are hardcoded as;

parms.version = 2;
parms.params = 1 << 2;

in TpmDeviceTbs.java. I guess that we cannot specify any other value to include TPM1.2. Am I correct in this that this library will not support TPM v1.2 ?

TSS.NET does not work on Linux - Unable to load DLL 'tbs.dll': The specified module or one of its dependencies could not be found.

Trying using TSS.NET in a netcoreapp2.1 on Ubuntu 16.04 Linux I'm getting:

System.DllNotFoundException: Unable to load DLL 'tbs.dll': The specified module or one of its dependencies could not be found.
 (Exception from HRESULT: 0x8007007E)
   at Tpm2Lib.TbsWrapper.NativeMethods.Tbsi_Context_Create(TBS_CONTEXT_PARAMS& ContextParams, UIntPtr& Context)
   at Tpm2Lib.TbsDevice.Connect()
   at Microsoft.Azure.Devices.Tpm.TpmDevice..ctor(Tpm2Device tpmDevice, UInt32 logicalDeviceId, Byte[] ekAuth, Action`2 initializeAction) in /home/cristian/int/DpsPoc/DpsPocLib/Tpm/TpmDevice.cs:line 56

Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'tbs.dll': The specified module or one of its dependencies could not be found.
 (Exception from HRESULT: 0x8007007E)

@amarochk and I discussed offline that the steps to enable this are:

  • Create a new class similar to TbsDevice
  • Instead of sending TPM command buffer via the TBS API, send it to /dev/tpm_n_ (n being the TPM device ID).
  • Packaging with multi target for RID == linux-x64

NVWrite prohibit

Is there a way to prohibit that a NVWrite can be done on an index with a different Auth than before?

Unable to compile with .Net Native Toolchain once Microsoft.TSS is added

This is on a UWP app. Disabling .Net Native Toolchain works, Debug build works, both compile and run. This is on VS 2017 RC.

Here is the error, any way around this:

2> Generating code...
2> Interop code generated.
2> Generating serialization code
2> Compiling interop code
2>C:\Users\marek.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
2>C:\Users\marek.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : at System.Collections.Generic.Dictionary2.get_Item(TKey key) 2>C:\Users\marek\.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : at SerializationAssemblyGenerator.Program.AddKnownContractsLists(McgCodeTypeDeclaration container, ContractTables tables) 2>C:\Users\marek\.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : at SerializationAssemblyGenerator.Program.GenerateDataContractSerializerHelperCode(IEnumerable1 contracts, IEnumerable1 jsonContracts, IEnumerable1 wcfSerializers)
2>C:\Users\marek.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : at SerializationAssemblyGenerator.Program.GenerateDataContractSerializerHelper(IEnumerable1 contracts, IEnumerable1 jsonContracts, GeneratorSettings settings, String intermediateAssembly, IEnumerable`1 wcfSerializers)
2>C:\Users\marek.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : at SerializationAssemblyGenerator.Program.Main(String[] args)
2> Generating System.Reflection.DispatchProxy proxy code.
2>C:\Users\marek.nuget\packages\microsoft.net.native.compiler\1.6.0\tools\Microsoft.NetNative.targets(691,5): error : ILT0032: Failed to compile serialization code. See the build log for error details.

Policy based NV read in Java

Hello,
I am trying to read NVRam using the TSS.Java in a location associated to a policy.
I have read that there is no complete support for policies in the Java implementation, but having a look around to the code, all the parts seem to be there.

I created the following snippet, checked that the policyDigest is equal to the one obtained listing the nvram entries. The problem is that I'm not able to fetch the value.

Tpm tpm = TpmFactory.platformTpm();
cleanSlots(tpm, TPM_HT.TRANSIENT);
cleanSlots(tpm, TPM_HT.LOADED_SESSION);
        
byte[] nonceCaller = Helpers.getRandom(20);
StartAuthSessionResponse policySession = tpm.StartAuthSession(TPM_HANDLE.NULL, TPM_HANDLE.NULL, nonceCaller, new byte[0], TPM_SE.POLICY, TPMT_SYM_DEF.nullObject(), TPM_ALG_ID.SHA256);
tpm.PolicyPCR(policySession.handle, new byte[0], TPMS_PCR_SELECTION.CreateSelectionArray(TPM_ALG_ID.SHA1, 9));
        
byte[] policyDigest = tpm.PolicyGetDigest(policySession.handle);
        
String policy = Helpers.toHex(policyDigest);
System.out.println("Policy: " + policy);
        
tpm._withSession(policySession.handle);

int nvIndex = 0x1500016;

TPM_HANDLE nvHandle = TPM_HANDLE.NV(nvIndex);

byte[] dataRead = tpm.NV_Read(nvHandle, nvHandle, 16, 0);

try {
            tpm.FlushContext(policySession.handle);
            tpm.close();
} catch (IOException e) {

}

Am I missing something there?

Thanks.
Best regards,
Matteo

Access denied and no logs generated

Running on a win 10 client, logged in as user, cmd prompt running as local admin (We cant use the default way of opening a cmd prompt as administrator due to policy restrictions in effect)
When we run "tss VPN", we get an access is denied message at the beginning. The script then appears to run and collect logs, but the output file is not there after the script finishes (output shows compressed cab file in c:\MS_DATA\xxxxxxxxxxxxxx.cab, but there is no file created)

TSS.NET GetTime

Hi,

I'm currently implementing TPM2 GetTime Command using TSS.NET and have noticed that the response (Attest) includes ClockInfo. I would like the method to return TimeInfo as well. Is there a method available that does GetTime() and also return Time Info?

Any help will be much appreciated.

Thanks & Regards,
Haritha

Request to switch to a Logging framework

I am using TSS.CPP for a work project and would like to limit the messages printed to STDOUT and STDERR. It is working quite well for me, but I wondering if this project can be switch to using a logging framework to allow informative/warning/error messages to be disabled or redirected to another log destination when compiling for release.
Thank you

Provide ECDH get secret example

Is it possible to give an example on generating an ECDH secret from a key created using TSS and an imported public key?

I do not see any examples on DH key exchanges in the samples.

Fail to compile TSS.CPP on linux

Hi,
I'm trying to compile the TSS.CPP on Ubuntu 18.04 LTS with gcc-7
I get many "Incomplete type" errors:
e.g.
gcc -Wall -c -g -fPIC -D _TPMCPPLIB -std=c++11 -I../Src AuthSessions.cpp
In file included from /usr/include/c++/7/vector:64:0,
from fdefs.h:63,
from Helpers.h:13,
from TpmStructureBase.h:8,
from TpmTypes.h:8,
from Tpm2.h:8,
from stdafx.h:59,
from AuthSessions.cpp:10:
/usr/include/c++/7/bits/stl_vector.h: In instantiation of ‘struct std::vectorTpmCpp::TPMS_PCR_SELECTION::_Temporary_value’:
fdefs.h:117:46: required from here
/usr/include/c++/7/bits/stl_vector.h:1467:33: error: invalid application of ‘sizeof’ to incomplete type ‘TpmCpp::TPMS_PCR_SELECTION’
typename aligned_storage<sizeof(_Tp), alignof(_Tp)>::type __buf;
^
/usr/include/c++/7/bits/stl_vector.h: In instantiation of ‘struct std::vectorTpmCpp::TPMS_TAGGED_PCR_SELECT::_Temporary_value’:
fdefs.h:118:46: required from here
/usr/include/c++/7/bits/stl_vector.h:1467:33: error: invalid application of ‘sizeof’ to incomplete type ‘TpmCpp::TPMS_TAGGED_PCR_SELECT’
/usr/include/c++/7/bits/stl_vector.h: In instantiation of ‘struct std::vectorTpmCpp::TPMS_TAGGED_PROPERTY::_Temporary_value’:
fdefs.h:119:46: required from here

Any Idea?

Getting NvAuthorization error with NvCertify

I'm trying to attest an NV index with NvAttr.Authread attribute using NvCertify and I'm getting a NvAuthorization error.

Below you can see a minimal example to reproduce the problem. I guess the problem is that I don't provide the authentication for the NV index to NvCertify, and I don't see how I could provide that password.

How can I make this work?

using System.Threading.Tasks;
using Tpm2Lib;

namespace TpmTest
{
    class Program
    {
        static async Task Main()
        {
            byte[] Data = new byte[] { 1, 2, 3, 4, 5 };

            AuthValue OwnerAuth = new AuthValue();
            AuthValue NvAuth = AuthValue.FromRandom(10);
            AuthValue AikAuth = AuthValue.FromRandom(10);

            TpmHandle NvHandle = TpmHandle.NV(0);
            TpmHandle AikHandle = TpmHandle.Persistent(0);

            using (var device = new TcpTpmDevice("localhost", 2321))
            using (var tpm = new Tpm2(device))
            {

                device.Connect();
                if (device is TcpTpmDevice)
                {
                    device.PowerCycle();
                    tpm.Startup(Su.Clear);
                }

                // Clear TPM
                tpm.Clear(TpmHandle.RhPlatform);

                // Write id to NV memory
                tpm[OwnerAuth].NvDefineSpace(TpmHandle.RhOwner, NvAuth, new NvPublic(NvHandle, TpmAlgId.Sha256, NvAttr.Authread | NvAttr.Ownerwrite, null, (ushort)Data.Length));
                tpm[OwnerAuth].NvWrite(TpmHandle.RhOwner, NvHandle, Data, 0);

                // Reading data works fine
                var readData = tpm[NvAuth].NvRead(NvHandle, NvHandle, (ushort)Data.Length, 0);

                // Create attestation identity key
                var attestationIdentityKeyTemplate = new TpmPublic(
                    TpmAlgId.Sha256,
                    ObjectAttr.Restricted | ObjectAttr.UserWithAuth | ObjectAttr.AdminWithPolicy | ObjectAttr.Sign | ObjectAttr.FixedTPM | ObjectAttr.FixedParent | ObjectAttr.SensitiveDataOrigin,
                    null,
                    new RsaParms(new SymDefObject(), new SchemeRsassa(TpmAlgId.Sha256), 2048, 0), new Tpm2bPublicKeyRsa());
                var createPrimaryResult = await tpm[OwnerAuth].CreatePrimaryAsync(TpmHandle.RhOwner, new SensitiveCreate(AikAuth, null), attestationIdentityKeyTemplate, null, null);
                tpm[OwnerAuth].EvictControl(TpmHandle.RhOwner, createPrimaryResult.handle, AikHandle);
                tpm.FlushContext(createPrimaryResult.handle);

                // Signing the NV index using the attestation key fails with NvAuthorization
                var attest = tpm[AikAuth].NvCertify(AikHandle, TpmHandle.RhOwner, NvHandle, null, new SchemeRsassa(TpmAlgId.Sha256), (ushort)Data.Length, 0, out var signature);

            }
        }
    }
}

TcpTpmDevice is ignoring SetSocketTimeout

There are two issues:

  1. TcpTpmDevice doesn't use the SocketTimeout. (Offline discussion with @amarochk.)
  2. TcpTpmDevice.SetSocketTimeout fails before calling Connect().

For some simulators (real TCP TPM resourcemanagers?) connecting from two different clients at the same time causes one of them to block during Connect() on Socket.Receive(). We should have a way to avoid the situation by timing out for both the TCP connect and r/w operations.

More Samples Needed for Java Version

There are way more samples in C++ version of this TSS Implementation. In Java version, on the contrary, we lack samples and demonstrations. I hope there will be more sample use cases under Samples class.

One can easily copy them from C++ project, and rewrite it into Java.

NuGet for Native C should be separate

Currently, the Microsoft.TSS NuGet includes both the Native DLL and multiple .Net managed DLLs.

I believe that two separate NuGet packages are required. The native one should have different targets such as /build/Release/... and also contain the .h and .lib files similar to this.

Windows Store Certification Failure

(Original post on azure-iot-sdk github)

As if a few weeks ago, the windows store app review updated their requirements which caused our app to fail the review.

Starting from a bare-bones passing UWP app, adding the Microsoft.TSS package causes the review to fail:

FAILED
Supported APIs

Error Found: The supported APIs test detected the following errors:
    API SetDllDirectoryW in kernel32.dll is not supported for this application type. TestUpload.dll calls this API.
Impact if not fixed: Using an API that is not part of the Windows SDK for Microsoft Store apps violates the Microsoft Store certification requirements.
How to fix: Review the error messages to identify the API that is not part of the Windows SDK for Microsoft Store apps. Please note, apps that are built in a debug configuration or without .NET Native enabled (where applicable) can fail this test as these environments may pull in unsupported APIs. Retest your app in a release configuration, and with .NET Native enabled if applicable. See the link below for more information:
Alternatives to Windows APIs in Microsoft Store apps. 

This means no app that contains this package can get published on the windows store.

The source of this is likely the import of SetDllDirectory() in TbsDevice.cs

How to use OpenSSL

Hello,
I'd like to use the TSS.MSR project as an engine for OpenSSL.
Is there any documentation, which shows how to use the TSS.MSR as an OpenSSL engine or could you provide a sample?

Thank you for your help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.