gpt4 book ai didi

c# - 如何使用 TPM(可信平台模块)加密字节

转载 作者:行者123 更新时间:2023-12-02 09:57:33 24 4
gpt4 key购买 nike

如何使用机器的 TPM 模块加密字节?

加密保护数据

Windows 提供了一个(相对)简单的 API 来使用 CryptProtectData 加密 blob。 API,我们可以封装一个简单易用的函数:

public Byte[] ProtectBytes(Byte[] plaintext)
{
//...
}
ProtectBytes详情不如您可以轻松使用它的想法重要:
  • 这是我想用 System 中保存的 key 加密的字节
  • 把加密的 blob 还给我

  • 返回的 blob 是未记录的 documentation包含解密和返回原始数据所需的一切的结构(散列算法、密码算法、salt、HMAC 签名等)。

    为了完整起见,这里是 ProtectBytes 的示例伪代码实现使用 Crypt API保护字节:

    public Byte[] ProtectBytes(Byte[] plaintext)
    {
    //Setup our n-byte plaintext blob
    DATA_BLOB dataIn;
    dataIn.cbData = plaintext.Length;
    dataIn.pbData = Addr(plaintext[0]);

    DATA_BLOB dataOut;

    //dataOut = EncryptedFormOf(dataIn)
    BOOL bRes = CryptProtectData(
    dataIn,
    null, //data description (optional PWideChar)
    null, //optional entropy (PDATA_BLOB)
    null, //reserved
    null, //prompt struct
    CRYPTPROTECT_UI_FORBIDDEN || CRYPTPROTECT_LOCAL_MACHINE,
    ref dataOut);
    if (!bRes) then
    {
    DWORD le = GetLastError();
    throw new Win32Error(le, "Error calling CryptProtectData");
    }

    //Copy ciphertext from dataOut blob into an actual array
    bytes[] result;
    SetLength(result, dataOut.cbData);
    CopyMemory(dataOut.pbData, Addr(result[0]), dataOut.cbData);

    //When you have finished using the DATA_BLOB structure, free its pbData member by calling the LocalFree function
    LocalFree(HANDLE(dataOut.pbData)); //LocalFree takes a handle, not a pointer. But that's what the SDK says.
    }

    如何对 TPM 做同样的事情?

    上面的代码仅用于加密本地机器的数据。数据使用 System 加密帐户作为 key 生成器 ( details, while interesting, are unimportant )。最终结果是我可以加密只能由本地机器解密的数据(例如硬盘加密主 key )。

    现在是时候更进一步了。我想加密一些只能由本地 TPM 解密的数据(例如硬盘加密主 key )。换句话说,我想用 Windows 中的 TPM 替换下面 Android 框图中的 Qualcomm 可信执行环境 ( TEE ):

    enter image description here

    备注 :我意识到 TPM 不进行数据签名(或者如果这样做了,它不能保证每次签名相同的数据都会给出相同的二进制输出)。这就是为什么我愿意将“RSA 签名”替换为“使用硬件绑定(bind) key 加密 256 位 blob”的原因。

    那么代码在哪里呢?

    问题是TPM编程是 completely undocumented on MSDN .没有可用于执行任何操作的 API。相反,您必须为自己找到一份 Trusted Computing Group's Software Stack (aka TSS) 的副本。 ,找出要发送到 TPM 的命令、有效载荷、顺序,然后调用 Window's Tbsip_Submit_Command function直接提交命令:
    TBS_RESULT Tbsip_Submit_Command(
    _In_ TBS_HCONTEXT hContext,
    _In_ TBS_COMMAND_LOCALITY Locality,
    _In_ TBS_COMMAND_PRIORITY Priority,
    _In_ const PCBYTE *pabCommand,
    _In_ UINT32 cbCommand,
    _Out_ PBYTE *pabResult,
    _Inout_ UINT32 *pcbOutput
    );

    Windows 没有更高级别的 API 来执行操作。

    这相当于通过向硬盘驱动器发出 SATA I/O 命令来尝试创建文本文件。

    为什么不直接使用裤子

    Trusted Computing Group (TCG) 确实定义了他们自己的 API: TCB Software Stack (TSS) .这个 API 的实现是由一些人创建的,名为 TrouSerS .然后一个人 ported that project to Windows .

    该代码的问题在于它不能移植到 Windows 世界中。例如,您不能在 Delphi 中使用它,也不能在 C# 中使用它。它要求:
  • OpenSSL
  • pThread

  • 我只想要 代码用我的 TPM 加密一些东西。

    以上 CryptProtectData除了函数体中的内容外,什么都不需要。

    使用 TPM 加密数据的等效代码是什么?正如其他人所指出的, you probably have to consult the three TPM manuals, and construct the blobs yourself .它可能涉及 TPM_seal命令。虽然我想我不想 密封数据,我想我要 绑定(bind)它:

    Binding – encrypts data using TPM bind key, a unique RSA key descended from a storage key. Sealing – encrypts data in a similar manner to binding, but in addition specifies a state in which TPM must be in order for the data to be decrypted (unsealed)



    我尝试阅读所需的三卷以找到我需要的 20 行代码:
  • Part 1 - Design Principles
  • Part 2 - Structures of the TPM
  • Part 3 - Commands

  • 但我不知道我在读什么。如果有任何类型的教程或示例,我可能会试一试。但我完全迷失了。

    所以我们问 Stackoverflow

    以同样的方式,我能够提供:

    Byte[] ProtectBytes_Crypt(Byte[] plaintext)
    {
    //...
    CryptProtectData(...);
    //...
    }

    有人可以提供相应的等价物吗:

    Byte[] ProtectBytes_TPM(Byte[] plaintext)
    {
    //...
    Tbsip_Submit_Command(...);
    Tbsip_Submit_Command(...);
    Tbsip_Submit_Command(...);
    //...snip...
    Tbsip_Submit_Command(...);
    //...
    }

    做同样的事情,除了不是锁在 System 中的 key LSA,是否被锁在 TPM 中?

    研究开始

    我不知道绑定(bind)到底是什么意思。但是查看 TPM Main - Part 3 Commands - Specification Version 1.2,提到了 绑定(bind) :

    10.3 TPM_UnBind

    TPM_UnBind takes the data blob that is the result of a Tspi_Data_Bind command and decrypts it for export to the User. The caller must authorize the use of the key that will decrypt the incoming blob. TPM_UnBind operates on a block-by-block basis, and has no notion of any relation between one block and another.



    令人困惑的是那里 Tspi_Data_Bind命令。

    研究工作

    令人震惊的是,没有人费心记录 TPM 或其操作。就好像他们花了所有的时间来想出这个很酷的东西来玩,但不想处理让它可用于某些东西的痛苦步骤。

    从(现在)免费书籍开始 A Practical Guide to TPM 2.0: Using the Trusted Platform Module in the New Age of Security :

    Chapter 3 - Quick Tutorial on TPM 2.0

    The TPM has access to a self-generated private key, so it can encrypt keys with a public key and then store the resulting blob on the hard disk. This way, the TPM can keep a virtually unlimited number of keys available for use but not waste valuable internal storage. Keys stored on the hard disk can be erased, but they can also be backed up, which seemed to the designers like an acceptable trade-off.



    如何使用 TPM 的公钥加密 key ?

    Chapter 4 - Existing Applications That Use TPMs

    Applications That Should Use the TPM but Don’t

    In the past few years, the number of web-based applications has increased. Among them are web-based backup and storage. A large number of companies now offer such services, but as far as we are aware, none of the clients for these services let the user lock the key for the backup service to a TPM. If this were done, it would certainly be nice if the TPM key itself were backed up by duplicating it on multiple machines. This appears to be an opportunity for developers.



    开发人员如何锁定 TPM 的 key ?

    Chapter 9 - Heirarchies

    USE CASE: STORING LOGIN PASSWORDS

    A typical password file stores salted hashes of passwords. Verification consists of salting and hashing a supplied password and comparing it to the stored value. Because the calculation doesn’t include a secret, it’s subject to an offline attack on the password file.

    This use case uses a TPM-generated HMAC key. The password file stores an HMAC of the salted password. Verification consists of salting and HMACing the supplied password and comparing it to the stored value. Because an offline attacker doesn’t have the HMAC key, the attacker can’t mount an attack by performing the calculation.



    这可以工作。如果 TPM 有一个 secret 的 HMAC key ,并且只有我的 TPM 知道 HMAC key ,那么我可以用“HMAC”替换“签名(又名 TPM 用它的私钥加密)”。但是在接下来的一行中,他完全颠倒了自己:

    TPM2_Create, specifying an HMAC key



    如果我必须指定 HMAC key ,这不是 TPM secret 。当您意识到这是有关 TPM 提供的加密实用程序的章节时,HMAC key 不是 secret 的事实就有意义了。您不必自己编写 SHA2、AES、HMAC 或 RSA,您可以重用 TPM 已有的内容。

    Chapter 10 - Keys

    As a security device, the ability of an application to use keys while keeping them safe in a hardware device is the TPM’s greatest strength. The TPM can both generate and import externally generated keys. It supports both asymmetric and symmetric keys.



    太棒了!你是怎么做到的!?

    Key Generator

    Arguably, the TPM’s greatest strength is its ability to generate a cryptographic key and protect its secret within a hardware boundary. The key generator is based on the TPM’s own random number generator and doesn’t rely on external sources of randomness. It thus eliminates weaknesses based on weak softwaresoftware with an insufficient source of entropy.



    是否 TPM 是否能够生成加密 key 并在硬件边界内保护其 secret ?是这样,怎么样?

    Chapter 12 - Platform Configuration Registers

    PCRs for Authorization

    USE CASE: SEALING A HARD DISK ENCRYPTION KEY TO PLATFORM STATE

    Full-disk encryption applications are far more secure if a TPM protects theencryption key than if it’s stored on the same disk, protected only by a password. First, the TPM hardware has anti-hammering protection (see Chapter 8 for a detailed description of TPM dictionary attack protection), making a brute-force attack on the password impractical. A key protected only by software is far more vulnerable to a weak password. Second, a software key stored on disk is far easier to steal. Take the disk (or a backup of the disk), and you get the key. When a TPM holds the key, the entire platform, or at least the disk and the motherboard, must be stolen.

    Sealing permits the key to be protected not only by a password but by a policy. A typical policy locks the key to PCR values (the software state) current at the time of sealing. This assumes that the state at first boot isn’t compromised. Any preinstalled malware present at first boot would be measured into the PCRs, and thus the key would be sealed to a compromised software state. A less trusting enterprise might have a standard disk image and seal to PCRs representing that image. These PCR values would be precalculated on a presumably more trusted platform. An even more sophisticated enterprise would use TPM2_PolicyAuthorize, and provide several tickets authorizing a set of trusted PCR values. See Chapter 14 for a detailed description of policy authorize and its application to solve the PCRbrittleness problem.

    Although a password could also protect the key, there is a security gain even without a TPM key password. An attacker could boot the platform without supplying a TPMkey password but could not log in without the OS username and password. The OSsecurity protects the data. The attacker could boot an alternative OS, say from a live DVD or USB stick rather that from the hard drive, to bypass the OS login security. However, this different boot configuration and software would change the PCRvalues. Because these new PCRs would not match the sealed values, the TPM would not release the decryption key, and the hard drive could not be decrypted.



    太棒了!这正是我碰巧想要的用例。这也是 Microsoft 使用 TPM 的用例。我该怎么做!?

    所以我读了整本书,并没有提供任何有用的信息。这是相当令人印象深刻的,因为它有 375 页。你想知道这本书包含了什么 - 回顾它,我不知道。

    因此,我们放弃了 TPM 编程的权威指南,转而使用 Microsoft 的一些文档:

    来自 Microsoft TPM Platform Crypto-Provider Toolkit .它准确地提到了我想要做的事情:

    The Endorsement Key or EK

    The EK is designed to provide a reliable cryptographic identifier for the platform. An enterprise might maintain a database of the Endorsement Keys belonging to the TPMs of all of the PCs in their enterprise, or a data center fabric controller might have a database of the TPMs in all of the blades. On Windows you can use the NCrypt provider described in the section “Platform Crypto Provider in Windows 8” to read the public part of the EK.



    TPM 内部的某个地方是一个 RSA 私钥。那把 key 被锁在那里——永远不会被外界看到。我希望 TPM 用它的私钥对某些东西进行签名(即用它的私钥对其进行加密)。

    所以我想要可能存在的最基本的操作:

    enter image description here

    用你的私钥加密一些东西。我什至(还)没有要求更复杂的东西:
  • 基于 PCR 状态“密封”它
  • 创建 key 并将其存储在 volatile 或非 volatile 内存中
  • 创建对称 key 并尝试将其加载到 TPM

  • 我要求 TPM 可以执行的最基本操作。为什么无法获得有关如何操作的任何信息?

    我可以得到随机数据

    当我说 RSA 签名是 TPM 可以做的最基本的事情时,我想我是在说谎。 大多数可以要求 TPM 做的基本事情是给我随机字节。 那个我已经想出了如何做:
    public Byte[] GetRandomBytesTPM(int desiredBytes)
    {
    //The maximum random number size is limited to 4,096 bytes per call
    Byte[] result = new Byte[desiredBytes];

    BCRYPT_ALG_HANDLE hAlgorithm;

    BCryptOpenAlgorithmProvider(
    out hAlgorithm,
    BCRYPT_RNG_ALGORITHM, //AlgorithmID: "RNG"
    MS_PLATFORM_CRYPTO_PROVIDER, //Implementation: "Microsoft Platform Crypto Provider" i.e. the TPM
    0 //Flags
    );
    try
    {
    BCryptGenRandom(hAlgorithm, @result[0], desiredBytes, 0);
    }
    finally
    {
    BCryptCloseAlgorithmProvider(hAlgorithm);
    }

    return result;
    }

    花哨的东西

    我意识到使用 TPM 的人数非常少。这就是为什么 Stackoverflow 上没有人有答案的原因。所以我真的不能太贪婪地解决我的常见问题。但我真正想做的是“密封”一些数据:

    enter image description here
  • 向 TPM 提供一些数据(例如 32 字节的 key Material )
  • 让 TPM 加密数据,返回一些不透明的 blob 结构
  • 稍后要求 TPM 解密 blob
  • 只有在 TPM 的 PCR 寄存器与加密期间相同时,解密才会起作用。

  • 换句话说:
    Byte[] ProtectBytes_TPM(Byte[] plaintext, Boolean sealToPcr)
    {
    //...
    }

    Byte[] UnprotectBytes_TPM(Byte[] protectedBlob)
    {
    //...
    }

    下一代加密(Cng,又名 BCrypt)支持 TPM

    Windows 中的原始加密 API 被称为加密 API。

    从 Windows Vista 开始,加密 API 已替换为 Cryptography API: Next Generation (内部称为 BestCrypt,缩写为 BCrypt,不要与 the password hashing algorithm 混淆)。

    Windows 附带两个 BCrypt 提供程序:
  • Microsoft 原始提供程序 ( MS_PRIMITIVE_PROVIDER ) 默认 :所有primitives (hashing, symmetric encryption, digital signatures, etc)的默认软件实现
  • Microsoft 平台加密提供程序 ( MS_PLATFORM_CRYPTO_PROVIDER ):提供 TPM 访问的提供商

  • 平台加密提供程序没有记录在 MSDN 上,但确实有来自 2012 年 Microsoft Research 站点的文档:

    TPM Platform Crypto-Provider Toolkit

    The TPM Platform Crypto Provider and Toolkit contains sample code, utilities and documentation for using TPM-related functionality in Windows 8. Subsystems described include the TPM-backed Crypto-Next-Gen (CNG) platform crypto-provider, and how attestation-service providers can use the new Windows features. Both TPM1.2 and TPM2.0-based systems are supported.



    微软的意图似乎是通过 来展示 TPM 加密功能。 Microsoft 平台加密提供程序 密码学异常 应用程序接口(interface)。

    使用 Microsoft BCrypt 进行公钥加密

    鉴于:
  • 我想执行 RSA 非对称加密(使用 TPM)
  • 微软 BestCrypt supports RSA asymmetric encryption
  • Microsoft BestCrypt 有一个 TPM 提供商

  • 一种前进的方式可能是弄清楚如何使用 进行数字签名。 Microsoft 加密下一代 API .

    我的下一步将是使用标准提供程序 ( MS_PRIMITIVE_PROVIDER ) 使用 RSA 公钥编写在 BCrypt 中进行加密的代码。例如:
  • modulus : 0xDC 67 FA F4 9E F2 72 1D 45 2C B4 80 79 06 A0 94 27 50 8209 DD 67 CE 57 B8 6C 4A 4F 40 9F D2 D1 69 FB 857 196E F B 87 4 B 6 C F 27 19 F 27 50 8209 58 36 37 99 29 AA 4F A8 12 E8 4F C7 82 2B 9D 72 2A 9C DE 6F C2 EE 12 6D CF F0 F2 B8 C4 DD 7C 5C 1A C8 17 DF 51 A80 4 B 2A 9 D B 9 D F EB 5C 51 1A D8 F8 F9 56 9E F8 FB 37 9B 3F D3 74 65 24 0D FF 34 75 57 A4 F5 BF 55
  • publicExponent : 65537

  • 随着该代码的运行,我可以切换到使用 TPM 提供程序 ( MS_PLATFORM_CRYPTO_PROVIDER )。

    2/22/2016:随着 Apple 被迫帮助解密用户数据,人们重新关注如何让 TPM 执行它发明的最简单的任务——加密某些东西。

    这大致相当于每个人都拥有一辆汽车,但没有人知道如何开始。它可以做非常有用和很酷的事情,如果我们能通过 步骤 1 .

    奖励阅读
  • Android - Encryption - Storing the encrypted key
  • Android Explorations - Revisiting Android disk encryption
  • DPAPI Secrets. Security analysis and data recovery in DPAPI (Part 1)
  • 最佳答案

    底漆

    接下来的所有内容都是关于 TPM 1.2。请记住,Microsoft 要求所有 future 的 Windows 版本都使用 TPM 2.0。 2.0 代与 1.2 代根本不同

    由于 TPM 设计原则,没有单线解决方案。将 TPM 视为资源有限的微 Controller 。它的主要设计目标是便宜,同时仍然安全。因此,TPM 删除了安全操作所不需要的所有逻辑。因此,TPM 仅在您至少有一些或多或少时才起作用 脂肪软件,以正确的顺序发出许多命令。这些命令序列可能会变得非常复杂。这就是 TCG 使用定义良好的 API 指定 TSS 的原因。如果您想走 Java 之路,甚至还有一个高级别的 Java API .我不知道 C#/.net 的类似项目

    发展

    在您的情况下,我建议您查看 IBM 的软件 TPM。

  • Project page
  • Donwload the whole package

  • 在包中,您会发现 3 个非常有用的组件:
  • 一个软件 TPM 模拟器
  • 轻量级 tpm 库
  • 一些基本的命令行实用程序

  • 您不一定需要软件 TPM 模拟器,您也可以连接到机器的 HW TPM。但是,您可以拦截发出的命令并查看响应,从而了解它们是如何组装的以及它们如何与命令规范相对应。

    高水平

    先决条件:
  • TPM 已激活
  • TPM 驱动已加载
  • 您已拥有 TPM

  • 为了密封 blob,您需要执行以下操作:
  • 创建 key
  • 将 key 块存储在某处
  • 确保 key 已加载到 TPM
  • 密封 blob

  • 要开封,您需要:
  • 获取 key 块
  • 将 key 加载到 TPM
  • 打开密封的 blob

  • 您可以将 key blob 存储在用于存储 protected 字节的数据结构中。

    您需要的大多数 TPM 命令都是授权命令。因此,您需要在需要时建立授权 session 。 AFAIR 这些主要是 OSAP session 。

    TPM 命令

    目前我无法运行调试版本,因此我无法为您提供确切的顺序。所以认为这是一个 无序 您必须使用的命令列表:
  • TPM_OSAP
  • TPM_CreateWrapKey
  • TPM_LoadKey2
  • TPM_Seal

  • 如果您还想读取当前的 PCR 值:
  • TPM_PCRRead
  • 关于c# - 如何使用 TPM(可信平台模块)加密字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28862767/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com