TPM-Based Device Fingerprinting Library
TrustCore-TPM is a Python library for hardware-based device fingerprinting using Trusted Platform Module (TPM) 2.0. It provides cryptographically enforced device identity with automatic policy enforcement.
- Hardware-rooted device fingerprinting using TPM 2.0
- PCR-based state binding for platform integrity
- PCR-bound sealing via TrustCore-TPM
- Challenge-response authentication protocol
- Automatic policy enforcement
- Offline verification capability
- Comprehensive audit logging
pip install trustcore-tpmgit clone https://github.com/Johnsonajibi/Trustcore-TPM.git
cd Trustcore-TPM
pip install -e .- Python 3.8 or higher
- TPM 2.0 hardware (or software simulator)
- Windows: WMI access for TPM operations
- Linux: tpm2-tools package
from tpm_fingerprint_lib import OfflineVerifier
# Initialize verifier
verifier = OfflineVerifier()
# Enroll device
device_id = "device-001"
result = verifier.enroll_device(device_id)
if result["success"]:
print(f"Device enrolled: {result['fingerprint_id']}")
# Verify device
verification = verifier.verify_device(device_id)
print(f"Valid: {verification['valid']}")from tpm_fingerprint_lib import PolicyEngine, ConsequenceHandler
# Define policy
policy = {
"max_failures": 3,
"require_tpm": True,
"allowed_pcrs": [0, 1, 2, 3, 7]
}
# Verify with policy
engine = PolicyEngine()
result = engine.evaluate(device_id, policy)
if result["violated"]:
# Handle consequences
handler = ConsequenceHandler()
handler.execute(device_id, result["violations"])graph TB
subgraph "Application Layer"
A[Your Application]
end
subgraph "Library API Layer"
B[OfflineVerifier]
C[PolicyEngine]
D[ConsequenceHandler]
end
subgraph "Core Engine Layer"
E[FingerprintEngine]
F[PolicyEngine Core]
G[ConsequenceHandler Core]
H[AuditLogger]
end
subgraph "TPM Abstraction Layer"
I[TPMOperations]
end
subgraph "Hardware Layer"
J[TPM 2.0 Chip]
end
A --> B
A --> C
A --> D
B --> E
C --> F
D --> G
E --> I
F --> I
G --> H
H --> I
I --> J
style J fill:#3498db,stroke:#2980b9,color:#fff
style I fill:#95a5a6,stroke:#7f8c8d
style E fill:#2ecc71,stroke:#27ae60
style F fill:#2ecc71,stroke:#27ae60
style G fill:#2ecc71,stroke:#27ae60
style H fill:#2ecc71,stroke:#27ae60
Enrollment and Verification Sequence:
sequenceDiagram
participant App as Application
participant Ver as OfflineVerifier
participant FP as FingerprintEngine
participant TPM as TPM Hardware
participant Policy as PolicyEngine
participant Cons as ConsequenceHandler
Note over App,TPM: Device Enrollment
App->>Ver: enroll_device(device_id)
Ver->>FP: generate_fingerprint()
FP->>TPM: read_pcrs()
TPM-->>FP: PCR values
FP->>TPM: seal_data(fingerprint)
TPM-->>FP: sealed_blob
FP-->>Ver: fingerprint_id
Ver-->>App: {success, fingerprint_id}
Note over App,Cons: Device Verification
App->>Ver: verify_device(device_id)
Ver->>FP: verify_fingerprint()
FP->>TPM: unseal_data()
TPM-->>FP: unsealed_data or FAIL
alt Verification Success
FP-->>Ver: valid=true
Ver-->>App: {valid: true}
else Verification Failure
FP-->>Ver: valid=false
Ver->>Policy: evaluate_policy()
Policy-->>Ver: violations
Ver->>Cons: execute_consequences()
Cons-->>Ver: enforcement_result
Ver-->>App: {valid: false, violations}
end
┌─────────────────────────────────────────────┐
│ Application Layer │
│ (Your Application) │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ Library API Layer │
│ OfflineVerifier, PolicyEngine, etc. │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ Core Engine Layer │
│ - FingerprintEngine │
│ - PolicyEngine │
│ - ConsequenceHandler │
│ - AuditLogger │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ TPM Abstraction Layer │
│ TPMOperations │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ Hardware Layer │
│ TPM 2.0 Chip │
└─────────────────────────────────────────────┘
Device fingerprints are cryptographically bound to TPM Platform Configuration Registers (PCRs). The fingerprint lifecycle is managed through hardware state:
- Enrollment: Device attributes are collected and sealed to current PCR values
- Verification: TPM unseals data only if PCR values match enrollment state
- Expiry: Fingerprint automatically becomes invalid when:
- Boot state changes (PCR 0-3)
- Firmware is updated (PCR 0-2)
- Secure Boot state changes (PCR 7)
- Custom policy conditions are triggered
State Machine:
stateDiagram-v2
[*] --> Generated: Device Enrollment
Generated --> Valid: PCR-bound Sealing
Valid --> Valid: Successful Verification
Valid --> Expired: Boot State Change
Valid --> Expired: Firmware Update
Valid --> Expired: Policy Violation
Valid --> Expired: Time Limit Reached
Expired --> [*]: Requires Re-enrollment
note right of Valid
Fingerprint bound to
TPM hardware state
end note
note right of Expired
Automatic expiry enforced
by cryptographic operations
end note
Comparison with Traditional Approaches:
| Traditional Fingerprinting | TrustCore-TPM |
|---|---|
| Software-based hash | PCR-bound sealing via TrustCore-TPM |
| Copyable identifier | Non-exportable capability |
| Manual revocation | Automatic expiry on state change |
| No hardware binding | TPM PCR binding |
| Replay vulnerable | Challenge-response protocol |
The fingerprint is not a static value—it is a cryptographic capability bound to specific TPM hardware.
Cloning Attack Flow:
graph LR
A[Attacker] -->|1. Steals fingerprint data| B[Fingerprint File]
B -->|2. Copies to new device| C[Cloned Device]
C -->|3. Attempts unseal| D{TPM Check}
D -->|Different PCR values| E[Unseal Fails]
D -->|Different TPM hardware| E
F[Legitimate Device] -->|Verification| G{TPM Unseal}
G -->|Correct PCRs| H[Success]
G -->|TPM generates proof| H
style E fill:#e74c3c,stroke:#c0392b,color:#fff
style H fill:#2ecc71,stroke:#27ae60,color:#fff
Cloning Attack Resistance:
An attacker who steals the fingerprint file cannot use it on another device because:
- Different TPM: Each TPM has unique internal state
- Different PCR Values: Each device has unique boot measurements
- Hardware sealing: (
tpm2-tools) Native TPMseal.pubandseal.privbound viatpm2_createpolicy. - Software fallback: AES-GCM ciphertext bound with PCR-derived key.
- Hardware sealing: (
- Challenge-Response: Each verification requires fresh TPM signature
Technical Details:
Sealed Data Structure:
┌────────────────────────────────────────┐
│ sealing_type ("tpm2-tools"|"software") │
│ TPM hardware blobs OR AES ciphertext │
│ PCR values and verification data │
└────────────────────────────────────────┘
Unsealing Process (Hardware Sealing):
1. Extract `seal.pub` and `seal.priv` blobs.
2. Load object via `tpm2_load` into TPM context.
3. Unseal via `tpm2_unseal` providing current PCR hashes.
4. Fail if TPM denies unseal (hardware rejection).
Unsealing Process (Software Fallback):
1. Read current PCRs from TPM
2. Derive key = KDF(PCR_0 || PCR_1 || ... || PCR_7)
3. Attempt AES-GCM decryption
4. Fail if PCRs don't match original enrollment state
Challenge-Response Protocol:
Verifier Device
│ │
├──── Challenge (32-byte nonce) ────>│
│ │
│ ┌──────▼──────┐
│ │ TPM │
│ │ Read PCRs │
│ │ Sign HMAC │
│ └──────┬──────┘
│ │
│<─── Response: {signature, PCRs} ────┤
│ │
├─ Verify: │
│ • Timestamp fresh (< 5 min) │
│ • Nonce matches │
│ • Signature = HMAC(nonce||PCRs) │
│ • PCRs match baseline │
│ │
└─> Valid or Invalid │
Device verification is coupled with automatic consequence execution. Policy violations trigger immediate enforcement actions.
Policy Evaluation Flow:
graph TD
A[Device Verification] --> B{Fingerprint Valid?}
B -->|Yes| C[Access Granted]
B -->|No| D[Policy Violation Detected]
D --> E[Automatic Consequences]
E --> F[Revoke Credentials]
E --> G[Lock Vaults]
E --> H[Invalidate Tokens]
E --> I[Seal Audit Event]
E --> J[Force Re-enrollment]
F --> K[Access Denied]
G --> K
H --> K
I --> K
J --> K
style C fill:#2ecc71,stroke:#27ae60,color:#fff
style K fill:#e74c3c,stroke:#c0392b,color:#fff
style E fill:#f39c12,stroke:#e67e22
Example Policies:
- Maximum verification failures
- Required PCR values
- Time-based restrictions
- Geographic limitations
- Custom business logic
Unlike cloud-based attestation systems, TrustCore-TPM operates entirely offline:
Architecture Comparison:
Traditional Cloud Attestation:
Device → Network → Cloud Server → Database → Response
(Latency, availability dependency)
TrustCore-TPM:
Device → Local TPM → Verification Result
(No network, instant, always available)
Benefits:
- Zero network latency
- No cloud infrastructure required
- Works in air-gapped environments
- No data leaves the device
- Reduced attack surface
- Symmetric Encryption: AES-256-GCM (NIST approved)
- Message Authentication: HMAC-SHA256
- Key Derivation: HKDF-SHA256
- Random Generation: TPM RNG (FIPS 140-2 Level 2)
| PCR | Purpose | Use Case |
|---|---|---|
| 0-3 | BIOS/UEFI firmware, boot components | Detect firmware changes |
| 4-5 | Boot loader, boot configuration | Detect boot tampering |
| 7 | Secure Boot state | Detect Secure Boot disable |
| 8-15 | OS and application measurements | Custom application binding |
Root of Trust: TPM 2.0 hardware provides:
- Protected storage for cryptographic keys
- Secure crypto operations
- Platform integrity measurements (PCRs)
- Random number generation
Trust Chain:
graph TB
A[TPM 2.0 Hardware Root]
B[PCR Measurements]
C[Platform State]
D[Sealed Credentials]
E[Audit Logs]
F[Application Trust]
A --> B
B --> C
C --> D
C --> E
D --> F
E --> F
style A fill:#3498db,stroke:#2980b9,color:#fff
style B fill:#95a5a6,stroke:#7f8c8d
style C fill:#95a5a6,stroke:#7f8c8d
style D fill:#2ecc71,stroke:#27ae60
style E fill:#2ecc71,stroke:#27ae60
style F fill:#2ecc71,stroke:#27ae60
- Confidentiality: Fingerprint data encrypted with AES-256-GCM
- Integrity: HMAC-SHA256 signatures prevent tampering
- Authenticity: TPM-signed challenges prove device identity
- Non-repudiation: Audit logs sealed to TPM
- Freshness: Challenge-response prevents replay attacks
Main interface for device fingerprinting operations.
class OfflineVerifier:
def __init__(self, storage_path: str = "~/.tpm_fingerprint/")
def enroll_device(self, device_id: str,
metadata: dict = None) -> dict
def verify_device(self, device_id: str,
strict: bool = True) -> dict
def revoke_device(self, device_id: str) -> bool
def list_devices(self) -> listCore fingerprinting logic.
class FingerprintEngine:
def generate_fingerprint(self, device_id: str) -> dict
def verify_fingerprint(self, device_id: str,
challenge: bytes) -> dictPolicy evaluation and enforcement.
class PolicyEngine:
def evaluate(self, device_id: str,
policy: dict) -> dict
def register_policy(self, policy_id: str,
policy: dict) -> boolAutomatic enforcement actions.
class ConsequenceHandler:
def execute(self, device_id: str,
violations: list) -> dict
def register_consequence(self, name: str,
handler: callable) -> bool# TPM device path (Linux)
export TPM_DEVICE=/dev/tpm0
# Storage location
export TPM_FP_STORAGE=~/.tpm_fingerprint/
# Log level
export TPM_FP_LOG_LEVEL=INFO# config.py
TPM_CONFIG = {
"pcr_selection": [0, 1, 2, 3, 7],
"challenge_timeout": 300, # seconds
"max_failures": 3,
"require_secure_boot": True,
"audit_retention_days": 90
}~/.tpm_fingerprint/
├── fingerprints/
│ ├── device-001.json
│ └── device-002.json
├── policies/
│ └── default.json
├── audit/
│ └── 2024-01-15.log
└── tpm_state.json
{
"device_id": "device-001",
"fingerprint_id": "fp_a1b2c3d4",
"created_at": "2024-01-15T10:30:00Z",
"pcr_values": {
"0": "base64_encoded_value",
"1": "base64_encoded_value"
},
"sealed_data": "base64_encrypted_blob",
"metadata": {
"hostname": "workstation-01",
"os": "Windows 11"
}
}# Enroll device
trustcore-tpm enroll --device-id device-001
# Verify device
trustcore-tpm verify --device-id device-001
# List devices
trustcore-tpm list
# Revoke device
trustcore-tpm revoke --device-id device-001
# Show TPM info
trustcore-tpm tpm-infodef custom_policy(device_id: str, context: dict) -> dict:
# Business logic
if context['time_of_day'] not in ['09:00', '17:00']:
return {
"violated": True,
"reason": "Outside business hours"
}
return {"violated": False}
# Register policy
engine = PolicyEngine()
engine.register_policy("business_hours", custom_policy)def send_alert(device_id: str, violation: dict):
# Send notification
print(f"Alert: {device_id} violated policy")
# Register consequence
handler = ConsequenceHandler()
handler.register_consequence("alert", send_alert)devices = ["device-001", "device-002", "device-003"]
for device_id in devices:
result = verifier.verify_device(device_id)
print(f"{device_id}: {result['valid']}")python -m pytest tests/python -m pytest tests/integration/For development without hardware TPM:
# Install TPM simulator (Linux)
sudo apt-get install swtpm
# Run tests with simulator
export TPM_DEVICE=/dev/tpm_sim
python -m pytestWindows:
# Check TPM status
Get-Tpm
# Enable TPM in BIOS/UEFILinux:
# Check TPM device
ls -l /dev/tpm0
# Install tools
sudo apt-get install tpm2-tools# Add user to tpm group (Linux)
sudo usermod -a -G tss $USER
# Windows: Run as Administrator for TPM accessPCR values change when:
- BIOS/UEFI firmware is updated
- Secure Boot is enabled/disabled
- Boot configuration changes
Solution: Re-enroll device after platform changes.
Tested on Intel Core i7-8650U with TPM 2.0:
| Operation | Time | Notes |
|---|---|---|
| Enrollment | ~150ms | Includes PCR reads and sealing |
| Verification | ~80ms | Challenge-response protocol |
| Policy Evaluation | ~10ms | In-memory computation |
| Audit Log Write | ~5ms | Async write |
- Secure Boot: Enable Secure Boot for PCR 7 binding
- BIOS Password: Protect BIOS/UEFI settings
- Physical Security: Prevent hardware tampering
- Regular Updates: Keep firmware and OS updated
- Audit Logs: Monitor for unusual patterns
- Backup: Secure backup of fingerprint data
- TPM 2.0 required (TPM 1.2 not supported)
- Platform-specific (cannot migrate between devices)
- PCR changes require re-enrollment
- Software TPM emulators provide reduced security
Contributions welcome! Please see CONTRIBUTING.md.
MIT License - see LICENSE file.
- GitHub Issues: https://github.com/Johnsonajibi/Trustcore-TPM/issues
- Documentation: https://github.com/Johnsonajibi/Trustcore-TPM
- Fixed package name to trustcore-tpm
- Updated documentation
- Production release
- Initial release
- TPM 2.0 support
- Complete fingerprinting system
- Policy enforcement
- Audit logging