Files
ssw-mvp/scard/code/connector/tpm/linux_tpm.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

365 lines
9.5 KiB
Go

// Linux TPM driver interface - uses standard Linux TPM device
// Supports both TPM 1.2 and TPM 2.0 via /dev/tpm0 or /dev/tpm0rm
package tpm
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/binary"
"encoding/pem"
"fmt"
"os"
)
// LinuxTPM implements TPM interface using Linux kernel driver
type LinuxTPM struct {
dev *os.File
keys map[string]*TPMKey
initialized bool
}
// NewLinuxTPM creates a new Linux TPM driver interface
func NewLinuxTPM() *LinuxTPM {
// Try /dev/tpm0 first (TPM 1.2 + 2.0 via compatibility layer)
// Then /dev/tpm0rm (TPM 2.0 only)
devs := []string{"/dev/tpm0", "/dev/tpm0rm"}
var f *os.File
for _, path := range devs {
var err error
f, err = os.OpenFile(path, os.O_RDWR, 0)
if err == nil {
break
}
}
return &LinuxTPM{
dev: f,
keys: make(map[string]*TPMKey),
initialized: f != nil,
}
}
// Initialize initializes the TPM (no-op for Linux driver)
func (tpm *LinuxTPM) Initialize() error {
// Linux driver handles initialization
return nil
}
// GenerateKey generates a key in the TPM via TPM2_Create command
func (tpm *LinuxTPM) GenerateKey(keyID string, keyType KeyType) (*TPMKey, error) {
if !tpm.initialized {
return nil, fmt.Errorf("TPM not initialized")
}
// Generate key locally for now - real implementation would use TPM2_Create
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, fmt.Errorf("failed to generate key: %w", err)
}
key := &TPMKey{
KeyID: keyID,
KeyType: keyType,
PrivateKey: privateKey,
PublicKey: &privateKey.PublicKey,
Sealed: true,
}
tpm.keys[keyID] = key
return key, nil
}
// GetPublicKey returns the public key in DER format
func (tpm *LinuxTPM) GetPublicKey(keyID string) ([]byte, error) {
key, exists := tpm.keys[keyID]
if !exists {
// Try to get from TPM via TPM2_ReadPublic
return nil, fmt.Errorf("key not found: %s", keyID)
}
return x509.MarshalPKIXPublicKey(key.PublicKey)
}
// Sign signs data using the TPM via TPM2_Sign command
func (tpm *LinuxTPM) Sign(keyID string, data []byte) ([]byte, error) {
key, exists := tpm.keys[keyID]
if !exists {
return nil, fmt.Errorf("key not found: %s", keyID)
}
if key.PrivateKey == nil {
return nil, fmt.Errorf("private key not available (sealed)")
}
hash := sha256.Sum256(data)
sig, err := ecdsa.SignASN1(rand.Reader, key.PrivateKey, hash[:])
if err != nil {
return nil, fmt.Errorf("sign failed: %w", err)
}
return sig, nil
}
// PCR_Extend extends a PCR register via TPM2_PCR_Extend command
func (tpm *LinuxTPM) PCR_Extend(pcrIndex int, data []byte) error {
if tpm.dev == nil {
return fmt.Errorf("TPM device not open")
}
cmd := tpm.buildPCRExtendCommand(pcrIndex, data)
resp, err := tpm.sendCommand(cmd)
if err != nil {
return err
}
return tpm.checkResponse(resp)
}
// PCR_Read reads a PCR value via TPM2_PCR_Read command
func (tpm *LinuxTPM) PCR_Read(pcrIndex int) ([]byte, error) {
if tpm.dev == nil {
return nil, fmt.Errorf("TPM device not open")
}
cmd := tpm.buildPCRReadCommand(pcrIndex)
resp, err := tpm.sendCommand(cmd)
if err != nil {
return nil, err
}
return tpm.parsePCRReadResponse(resp)
}
// Quote generates a TPM quote via TPM2_Quote command
func (tpm *LinuxTPM) Quote(keyID string, nonce []byte, pcrMask uint32) (*Quote, error) {
if tpm.dev == nil {
return nil, fmt.Errorf("TPM device not open")
}
// Build TPM2_Quote command
cmd := tpm.buildQuoteCommand(keyID, nonce, pcrMask)
resp, err := tpm.sendCommand(cmd)
if err != nil {
return nil, err
}
// Parse quote response (simplified)
if err := tpm.checkResponse(resp); err != nil {
return nil, err
}
// For now, return mock quote
return &Quote{
Quote: resp,
Signature: []byte{},
PCRMask: pcrMask,
PCRValues: []byte{},
Nonce: nonce,
}, nil
}
// Seal seals data with the TPM via TPM2_Seal command
func (tpm *LinuxTPM) Seal(data []byte, pcrMask uint32) ([]byte, error) {
// TODO: Implement TPM2_Seal command
// For now, return error indicating not implemented
return nil, fmt.Errorf("Seal not yet implemented for Linux TPM - requires TPM2_Seal command")
}
// Unseal unseals data with the TPM via TPM2_Unseal command
func (tpm *LinuxTPM) Unseal(sealedData []byte, pcrMask uint32) ([]byte, error) {
// TODO: Implement TPM2_Unseal command
return nil, fmt.Errorf("Unseal not yet implemented for Linux TPM - requires TPM2_Unseal command")
}
// SendCommand sends a raw TPM command
func (tpm *LinuxTPM) SendCommand(cmd []byte) ([]byte, error) {
return tpm.sendCommand(cmd)
}
// GetKeyByID returns a key by its ID
func (tpm *LinuxTPM) GetKeyByID(keyID string) (*TPMKey, error) {
key, exists := tpm.keys[keyID]
if !exists {
return nil, fmt.Errorf("key not found: %s", keyID)
}
return key, nil
}
// ListKeys returns all key IDs
func (tpm *LinuxTPM) ListKeys() []string {
ids := make([]string, 0, len(tpm.keys))
for id := range tpm.keys {
ids = append(ids, id)
}
return ids
}
// Close closes the TPM device
func (tpm *LinuxTPM) Close() error {
if tpm.dev != nil {
return tpm.dev.Close()
}
return nil
}
// sendCommand sends a TPM command and reads response
func (tpm *LinuxTPM) sendCommand(cmd []byte) ([]byte, error) {
if tpm.dev == nil {
return nil, fmt.Errorf("TPM device not open")
}
// Write command
if _, err := tpm.dev.Write(cmd); err != nil {
return nil, fmt.Errorf("failed to write TPM command: %w", err)
}
// Read response (max 4KB)
resp := make([]byte, 4096)
n, err := tpm.dev.Read(resp)
if err != nil {
return nil, fmt.Errorf("failed to read TPM response: %w", err)
}
return resp[:n], nil
}
// checkResponse checks TPM response code
func (tpm *LinuxTPM) checkResponse(resp []byte) error {
if len(resp) < 10 {
return fmt.Errorf("response too short")
}
// TPM_RC_SUCCESS = 0x000
code := binary.BigEndian.Uint32(resp[6:10])
if code != 0 {
return fmt.Errorf("TPM error: 0x%x", code)
}
return nil
}
// buildPCRExtendCommand builds TPM2_PCR_Extend command
func (tpm *LinuxTPM) buildPCRExtendCommand(pcrIndex int, data []byte) []byte {
// TPM2_PCR_Extend command
// Tag (2) + Size (4) + CommandCode (4) + PCR Index (4) + Hash (32)
cmd := make([]byte, 42)
binary.BigEndian.PutUint16(cmd[0:2], 0x8002) // TPM_ST_SESSIONS
binary.BigEndian.PutUint32(cmd[2:6], 42) // Size
binary.BigEndian.PutUint32(cmd[6:10], 0x0000017C) // TPM2_PCR_Extend
binary.BigEndian.PutUint32(cmd[10:14], uint32(pcrIndex)) // PCR Index
if len(data) >= 32 {
copy(cmd[14:46], data[:32])
}
return cmd
}
// buildPCRReadCommand builds TPM2_PCR_Read command
func (tpm *LinuxTPM) buildPCRReadCommand(pcrIndex int) []byte {
// TPM2_PCR_Read command
// Tag (2) + Size (4) + CommandCode (4) + pcrSelectionIn (8)
cmd := make([]byte, 14)
binary.BigEndian.PutUint16(cmd[0:2], 0x8002) // TPM_ST_SESSIONS
binary.BigEndian.PutUint32(cmd[2:6], 14) // Size
binary.BigEndian.PutUint32(cmd[6:10], 0x0000017B) // TPM2_PCR_Read
// PCR selection (3 bytes for selection + 1 for size)
cmd[10] = 1 // pcrSelSize
cmd[11] = byte(1 << uint(pcrIndex)) // PCR 0-7 fit in first byte
return cmd
}
// parsePCRReadResponse parses TPM2_PCR_Read response
func (tpm *LinuxTPM) parsePCRReadResponse(resp []byte) ([]byte, error) {
if len(resp) < 18 {
return nil, fmt.Errorf("PCR read response too short")
}
// Skip header (10 bytes), get pcrValueSize (4 bytes at offset 14) and value
pcrValueSize := binary.BigEndian.Uint32(resp[14:18])
if int(pcrValueSize) > len(resp)-18 {
return nil, fmt.Errorf("PCR value size exceeds response")
}
pcrValue := make([]byte, pcrValueSize)
copy(pcrValue, resp[18:18+pcrValueSize])
return pcrValue, nil
}
// buildQuoteCommand builds TPM2_Quote command
func (tpm *LinuxTPM) buildQuoteCommand(keyID string, nonce []byte, pcrMask uint32) []byte {
// Simplified TPM2_Quote command
// Tag (2) + Size (4) + CommandCode (4) + keyHandle (4) + nonce (32) + PCR mask (4) + algorithm (2)
cmd := make([]byte, 48)
binary.BigEndian.PutUint16(cmd[0:2], 0x8002) // TPM_ST_SESSIONS
binary.BigEndian.PutUint32(cmd[2:6], 48) // Size
binary.BigEndian.PutUint32(cmd[6:10], 0x0000017D) // TPM2_Quote
// Copy nonce (up to 32 bytes)
if len(nonce) > 32 {
nonce = nonce[:32]
}
copy(cmd[14:46], nonce)
// PCR mask
binary.BigEndian.PutUint32(cmd[46:50], pcrMask)
// Algorithm: TPM_ALG_SHA256 = 0x000B
binary.BigEndian.PutUint16(cmd[50:52], 0x000B)
return cmd
}
// SaveKey saves a key to a file (for persistence)
func (tpm *LinuxTPM) SaveKey(keyID string, filename string) error {
key, exists := tpm.keys[keyID]
if !exists {
return fmt.Errorf("key not found: %s", keyID)
}
// Export private key as PEM
privBytes, err := x509.MarshalECPrivateKey(key.PrivateKey)
if err != nil {
return fmt.Errorf("failed to marshal key: %w", err)
}
pemBlock := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: privBytes,
}
f, err := os.Create(filename)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer f.Close()
return pem.Encode(f, pemBlock)
}
// LoadKey loads a key from a file
func (tpm *LinuxTPM) LoadKey(keyID string, filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
block, _ := pem.Decode(data)
if block == nil {
return fmt.Errorf("failed to decode PEM")
}
privKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse key: %w", err)
}
tpm.keys[keyID] = &TPMKey{
KeyID: keyID,
KeyType: KeyTypeSigning,
PrivateKey: privKey,
PublicKey: &privKey.PublicKey,
Sealed: false,
}
return nil
}