chore: remove internal dev artifacts

Remove planning docs, phase summaries, old installers, and redundant
documentation. These were development-phase artifacts that don't belong
in the shipped project. install.sh replaces setup.sh and
install-system.sh. API docs can be generated with cargo doc.

Removed:
- .planning/ (37 files of threat modeling and review docs)
- CODING_STANDARDS.md, TESTING.md, CHANGELOG.md
- docs/API.md, docs/BENCHMARKS.md
- scripts/setup.sh, scripts/install-system.sh
- tests/PHASE*_TEST_SUMMARY.md

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-02 15:43:23 +02:00
parent 737743c261
commit 7a4db52140
45 changed files with 0 additions and 9435 deletions

View File

@@ -1,64 +0,0 @@
# Linux Hello
## What This Is
Linux Hello is a Windows Hello-equivalent biometric authentication system for Linux. It provides secure facial authentication using IR cameras and TPM2-backed credential storage, enabling passwordless login across the Linux desktop ecosystem.
## Core Value
Secure, privacy-preserving facial authentication that works seamlessly with Linux login (PAM) and desktop environments (GNOME/KDE).
## Requirements
### Validated
- ✓ Face detection with ONNX models (RetinaFace, MTCNN, BlazeFace) — existing
- ✓ Face embedding extraction (MobileFaceNet, ArcFace, LBPH) — existing
- ✓ Template matching with cosine similarity — existing
- ✓ Anti-spoofing / liveness detection (IR, depth, texture, blink, movement) — existing
- ✓ V4L2 camera support with IR emitter control — existing
- ✓ AES-256-GCM template encryption with PBKDF2 — existing
- ✓ TPM2 integration with software fallback — existing
- ✓ Secure memory with zeroization and mlock — existing
- ✓ Unix socket IPC for PAM/CLI — existing
- ✓ D-Bus service for desktop integration — existing
- ✓ CLI tool (capture, detect, enroll, list, remove, test, config) — existing
- ✓ GNOME Settings app (GTK4/libadwaita) — existing
- ✓ KDE Settings module (Qt6/QML) — existing
- ✓ PAM module for system login — existing
### Active
- [ ] Code audit: Security review of authentication pipeline
- [ ] Code audit: Review of IPC security model
- [ ] Code audit: Memory safety verification
- [ ] Code audit: TPM integration verification
### Out of Scope
- Adding new authentication methods (beyond face) — not core to value
- Cloud sync / backup — privacy concern, out of scope
- Mobile app — not relevant to Linux desktop focus
## Context
The codebase is feature-complete (all 5 phases shipped). The user wants to audit the existing code for security, correctness, and quality before further development. This is a brownfield project with existing validated requirements.
## Constraints
- **Tech Stack**: Rust with ONNX Runtime, C PAM module, GTK4/Qt6 for GUIs
- **Platform**: Linux with V4L2, D-Bus, PAM
- **Security**: Must maintain existing security properties (encryption, secure memory, TPM)
- **Compatibility**: Must work with existing installations
## Key Decisions
| Decision | Rationale | Outcome |
|----------|-----------|---------|
| Face auth over other biometrics | Ubiquity of IR cameras on laptops | — Pending |
| TPM2 with software fallback | Hardware availability varies | — Pending |
| Unix socket + D-Bus IPC | PAM needs socket, desktops need D-Bus | — Pending |
---
*Last updated: 2026-02-14 after codebase mapping*

View File

@@ -1,123 +0,0 @@
# Requirements: Linux Hello Security Audit
**Defined:** 2026-02-14
**Core Value:** Secure, privacy-preserving facial authentication that works seamlessly with Linux login
## v1 Requirements
### Audit Tools
- [ ] **TOOL-01**: Run cargo-audit to find dependency vulnerabilities
- [ ] **TOOL-02**: Run cargo-deny to enforce security policies
- [ ] **TOOL-03**: Run clippy for code quality/security lints
- [ ] **TOOL-04**: Run Miri on unsafe code blocks
- [ ] **TOOL-05**: Set up cargo-fuzz for IPC and template parsing
### Architecture & Threat Modeling
- [ ] **ARCH-01**: Create system DFD with trust boundaries
- [ ] **ARCH-02**: Perform STRIDE threat analysis
- [ ] **ARCH-03**: Enumerate attack surface
- [ ] **ARCH-04**: Map security controls
### Code Security Review
- [ ] **CODE-01**: Inventory all unsafe code blocks
- [ ] **CODE-02**: Review FFI boundaries for security
- [ ] **CODE-03**: Check input validation in all modules
- [ ] **CODE-04**: Verify error handling doesn't leak information
- [ ] **CODE-05**: Review logging for sensitive data exposure
### Cryptographic Implementation
- [ ] **CRYP-01**: Verify AES-256-GCM implementation
- [ ] **CRYP-02**: Verify PBKDF2-HMAC-SHA256 key derivation
- [ ] **CRYP-03**: Check constant-time operations in matching
- [ ] **CRYP-04**: Review TPM integration (if hardware available)
- [ ] **CRYP-05**: Verify secure random number generation
### Biometric Security
- [ ] **BIO-01**: Review anti-spoofing implementation
- [ ] **BIO-02**: Verify IR liveness detection
- [ ] **BIO-03**: Verify depth estimation logic
- [ ] **BIO-04**: Verify texture analysis
- [ ] **BIO-05**: Review blink/movement detection
- [ ] **BIO-06**: Check template storage security
### IPC & Authorization
- [ ] **IPC-01**: Verify SO_PEERCRED validation
- [ ] **IPC-02**: Review authorization boundaries
- [ ] **IPC-03**: Verify rate limiting implementation
- [ ] **IPC-04**: Check message size limits
### Integration Security
- [ ] **INT-01**: Review PAM module security
- [ ] **INT-02**: Review D-Bus interface security
- [ ] **INT-03**: Verify camera input validation
## v2 Requirements
### Advanced Testing
- **ADV-01**: FAR/FRR testing with dataset (requires 245+ subjects)
- **ADV-02**: PAD deepfake/mask testing
- **ADV-03**: TPM hardware security testing
- **ADV-04**: Penetration testing with external testers
## Out of Scope
| Feature | Reason |
|---------|--------|
| ONNX model integrity verification | Requires model signing infrastructure |
| Camera firmware verification | Platform-dependent, out of scope |
| FIDO compliance certification | Enterprise feature, defer to v2 |
## Traceability
| Requirement | Phase | Status |
|-------------|-------|--------|
| TOOL-01 | Phase 2 | Pending |
| TOOL-02 | Phase 2 | Pending |
| TOOL-03 | Phase 2 | Pending |
| TOOL-04 | Phase 2 | Pending |
| TOOL-05 | Phase 5 | Pending |
| ARCH-01 | Phase 1 | Pending |
| ARCH-02 | Phase 1 | Pending |
| ARCH-03 | Phase 1 | Pending |
| ARCH-04 | Phase 1 | Pending |
| CODE-01 | Phase 2 | Pending |
| CODE-02 | Phase 2 | Pending |
| CODE-03 | Phase 2 | Pending |
| CODE-04 | Phase 2 | Pending |
| CODE-05 | Phase 2 | Pending |
| CRYP-01 | Phase 3 | Pending |
| CRYP-02 | Phase 3 | Pending |
| CRYP-03 | Phase 3 | Pending |
| CRYP-04 | Phase 3 | Pending |
| CRYP-05 | Phase 3 | Pending |
| BIO-01 | Phase 4 | Pending |
| BIO-02 | Phase 4 | Pending |
| BIO-03 | Phase 4 | Pending |
| BIO-04 | Phase 4 | Pending |
| BIO-05 | Phase 4 | Pending |
| BIO-06 | Phase 4 | Pending |
| IPC-01 | Phase 2 | Pending |
| IPC-02 | Phase 2 | Pending |
| IPC-03 | Phase 2 | Pending |
| IPC-04 | Phase 2 | Pending |
| INT-01 | Phase 5 | Pending |
| INT-02 | Phase 5 | Pending |
| INT-03 | Phase 5 | Pending |
**Coverage:**
- v1 requirements: 32 total
- Mapped to phases: 32
- Unmapped: 0 ✓
---
*Requirements defined: 2026-02-14*
*Last updated: 2026-02-14 after research synthesis*

View File

@@ -1,120 +0,0 @@
# Roadmap: Linux Hello Security Audit
## Overview
This roadmap orchestrates a comprehensive security audit of Linux Hello, a Rust-based biometric authentication system. The audit follows a 5-phase approach: Architecture & Threat Modeling → Rust-Specific Code Review → Cryptographic Implementation → Biometric-Specific Security → Integration & Penetration Testing. Each phase builds on findings from previous phases, ensuring foundational issues inform detailed component analysis.
## Phases
- [x] **Phase 1: Architecture & Threat Modeling** - Establish security context and identify attack surface
- [x] **Phase 2: Rust-Specific Code Security Review** - Identify Rust vulnerabilities and unsafe code issues
- [ ] **Phase 3: Cryptographic Implementation Audit** - Verify cryptographic implementations follow best practices
- [ ] **Phase 4: Biometric-Specific Security Audit** - Address unique biometric authentication concerns
- [ ] **Phase 5: Integration & Penetration Testing** - Validate security in realistic attack scenarios
## Phase Details
### Phase 1: Architecture & Threat Modeling
**Goal**: Establish security context and identify attack surface before code review
**Depends on**: Nothing (first phase)
**Requirements**: ARCH-01, ARCH-02, ARCH-03, ARCH-04
**Success Criteria** (what must be TRUE):
1. System DFD with trust boundaries exists and documents all data flows
2. STRIDE threat analysis identifies threats for each system component
3. Attack surface enumeration lists all exposed interfaces and entry points
4. Security control mapping documents how each threat is mitigated
**Plans**: 2 plans in 2 waves
Plans:
- [ ] 01-01-PLAN.md — DFD with trust boundaries + Attack surface enumeration
- [ ] 01-02-PLAN.md — STRIDE threat analysis + Security control mapping
---
### Phase 2: Rust-Specific Code Security Review
**Goal**: Identify Rust-specific vulnerabilities, unsafe code issues, and run security tooling
**Depends on**: Phase 1
**Requirements**: TOOL-01, TOOL-02, TOOL-03, TOOL-04, CODE-01, CODE-02, CODE-03, CODE-04, CODE-05, IPC-01, IPC-02, IPC-03, IPC-04
**Success Criteria** (what must be TRUE):
1. cargo-audit reports no high/critical vulnerabilities in dependencies
2. cargo-deny passes all security policy checks (licenses, duplicates, sources)
3. clippy reports no security-related warnings (with appropriate allowlist)
4. Miri analysis completes on all unsafe blocks without undefined behavior
5. Unsafe code inventory documents all unsafe blocks with justification
6. FFI boundary review identifies any potential memory safety issues
7. Input validation exists in all modules that process external data
8. Error handling does not leak sensitive information in error messages
9. Logging does not expose passwords, templates, or biometric data
10. SO_PEERCRED validation is properly implemented in IPC layer
11. Authorization boundaries are enforced for all IPC operations
12. Rate limiting prevents brute-force attacks (verified via test)
13. Message size limits prevent buffer overflow attacks
**Plans**: 3 plans in 1 wave
Plans:
- [ ] 02-01-PLAN.md — Security tooling scan (cargo-audit, cargo-deny, clippy, Miri)
- [ ] 02-02-PLAN.md — Manual code review (unsafe inventory, FFI, input validation, error handling, logging)
- [ ] 02-03-PLAN.md — IPC security verification (SO_PEERCRED, authorization, rate limiting, message limits)
---
### Phase 3: Cryptographic Implementation Audit
**Goal**: Verify cryptographic implementations follow best practices
**Depends on**: Phase 2
**Requirements**: CRYP-01, CRYP-02, CRYP-03, CRYP-04, CRYP-05
**Success Criteria** (what must be TRUE):
1. AES-256-GCM implementation uses correct key size and nonces
2. PBKDF2-HMAC-SHA256 uses 600k iterations as specified
3. Template matching uses constant-time comparison (subtle crate)
4. TPM integration properly handles key binding (or graceful fallback)
5. Secure random number generation uses OS CSPRNG
**Plans**: TBD
---
### Phase 4: Biometric-Specific Security Audit
**Goal**: Address unique biometric authentication concerns
**Depends on**: Phase 3
**Requirements**: BIO-01, BIO-02, BIO-03, BIO-04, BIO-05, BIO-06
**Success Criteria** (what must be TRUE):
1. Anti-spoofing implementation includes multiple detection signals
2. IR liveness detection rejects photo-based presentation attacks
3. Depth estimation logic properly validates 3D structure
4. Texture analysis detects printed photo artifacts
5. Blink/movement detection prevents replay attacks
6. Template storage uses encryption with proper key management
**Plans**: TBD
---
### Phase 5: Integration & Penetration Testing
**Goal**: Validate security in realistic attack scenarios
**Depends on**: Phase 4
**Requirements**: TOOL-05, INT-01, INT-02, INT-03
**Success Criteria** (what must be TRUE):
1. cargo-fuzz configured for IPC message parsing (no crashes)
2. cargo-fuzz configured for template storage (no crashes)
3. PAM module properly validates session and fails securely
4. D-Bus interface properly authorizes method calls
5. Camera input validation prevents frame injection attacks
**Plans**: TBD
## Progress
| Phase | Plans | Status | Completed |
|-------|-------|--------|-----------|
| 1. Architecture & Threat Modeling | 2 plans in 2 waves | ✓ Complete | 100% |
| 2. Rust-Specific Code Security Review | 3 plans in 1 wave | ✓ Complete | 100% |
| 3. Cryptographic Implementation Audit | TBD | Not started | - |
| 4. Biometric-Specific Security Audit | TBD | Not started | - |
| 5. Integration & Penetration Testing | TBD | Not started | - |
---
*Roadmap created: 2026-02-14*
*Based on research: .planning/research/SUMMARY.md*

View File

@@ -1,36 +0,0 @@
# Project State
## Project Reference
See: .planning/PROJECT.md (updated 2026-02-14)
**Core value:** Secure, privacy-preserving facial authentication that works seamlessly with Linux login (PAM) and desktop environments (GNOME/KDE).
**Current focus:** Phase 2 - Rust Code Security Review
## Decisions Made
- Remediated bytes crate vulnerability RUSTSEC-2026-0007 by updating to v1.11.1 via workspace.dependencies override
- Created cargo-deny configuration with permissive license policy allowing MIT, Apache-2.0, BSD-2/3-Clause, ISC, Zlib, Unlicense, CC0-1.0, Unicode-3.0, GPL-3.0-only
## Current Position
Phase: 2 of 5 (Rust Code Security Review)
Plan: 02-04 (Phase 2 Gap Fixes)
Status: Completed
Last activity: 2026-02-14 — Fixed Phase 2 verification gaps
Progress: [████░░░░░] 30% (6/20 plans)
**Recent Trend:**
- 01-01: 3 min, 2 tasks, 2 files
- 01-02: 3 min, 2 tasks, 2 files
- 02-01: 40 min, 4 tasks, 11 files
- 02-02: 5 min, 5 tasks, 5 files
- 02-03: 1 min, 4 tasks, 1 file
- 02-04: 2 min, 4 tasks, 4 files (Gap fixes: bytes vulnerability, cargo-deny)
## Session Continuity
Last session: 2026-02-14
Stopped at: Completed Phase 2 gap fixes (bytes vulnerability remediation, cargo-deny config)
Resume file: None

View File

@@ -1,12 +0,0 @@
{
"mode": "yolo",
"depth": "standard",
"parallelization": true,
"commit_docs": true,
"model_profile": "balanced",
"workflow": {
"research": true,
"plan_check": true,
"verifier": true
}
}

View File

@@ -1,135 +0,0 @@
---
phase: 01-architecture-threat-modeling
plan: 01
type: execute
wave: 1
depends_on: []
files_modified:
- .planning/phases/01-architecture-threat-modeling/dfd.md
- .planning/phases/01-architecture-threat-modeling/attack-surface.md
autonomous: true
must_haves:
truths:
- "System DFD with trust boundaries exists and documents all data flows"
- "Attack surface enumeration lists all exposed interfaces and entry points"
artifacts:
- path: ".planning/phases/01-architecture-threat-modeling/dfd.md"
provides: "System DFD with trust boundaries per ARCH-01"
min_lines: 50
- path: ".planning/phases/01-architecture-threat-modeling/attack-surface.md"
provides: "Attack surface enumeration per ARCH-03"
min_lines: 30
key_links:
- from: "dfd.md"
to: "attack-surface.md"
via: "DFD identifies entry points used in attack surface enumeration"
pattern: "entry points.*attack surface"
---
<objective>
Create System Data Flow Diagram (DFD) with trust boundaries and enumerate attack surface.
</objective>
<execution_context>
@/home/eliott/.config/opencode/get-shit-done/workflows/execute-plan.md
@/home/eliott/.config/opencode/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/ROADMAP.md
@.planning/phases/01-architecture-threat-modeling/01-RESEARCH.md
# Reference Linux Hello architecture from CLAUDE.md
# DFD should cover: Unix Socket IPC, D-Bus, V4L2 camera, TPM, template storage
</context>
<tasks>
<task type="auto">
<name>Task 1: Create System DFD with Trust Boundaries</name>
<files>.planning/phases/01-architecture-threat-modeling/dfd.md</files>
<action>
Create comprehensive Data Flow Diagram document in Markdown with:
1. **External Entities** (all entry points):
- User (face)
- PAM Module (pam_linux_hello.so)
- CLI Client (linux-hello binary)
- GNOME Settings App
- KDE Settings
2. **Processes - linux-h**:
ello-daemon (with internal modules: camera, detection, matching, anti-spoofing, secure memory/IPC)
3. **Data Stores**:
- Template Storage (~/.local/share/linux-hello/)
- TPM Key Storage
- Config Files (/etc/linux-hello/)
4. **Trust Boundaries** (5 boundaries from research):
- TB1: Unix Socket IPC (/run/linux-hello/)
- TB2: Encrypted Storage / TPM Interface
- TB3: Hardware Interfaces (V4L2, TPM2)
- TB4: D-Bus (org.linuxhello)
- TB5: System Integration (systemd, PAM)
5. **Data Flows**: Document all flows between entities across boundaries
Use OWASP Threat Dragon concepts. Include ASCII diagrams for clarity.
Reference: 01-RESEARCH.md section "Architecture Patterns" for DFD structure.
</action>
<verify>
File exists with >50 lines, includes all 5 trust boundaries, covers all external entities and data stores</verify>
<done>DFD document created with trust boundaries documented for TB1-TB5</done>
</task>
<task type="auto">
<name>Task 2: Enumerate Attack Surface</name>
<files>.planning/phases/01-architecture-threat-modeling/attack-surface.md</files>
<action>
Create attack surface enumeration document covering:
1. **IPC Interfaces**:
- Unix Socket (/run/linux-hello/auth.sock): untrusted, SO_PEERCRED, 0o600, rate limit 10/sec
- D-Bus (org.linuxhello): untrusted, D-Bus policy validation
2. **Storage Interfaces**:
- Template files (~/.local/share/linux-hello/): trusted but encrypted
- TPM key storage: trusted via hardware
- Config files (/etc/linux-hello/): admin-only
3. **Hardware Interfaces**:
- V4L2 camera device: untrusted input
- TPM2 device: trusted hardware
4. **Configuration Vectors**:
- Environment variables: untrusted
- Command-line arguments: untrusted
- Config files: admin-only
5. **Biometric-Specific Attack Surface**:
- ONNX model files: potential tampering vector
- Camera frame input: injection risk
- Template replay: extraction risk
Use OWASP Attack Surface Analysis methodology. Include risk ratings.
</action>
<verify>
File exists with >30 lines, covers all IPC/storage/hardware/configuration entry points</verify>
<done>Attack surface document created with all interfaces enumerated and risk-rated</done>
</task>
</tasks>
<verification>
- DFD document contains all 5 trust boundaries
- Attack surface covers all entry points from DFD
</verification>
<success_criteria>
DFD and attack surface enumeration complete and ready for STRIDE analysis</success_criteria>
<output>
After completion, create `.planning/phases/01-architecture-threat-modeling/01-01-SUMMARY.md`
</output>

View File

@@ -1,83 +0,0 @@
---
phase: 01-architecture-threat-modeling
plan: 01
subsystem: security
tags: [threat-modeling, dfd, attack-surface, owasp]
# Dependency graph
requires: []
provides:
- "System DFD with 5 trust boundaries"
- "Attack surface enumeration with risk ratings"
affects: [01-02-STRIDE-analysis]
# Tech tracking
tech-stack:
added: []
patterns: [OWASP Threat Dragon methodology, OWASP Attack Surface Analysis]
key-files:
created:
- ".planning/phases/01-architecture-threat-modeling/dfd.md"
- ".planning/phases/01-architecture-threat-modeling/attack-surface.md"
key-decisions:
- "Used 5 trust boundaries: Unix Socket IPC, Encrypted Storage/TPM, Hardware Interfaces, D-Bus, System Integration"
- "Risk-rated attack surface: HIGH (socket, camera, ONNX), MEDIUM (most others), LOW (hardware TPM)"
patterns-established:
- "DFD with trust boundaries following OWASP methodology"
- "Attack surface enumeration with existing controls and risk ratings"
# Metrics
duration: 3 min
completed: 2026-02-14
---
# Phase 1 Plan 1: Architecture & Threat Modeling Summary
**System DFD with 5 trust boundaries and comprehensive attack surface enumeration with risk ratings**
## Performance
- **Duration:** 3 min
- **Started:** 2026-02-14T09:08:45Z
- **Completed:** 2026-02-14T09:11:17Z
- **Tasks:** 2
- **Files modified:** 2
## Accomplishments
- Created System DFD documenting all external entities, processes, data stores, and 5 trust boundaries
- Enumerated attack surface across IPC, storage, hardware, configuration, and biometric-specific vectors
- Risk-rated each entry point for STRIDE analysis prioritization
## Task Commits
Each task was committed atomically:
1. **Task 1: Create System DFD with Trust Boundaries** - `96b31ad` (feat)
2. **Task 2: Enumerate Attack Surface** - `444c430` (feat)
## Files Created/Modified
- `.planning/phases/01-architecture-threat-modeling/dfd.md` - System DFD with trust boundaries
- `.planning/phases/01-architecture-threat-modeling/attack-surface.md` - Attack surface enumeration
## Decisions Made
- Used 5 trust boundaries: Unix Socket IPC, Encrypted Storage/TPM, Hardware Interfaces, D-Bus, System Integration
- Risk-rated attack surface: HIGH (socket, camera, ONNX), MEDIUM (most others), LOW (hardware TPM)
## Deviations from Plan
None - plan executed exactly as written.
## Issues Encountered
None
## Next Phase Readiness
- DFD and attack surface enumeration complete
- Ready for 01-02: STRIDE threat analysis + Security control mapping
---
*Phase: 01-architecture-threat-modeling*
*Completed: 2026-02-14*

View File

@@ -1,158 +0,0 @@
---
phase: 01-architecture-threat-modeling
plan: 02
type: execute
wave: 2
depends_on:
- 01-01
files_modified:
- .planning/phases/01-architecture-threat-modeling/stride-threats.md
- .planning/phases/01-architecture-threat-modeling/security-controls.md
autonomous: true
must_haves:
truths:
- "STRIDE threat analysis identifies threats for each system component"
- "Security control mapping documents how each threat is mitigated"
artifacts:
- path: ".planning/phases/01-architecture-threat-modeling/stride-threats.md"
provides: "STRIDE threat analysis per ARCH-02"
min_lines: 80
- path: ".planning/phases/01-architecture-threat-modeling/security-controls.md"
provides: "Security control mapping per ARCH-04"
min_lines: 40
key_links:
- from: "stride-threats.md"
to: "security-controls.md"
via: "Each STRIDE threat should have corresponding security control"
pattern: "mitigation.*control"
---
<objective>
Perform STRIDE threat analysis and map security controls to mitigate identified threats.
</objective>
<execution_context>
@/home/eliott/.config/opencode/get-shit-done/workflows/execute-plan.md
@/home/eliott/.config/opencode/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/phases/01-architecture-threat-modeling/01-01-PLAN.md
@.planning/phases/01-architecture-threat-modeling/01-RESEARCH.md
@.planning/phases/01-architecture-threat-modeling/dfd.md
@.planning/phases/01-architecture-threat-modeling/attack-surface.md
</context>
<tasks>
<task type="auto">
<name>Task 1: Perform STRIDE Threat Analysis</name>
<files>.planning/phases/01-architecture-threat-modeling/stride-threats.md</files>
<action>
Create STRIDE threat analysis document analyzing all DFD components. Use the following structure:
**STRIDE Categories Applied to Linux Hello:**
1. **Spoofing Threats**:
- Fake camera device injection
- UID spoofing via socket manipulation
- TPM hardware emulation
- D-Bus service impersonation
2. **Tampering Threats**:
- Modify templates in encrypted storage
- Inject frames into camera stream
- Tamper with ONNX model files
- Modify config files in /etc/
3. **Repudiation Threats**:
- Delete authentication logs
- Modify audit records
- No logging of failed attempts
4. **Information Disclosure Threats**:
- Expose templates via filesystem
- Leak embedding data in error messages
- Timing attack on template matching
- Config file permission escalation
5. **Denial of Service Threats**:
- Exhaust rate limiting (10/sec)
- Camera resource exhaustion
- Fork bomb on daemon
- TPM command flooding
6. **Elevation of Privilege Threats**:
- Root to user privilege escalation
- Bypass PAM authorization
- Template replacement attack
- D-Bus method injection
For each threat, include:
- Affected component (from DFD)
- Attack vector
- Risk rating (likelihood × impact)
Reference: 01-RESEARCH.md section "Code Examples" for STRIDE categories.
</action>
<verify>
File exists with >80 lines, covers all 6 STRIDE categories with component-specific threats</verify>
<done>STRIDE threat analysis complete with threats enumerated for each DFD component</done>
</task>
<task type="auto">
<name>Task 2: Map Security Controls</name>
<files>.planning/phases/01-architecture-threat-modeling/security-controls.md</files>
<action>
Create security control mapping document that maps existing controls to identified threats:
**IPC Security Controls**:
- SO_PEERCRED credential validation
- Unix socket permissions (0o600)
- Rate limiting (10 requests/sec)
- Message size limits (64KB max)
**Cryptographic Controls**:
- AES-256-GCM for template encryption
- PBKDF2-HMAC-SHA256 (600k iterations)
- TPM key binding (or software fallback)
- Constant-time comparison (subtle crate)
**Memory Security Controls**:
- mlock for sensitive data
- zeroize for automatic wiping
- SecureBytes and SecureEmbedding types
**Authorization Controls**:
- D-Bus policy enforcement
- PAM session validation
- Peer credential verification
For each control, document:
- What it protects
- Threats mitigated
- Implementation location (code reference)
- Effectiveness rating
Also identify gaps where controls are missing or insufficient.
</action>
<verify>
File exists with >40 lines, maps all major control categories to threats</verify>
<done>Security control mapping complete with all identified threats having mitigations</done>
</task>
</tasks>
<verification>
- STRIDE analysis covers all components from DFD
- Security controls map to threats from STRIDE analysis
- Gap analysis identifies missing mitigations
</verification>
<success_criteria>
Phase 1 complete: DFD, attack surface, STRIDE threats, and security controls all documented</success_criteria>
<output>
After completion, create `.planning/phases/01-architecture-threat-modeling/01-02-SUMMARY.md`
</output>

View File

@@ -1,102 +0,0 @@
---
phase: 01-architecture-threat-modeling
plan: 02
subsystem: security
tags: [stride, threat-modeling, security-controls, pad, encryption]
# Dependency graph
requires:
- phase: 01-architecture-threat-modeling
provides: DFD + Attack Surface Analysis
provides:
- STRIDE threat analysis document
- Security control mapping with gap analysis
affects: [future security implementation phases, code review focus areas]
# Tech tracking
tech-stack:
added: [STRIDE methodology, threat modeling documentation]
patterns: [threat-control mapping, risk rating matrix]
key-files:
created: [.planning/phases/01-architecture-threat-modeling/stride-threats.md, .planning/phases/01-architecture-threat-modeling/security-controls.md]
modified: []
key-decisions:
- "Risk ratings use likelihood × impact (5×5 = 25 scale)"
- "TPM hardware preferred over software fallback"
- "Constant-time comparison via subtle crate for timing attack prevention"
patterns-established:
- "STRIDE categories applied to biometric authentication systems"
- "Security control effectiveness ratings (HIGH/MEDIUM/LOW)"
- "Gap analysis identifies missing mitigations for future work"
# Metrics
duration: 3 min
completed: 2026-02-14
---
# Phase 1 Plan 2: STRIDE Threats + Security Controls Summary
**STRIDE threat analysis with security control mapping - comprehensive threat model for biometric authentication system**
## Performance
- **Duration:** 3 min
- **Started:** 2026-02-14T09:13:50Z
- **Completed:** 2026-02-14T09:16:44Z
- **Tasks:** 2
- **Files modified:** 2
## Accomplishments
- Created comprehensive STRIDE threat analysis covering all 6 categories (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege)
- Mapped security controls to identified threats with implementation locations and effectiveness ratings
- Identified gaps requiring future enhancement (immutable audit logging, model integrity verification)
## Task Commits
Each task was committed atomically:
1. **Task 1: Perform STRIDE Threat Analysis** - `0f018ba` (docs)
2. **Task 2: Map Security Controls** - `8cbb5ad` (docs)
**Plan metadata:** `34fc509` (docs: complete plan)
## Files Created/Modified
- `.planning/phases/01-architecture-threat-modeling/stride-threats.md` - STRIDE threat analysis (433 lines)
- `.planning/phases/01-architecture-threat-modeling/security-controls.md` - Security control mapping (384 lines)
## Decisions Made
- Used likelihood × impact (5×5 = 25) risk rating scale for consistency
- Prioritized HIGH-risk threats for immediate mitigation focus
- TPM hardware preferred over software fallback for key protection
- Constant-time comparison via `subtle` crate prevents timing attacks
## Deviations from Plan
None - plan executed exactly as written.
## Issues Encountered
None - plan executed without issues.
## User Setup Required
None - no external service configuration required.
## Next Phase Readiness
Phase 1 complete: DFD, attack surface, STRIDE threats, and security controls all documented. Ready for Phase 2 implementation planning based on threat model.
---
## Self-Check: PASSED
- All files created and verified
- All commits present (0f018ba, 8cbb5ad, 34fc509)
- Plan criteria met: STRIDE analysis (>80 lines) ✓, Security controls (>40 lines) ✓
---
*Phase: 01-architecture-threat-modeling*
*Completed: 2026-02-14*

View File

@@ -1,332 +0,0 @@
# Phase 1: Architecture & Threat Modeling - Research
**Researched:** 2026-02-14
**Domain:** Security Threat Modeling for Rust Biometric Authentication
**Confidence:** HIGH
## Summary
This phase establishes the security context for Linux Hello—a Rust biometric authentication system with face detection, TPM integration, secure memory handling, and encrypted template storage. The phase covers four key deliverables: system Data Flow Diagram (DFD) with trust boundaries, STRIDE threat analysis, attack surface enumeration, and security control mapping.
The recommended approach uses OWASP Threat Dragon or draw.io for DFD creation, STRIDE methodology for threat identification, and systematic attack surface enumeration across all IPC channels, storage, and hardware interfaces.
**Primary recommendation:** Use OWASP Threat Dragon for DFD creation (free, integrates STRIDE, versionable), enumerate attack surface across Unix socket IPC, D-Bus, camera V4L2, and template storage, then map existing security controls from the codebase.
---
## Standard Stack
### Threat Modeling Tools
| Tool | Version | Purpose | Why Standard |
|------|---------|---------|--------------|
| OWASP Threat Dragon | Latest | DFD creation with STRIDE integration | Free, open-source, OWASP project, integrates threat generation |
| draw.io | Latest | Generic diagramming | Familiar, available offline, threat modeling libraries available |
| Microsoft Threat Modeling Tool | 2016+ | DFD creation | Industry standard, but Windows-only, no longer updated |
### Supporting Tools
| Tool | Purpose | When to Use |
|------|---------|-------------|
| OWASP pytm | Code-based threat modeling | Prefer infrastructure-as-code, integrate with CI/CD |
| Threat Composer (AWS) | Cloud-native threat modeling | If adding cloud deployment |
| MITRE ATT&CK | Attack technique mapping | For detailed penetration testing preparation |
**Note:** For Linux Hello, OWASP Threat Dragon is recommended as it provides:
- Visual DFD editor with trust boundary support
- Automatic STRIDE threat generation
- Export to JSON/Markdown for documentation
- Free and open source
---
## Architecture Patterns
### Recommended DFD Structure for Linux Hello
```
┌─────────────────────────────────────────────────────────────────────┐
│ EXTERNAL ENTITIES │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ User │ │ PAM │ │ CLI │ │ GNOME │ │ KDE │ │
│ │ (Face) │ │ Module │ │ Client │ │Settings │ │Settings │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │
└───────┼────────────┼────────────┼────────────┼────────────┼────────┘
│ │ │ │ │
│ ┌─────────▼────────────▼────────────▼────────────▼────┐ │
│ │ TRUST BOUNDARY 1 │ │
│ │ Unix Socket IPC (/run/linux-hello/) │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼──────────────────────────────┐ │
│ │ PROCESSES │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ linux-hello-daemon │ │ │
│ │ │ ┌─────────┐ ┌─────────┐ ┌───────────────┐ │ │ │
│ │ │ │ Camera │ │Detection│ │ Matching │ │ │ │
│ │ │ │ V4L2 │ │ ONNX/ │ │ Service │ │ │ │
│ │ │ │ │ │Placeholder│ │ │ │ │ │
│ │ │ └────┬────┘ └────┬────┘ └───────┬───────┘ │ │ │
│ │ │ │ │ │ │ │ │
│ │ │ ┌────▼──────────▼──────────────▼────────┐ │ │ │
│ │ │ │ Anti-Spoofing / PAD │ │ │ │
│ │ │ │ (IR, Depth, Texture, Blink, Move) │ │ │ │
│ │ │ └────────────────┬────────────────────────┘ │ │ │
│ │ │ │ │ │ │
│ │ │ ┌────────────────▼────────────────────────┐ │ │ │
│ │ │ │ Secure Memory / IPC │ │ │ │
│ │ │ │ (mlock, zeroize, rate limiting) │ │ │ │
│ │ │ └────────────────┬────────────────────────┘ │ │ │
│ │ └────────────────────┼────────────────────────────┘ │ │
│ └──────────────────────┼───────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼───────────────────────────────┐ │
│ │ TRUST BOUNDARY 2 │ │
│ │ Encrypted Storage / TPM Interface │ │
│ └──────────────────────┬───────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼───────────────────────────────┐ │
│ │ DATA STORES │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌───────────┐ │ │
│ │ │ Template │ │ TPM Key │ │ Config │ │ │
│ │ │ Storage │ │ Storage │ │ Files │ │ │
│ │ │ (AES-256) │ │ (Hardware) │ │ │ │ │
│ │ └──────────────┘ └──────────────┘ └───────────┘ │ │
│ └────────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────────────────▼───────────────────────────────┐ │
│ │ TRUST BOUNDARY 3 │ │
│ │ Hardware Interfaces │ │
│ │ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ V4L2 │ │ TPM2 │ │ │
│ │ │ Camera │ │ (Hardware) │ │ │
│ │ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ D-Bus │ │
│ │ (Settings App Communication) │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ System │ │
│ │ (systemd, PAM, kernel interfaces) │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ External Entities │ │
│ │ (IR Camera, RGB Camera, TPM Chip) │ │
│ └────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘
```
### Trust Boundary Definitions
| Boundary | Location | Trust Level |
|----------|----------|-------------|
| TB1 | Unix Socket IPC | Untrusted clients connect here; daemon validates credentials |
| TB2 | Template Storage | Encrypted at rest; keys in TPM or software-derived |
| TB3 | Hardware Interfaces | V4L2 camera, TPM chip - kernel-mediated |
| TB4 | D-Bus | System bus; settings app communication |
| TB5 | System Integration | systemd service, PAM module execution context |
---
## Don't Hand-Roll
| Problem | Don't Build | Use Instead | Why |
|---------|-------------|-------------|-----|
| Threat modeling methodology | Create custom threat categories | STRIDE (well-documented, widely understood) | Ensures comprehensive coverage |
| DFD creation | Draw manually in image editor | OWASP Threat Dragon or draw.io | Versionable, supports threat generation |
| Attack surface enumeration | Ad-hoc list | OWASP Attack Surface Analysis methodology | Structured, repeatable |
**Key insight:** Threat modeling is a well-established practice with proven methodologies. Don't reinvent—use STRIDE for threat categorization and OWASP frameworks for attack surface analysis.
---
## Common Pitfalls
### Pitfall 1: Incomplete Trust Boundary Definition
**What goes wrong:** DFD shows components but doesn't clearly define where trust transitions occur.
**Why it happens:** Focus on functional data flow rather than security boundaries.
**How to avoid:**
- Mark every entry point from untrusted sources
- Document authentication/authorization at each boundary
- Verify credential flow across boundaries
**Warning signs:** DFD looks like an architecture diagram, not a security model.
### Pitfall 2: Missing Attack Surface Entry Points
**What goes wrong:** Enumerate only obvious interfaces (socket, D-Bus) but miss implicit paths.
**Why it happens:** Ignore filesystem, environment variables, command-line arguments.
**How to avoid:** Use OWASP Attack Surface Checklist:
- [ ] Network interfaces (Unix socket, D-Bus)
- [ ] Filesystem (config files, template storage)
- [ ] IPC mechanisms (signals, environment)
- [ ] Hardware (V4L2, TPM)
- [ ] Inter-process (PAM conversation)
### Pitfall 3: Threat List Without Prioritization
**What goes wrong:** Generate long list of threats but no risk ranking.
**Why it happens:** Treat all threats as equal priority.
**How to avoid:** Use risk scoring (likelihood × impact) and focus on:
- High-impact: Template theft, authentication bypass
- High-likelihood: IPC injection, rate limiting bypass
### Pitfall 4: Ignoring Biometric-Specific Threats
**What goes wrong:** Apply generic authentication threat model, miss PAD/template attacks.
**Why it happens:** Treat biometric like password authentication.
**How to avoid:** Include specific threats:
- Presentation attack (photo, video, mask, deepfake)
- Template extraction/replay
- FAR/FRR exploitation
- PAD bypass techniques
### Pitfall 5: Security Controls Not Mapped
**What goes wrong:** Identify threats but not existing mitigations.
**Why it happens:** Threat modeling disconnected from code review.
**How to avoid:** Document existing controls:
- IPC: SO_PEERCRED, rate limiting (10/sec), message size limits (64KB)
- Crypto: AES-256-GCM, PBKDF2 (600k), TPM binding
- Memory: mlock, zeroize, subtle crate for constant-time
---
## Code Examples
### STRIDE Threat Categories Applied to Linux Hello
```
┌─────────────────────────────────────────────────────────────────┐
│ STRIDE │ Linux Hello Application │
├────────────────┼────────────────────────────────────────────────┤
│ Spoofing │ • Fake camera device injection │
│ │ • UID spoofing via socket manipulation │
│ │ • TPM hardware emulation │
├────────────────┼────────────────────────────────────────────────┤
│ Tampering │ • Modify templates in storage │
│ │ • Inject frames into camera stream │
│ │ • Tamper with ONNX model files │
├────────────────┼────────────────────────────────────────────────┤
│ Repudiation │ • Delete authentication logs │
│ │ • Modify audit records │
│ │ • No logging of failed attempts │
├────────────────┼────────────────────────────────────────────────┤
│ Information │ • Expose templates via filesystem │
│ Disclosure │ • Leak embedding data in error messages │
│ │ • Timing attack on template matching │
├────────────────┼────────────────────────────────────────────────┤
│ Denial of │ • Exhaust rate limiting │
│ Service │ • Camera resource exhaustion │
│ │ • Fork bomb on daemon │
├────────────────┼────────────────────────────────────────────────┤
│ Elevation of │ • Root to user privilege escalation │
│ Privilege │ • Bypass PAM authorization │
│ │ • Template replacement attack │
└─────────────────────────────────────────────────────────────────┘
```
### Attack Surface Enumeration Template
| Category | Entry Point | Trust Level | Existing Controls | Risk Rating |
|----------|-------------|-------------|-------------------|-------------|
| IPC | Unix Socket (/run/linux-hello/auth.sock) | Untrusted | SO_PEERCRED, 0o600, rate limit 10/sec | High |
| IPC | D-Bus (org.linuxhello) | Untrusted | D-Bus policy, caller validation | Medium |
| Storage | Template files (~/.local/share/linux-hello/) | Trusted (encrypted) | AES-256-GCM | Medium |
| Storage | TPM key storage | Trusted (hardware) | TPM auth value | Low |
| Hardware | V4L2 camera | Untrusted | Frame validation, IR check | High |
| Hardware | TPM2 device | Trusted (hardware) | TPM physical security | Low |
| Config | /etc/linux-hello/ | Admin only | File permissions | Low |
| Config | Environment variables | Untrusted | Parsing validation | Medium |
---
## State of the Art
| Old Approach | Current Approach | When Changed | Impact |
|--------------|------------------|--------------|--------|
| Manual threat lists | STRIDE + DFD | 2000s Microsoft | Systematic, repeatable |
| Single threat model | Multiple trust boundaries | 2010s | Better isolation understanding |
| Point-in-time | Continuous/iterative | 2020s | Threat model as living document |
| Generic authentication | Biometric-specific (PAD, FAR/FRR) | FIDO standards 2024+ | Specialized threat categories |
**Deprecated/outdated:**
- Microsoft Threat Modeling Tool 2016: No longer actively maintained
- Pure manual enumeration: Replaced by tool-assisted approaches
---
## Open Questions
1. **How detailed should the DFD be?**
- What we know: Should show all processes, data stores, external entities
- What's unclear: Level of detail for internal module interactions
- Recommendation: Create high-level DFD + focused DFDs for critical paths (IPC, template storage)
2. **Should threat modeling include ONNX model security?**
- What we know: ONNX models loaded at runtime, potential tampering vector
- What's unclear: Whether model integrity verification exists
- Recommendation: Include as attack surface entry point in Phase 1, verify in Phase 4
3. **How to handle TPM vs software fallback in threat model?**
- What we know: Two distinct security levels (hardware-bound vs password-derived)
- What's unclear: Whether threat model should treat them separately
- Recommendation: Document both paths, flag software fallback as reduced security
---
## Sources
### Primary (HIGH confidence)
- **OWASP Threat Modeling Cheat Sheet** - https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html
- **OWASP Attack Surface Analysis Cheat Sheet** - https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html
- **OWASP Threat Dragon** - https://github.com/OWASP/threat-dragon
### Secondary (HIGH confidence)
- **Project Architecture Documentation** - linux-hello-daemon source code analysis
- **IPC Security Implementation** - ipc.rs with SO_PEERCRED, rate limiting
- **Template Storage** - secure_template_store.rs with AES-256-GCM
### Tertiary (MEDIUM confidence)
- **STRIDE Original Paper** - Microsoft threat modeling methodology
- **FIDO Biometrics Requirements v4.1** - Biometric-specific threat categories
---
## Metadata
**Confidence breakdown:**
- Standard stack: HIGH - OWASP methodologies well-documented, tools freely available
- Architecture: HIGH - Based on OWASP frameworks, tailored to Linux Hello components
- Pitfalls: HIGH - Based on real-world threat modeling experience documented in OWASP
**Research date:** 2026-02-14
**Valid until:** 90 days (threat modeling methodology is stable)
---
## Deliverables for Phase 1
| Requirement | Deliverable | Method |
|-------------|-------------|--------|
| ARCH-01 | System DFD with trust boundaries | OWASP Threat Dragon |
| ARCH-02 | STRIDE threat analysis | Per-component threat enumeration |
| ARCH-03 | Attack surface enumeration | OWASP Attack Surface Checklist |
| ARCH-04 | Security control mapping | Code analysis of existing controls |
**Timeline estimate:** 1-2 weeks for comprehensive threat model

View File

@@ -1,278 +0,0 @@
# Attack Surface Enumeration
**Created:** 2026-02-14
**Based on:** ARCH-03, DFD
**Confidence:** HIGH
---
## Overview
This document enumerates all attack surface entry points for Linux Hello, following OWASP Attack Surface Analysis methodology. Each entry point is assessed for trust level, existing controls, and risk rating.
---
## 1. IPC Interfaces
### 1.1 Unix Socket (`/run/linux-hello/auth.sock`)
| Attribute | Value |
|-----------|-------|
| **Type** | Unix domain socket |
| **Trust Level** | Untrusted |
| **Path** | `/run/linux-hello/auth.sock` |
| **Permissions** | `0o600` (owner read/write only) |
**Existing Controls:**
- SO_PEERCRED for UID verification
- Message size limit: 64KB
- Rate limiting: 10 requests/second
- Socket ownership: root:linux-hello
**Risk Rating:** HIGH
**Threats:** Socket injection, UID spoofing, DoS via rate limit exhaustion
### 1.2 D-Bus Interface (`org.linuxhello`)
| Attribute | Value |
|-----------|-------|
| **Type** | System D-Bus |
| **Bus Name** | `org.linuxhello` |
| **Object Path** | `/org/linuxhello` |
| **Trust Level** | Untrusted |
**Existing Controls:**
- D-Bus policy configuration
- Method call argument validation
- No secrets exposed via D-Bus
- Settings-only operations (no auth via D-Bus)
**Risk Rating:** MEDIUM
**Threats:** D-Bus policy bypass, method injection, service abuse
---
## 2. Storage Interfaces
### 2.1 Template Storage (`~/.local/share/linux-hello/`)
| Attribute | Value |
|-----------|-------|
| **Type** | Filesystem directory |
| **Location** | `~/.local/share/linux-hello/` |
| **Trust Level** | Trusted (encrypted at rest) |
| **Contents** | Face templates (AES-256-GCM encrypted) |
**Existing Controls:**
- AES-256-GCM encryption
- PBKDF2-HMAC-SHA256 key derivation (600k iterations)
- File permissions: user read/write only
- Secure memory: mlock + zeroize
**Risk Rating:** MEDIUM
**Threats:** Template extraction, offline decryption (if key compromised), storage tampering
### 2.2 TPM Key Storage
| Attribute | Value |
|-----------|-------|
| **Type** | Hardware security module |
| **Device** | TPM 2.0 |
| **Trust Level** | Trusted (hardware) |
| **Fallback** | Software (password-derived) |
**Existing Controls:**
- TPM hardware security
- TPM auth value required
- Software fallback available (reduced security)
**Risk Rating:** LOW (hardware) / MEDIUM (software fallback)
**Threats:** TPM hardware attack, software fallback key derivation weakness
### 2.3 Configuration Files (`/etc/linux-hello/`)
| Attribute | Value |
|-----------|-------|
| **Type** | System configuration |
| **Location** | `/etc/linux-hello/` |
| **Trust Level** | Admin-only |
| **Permissions** | `0o600` (root only) |
**Existing Controls:**
- Root-only permissions
- YAML parsing validation
- No secrets stored in config
**Risk Rating:** LOW
**Threats:** Config injection, privilege escalation (if writable)
---
## 3. Hardware Interfaces
### 3.1 V4L2 Camera Device
| Attribute | Value |
|-----------|-------|
| **Type** | Video4Linux2 device |
| **Devices** | `/dev/video0` (RGB), `/dev/video1` (IR) |
| **Trust Level** | Untrusted |
| **Access** | Video group |
**Existing Controls:**
- V4L2 frame validation
- IR liveness detection
- Anti-spoofing (PAD)
- Frame format validation
**Risk Rating:** HIGH
**Threats:** Camera injection, frame replay, IR spoofing, camera device manipulation
### 3.2 TPM2 Device
| Attribute | Value |
|-----------|-------|
| **Type** | Trusted Platform Module |
| **Device** | `/dev/tpm0` or `/dev/tpmrm0` |
| **Trust Level** | Trusted (hardware) |
| **Access** | TSS group |
**Existing Controls:**
- Hardware physical security
- TPM command validation
- Auth value protection
**Risk Rating:** LOW
**Threats:** Hardware tampering (requires physical access), TPM command injection
---
## 4. Configuration Vectors
### 4.1 Environment Variables
| Attribute | Value |
|-----------|-------|
| **Type** | Process environment |
| **Trust Level** | Untrusted |
| **Inheritance** | Inherited from parent process |
**Risk:** MEDIUM
**Threats:** Environment injection, LD_PRELOAD attacks, secret exposure
### 4.2 Command-Line Arguments
| Attribute | Value |
|-----------|-------|
| **Type** | Process arguments |
| **Trust Level** | Untrusted |
| **Sources** | PAM, CLI, systemd |
**Risk:** MEDIUM
**Threats:** Argument injection, path traversal via --config
### 4.3 Configuration Files
| Attribute | Value |
|-----------|-------|
| **Type** | YAML files |
| **Location** | `/etc/linux-hello/` |
| **Trust Level** | Admin-only |
**Risk:** LOW
**Threats:** YAML deserialization, config path traversal
---
## 5. Biometric-Specific Attack Surface
### 5.1 ONNX Model Files
| Attribute | Value |
|-----------|-------|
| **Type** | ML model files |
| **Location** | `models/` directory |
| **Trust Level** | Untrusted (loaded at runtime) |
**Existing Controls:**
- File permissions (if properly set)
- Model validation (runtime)
**Risk Rating:** HIGH
**Threats:** Model tampering, adversarial examples, model injection, memory corruption via malformed ONNX
### 5.2 Camera Frame Input
| Attribute | Value |
|-----------|-------|
| **Type** | Image/video stream |
| **Source** | V4L2 device |
| **Trust Level** | Untrusted |
**Existing Controls:**
- Frame format validation
- Resolution limits
- IR signature check
- Anti-spoofing (multiple signals)
**Risk Rating:** HIGH
**Threats:** Photo attack, video replay, deepfake, 3D mask, frame injection
### 5.3 Template Replay
| Attribute | Value |
|-----------|-------|
| **Type** | Biometric template |
| **Storage** | Encrypted filesystem |
| **Transmission** | Internal only |
**Existing Controls:**
- AES-256-GCM encryption at rest
- No plaintext template exposure
- Secure memory handling
**Risk Rating:** MEDIUM
**Threats:** Template extraction, template replay, template correlation
---
## Attack Surface Summary Table
| Category | Entry Point | Trust Level | Existing Controls | Risk Rating |
|----------|-------------|-------------|-------------------|-------------|
| IPC | Unix Socket (/run/linux-hello/auth.sock) | Untrusted | SO_PEERCRED, 0o600, rate limit 10/sec | HIGH |
| IPC | D-Bus (org.linuxhello) | Untrusted | D-Bus policy, caller validation | MEDIUM |
| Storage | Template files (~/.local/share/linux-hello/) | Trusted (encrypted) | AES-256-GCM, PBKDF2 | MEDIUM |
| Storage | TPM key storage | Trusted (hardware) | TPM auth value | LOW |
| Storage | Config files (/etc/linux-hello/) | Admin only | File permissions | LOW |
| Hardware | V4L2 camera | Untrusted | Frame validation, IR check, PAD | HIGH |
| Hardware | TPM2 device | Trusted (hardware) | TPM physical security | LOW |
| Config | Environment variables | Untrusted | Parsing validation | MEDIUM |
| Config | Command-line arguments | Untrusted | Argument parsing | MEDIUM |
| Biometric | ONNX model files | Untrusted | File permissions | HIGH |
| Biometric | Camera frame input | Untrusted | PAD, IR, depth checks | HIGH |
| Biometric | Template storage | Trusted | AES-256-GCM encryption | MEDIUM |
---
## High-Priority Attack Surface
Based on risk ratings, the following entry points require priority attention:
1. **V4L2 Camera Input (HIGH)** - Primary attack vector for presentation attacks
2. **Unix Socket IPC (HIGH)** - Untrusted client interface, potential injection
3. **ONNX Model Files (HIGH)** - Model tampering and adversarial attacks
---
## References
- DFD: `.planning/phases/01-architecture-threat-modeling/dfd.md`
- IPC Implementation: `linux-hello-daemon/src/ipc.rs`
- Anti-Spoofing: `linux-hello-daemon/src/anti_spoofing.rs`
- Template Storage: `linux-hello-daemon/src/secure_template_store.rs`
- ONNX Integration: `linux-hello-daemon/src/onnx/`
---
*This attack surface enumeration supports ARCH-03 and enables STRIDE threat analysis in subsequent plans.*

View File

@@ -1,314 +0,0 @@
# System Data Flow Diagram (DFD) with Trust Boundaries
**Created:** 2026-02-14
**Based on:** ARCH-01, 01-RESEARCH.md
**Confidence:** HIGH
---
## Overview
This document provides a comprehensive Data Flow Diagram (DFD) for Linux Hello, a Rust-based biometric authentication system. The DFD identifies all external entities, processes, data stores, and trust boundaries to establish the security context for threat modeling.
---
## External Entities
### Entry Points to the System
| Entity | Description | Trust Level | Connection Method |
|--------|-------------|-------------|-------------------|
| **User (Face)** | End-user's face for biometric authentication | Untrusted | Physical camera capture |
| **PAM Module** | pam_linux_hello.so for system login | Untrusted | Unix socket IPC |
| **CLI Client** | linux-hello command-line tool | Untrusted | Unix socket IPC |
| **GNOME Settings** | GNOME Control Center integration | Untrusted | D-Bus (org.linuxhello) |
| **KDE Settings** | KDE System Settings module | Untrusted | D-Bus (org.linuxhello) |
---
## Processes
### Core Process: linux-hello-daemon
The central authentication service comprising the following internal modules:
```
┌─────────────────────────────────────────────────────────────────┐
│ linux-hello-daemon │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Core Service │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ Camera │ │ Detection │ │ Matching │ │ │
│ │ │ Module │──│ Module │──│ Service │ │ │
│ │ │ (V4L2) │ │ (ONNX/Hybrid)│ │ (Cosine Sim) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │
│ │ │ │ │ │ │
│ │ └────────────────┼──────────────────┘ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ Anti-Spoofing / PAD │ │ │
│ │ │ (IR Liveness, Depth, Texture, Blink, Move) │ │ │
│ │ └─────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ Secure Memory / IPC Handler │ │ │
│ │ │ (mlock, zeroize, SO_PEERCRED, rate limit) │ │ │
│ │ └─────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ IPC Server (Unix Socket) │
└─────────────────────────────────────────────────────────────────┘
```
---
## Data Stores
### 1. Template Storage
- **Location:** `~/.local/share/linux-hello/`
- **Contents:** Encrypted face templates (AES-256-GCM)
- **Trust Level:** Trusted (encrypted at rest)
- **Access:** Daemon only (user-level)
### 2. TPM Key Storage
- **Location:** TPM 2.0 hardware (or software fallback)
- **Contents:** Encryption keys bound to TPM
- **Trust Level:** Trusted (hardware security)
- **Access:** Via tpm2-tss library
### 3. Configuration Files
- **Location:** `/etc/linux-hello/`
- **Contents:** System configuration, policies
- **Trust Level:** Admin-only (0o600)
- **Access:** Root/Daemon
---
## Trust Boundaries
### TB1: Unix Socket IPC
```
┌─────────────────────────────────────────────────────────────────┐
│ External Entities │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌───────┐ │
│ │ User │ │ PAM │ │ CLI │ │ GNOME │ │ KDE │ │
│ │ (Face) │ │ Module │ │ Client │ │Settings │ │Settings│ │
│ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ └───┬───┘ │
└───────┼────────────┼────────────┼────────────┼────────────┼─────┘
│ │ │ │ │
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
┌───────────────────────────────────────────────────────────────────┐
│ TRUST BOUNDARY 1 │
│ Unix Socket IPC │
│ (/run/linux-hello/auth.sock) │
│ │
│ Controls: │
│ - SO_PEERCRED for UID verification │
│ - Socket permissions: 0o600 (owner only) │
│ - Rate limiting: 10 requests/second │
│ - Message size limit: 64KB │
└────────────────────────────┬──────────────────────────────────────┘
┌─────────────────┐
│ IPC Handler │
│ (Validates, │
│ authorizes) │
└────────┬────────┘
```
### TB2: Encrypted Storage / TPM Interface
```
┌───────────────────────────────────────────────────────────────────┐
│ Daemon Internal │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ TRUST BOUNDARY 2 │ │
│ │ Encrypted Storage / TPM Interface │ │
│ │ │ │
│ │ Controls: │ │
│ │ - AES-256-GCM template encryption │ │
│ │ - PBKDF2-HMAC-SHA256 (600k iterations) │ │
│ │ - TPM key binding (or software fallback) │ │
│ │ - Secure memory: mlock + zeroize │ │
│ └──────────────────────────┬──────────────────────────────────┘ │
└─────────────────────────────┼────────────────────────────────────┘
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌─────────────────┐
│ Template │ │ TPM │ │ Config │
│ Storage │ │ Key │ │ Files │
│ (AES-256-GCM) │ │ Storage │ │ (/etc/) │
└───────────────┘ │ (Hardware) │ └─────────────────┘
└───────────────┘
```
### TB3: Hardware Interfaces
```
┌───────────────────────────────────────────────────────────────────┐
│ Hardware Layer │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ TRUST BOUNDARY 3 │ │
│ │ Hardware Interfaces │ │
│ │ │ │
│ │ Controls: │ │
│ │ - V4L2 frame validation │ │
│ │ - IR emitter control │ │
│ │ - TPM command validation │ │
│ │ - Device permissions │ │
│ └──────────────────────────┬──────────────────────────────────┘ │
└─────────────────────────────┼────────────────────────────────────┘
┌─────────────────────┼─────────────────────┐
▼ ▼
┌───────────────┐ ┌───────────────┐
│ V4L2 │ │ TPM2 │
│ Camera │ │ Device │
│ (IR + RGB) │ │ (Hardware) │
└───────────────┘ └───────────────┘
```
### TB4: D-Bus Interface
```
┌───────────────────────────────────────────────────────────────────┐
│ Settings Applications │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ GNOME │ │ KDE │ │
│ │ Settings │ │ Settings │ │
│ └──────┬──────┘ └──────┬──────┘ │
└─────────┼────────────────┼───────────────────────────────────────┘
│ │
▼ ▼
┌───────────────────────────────────────────────────────────────────┐
│ TRUST BOUNDARY 4 │
│ D-Bus │
│ (org.linuxhello) │
│ │
│ Controls: │
│ - D-Bus policy configuration │
│ - Method call validation │
│ - No secrets exposed via D-Bus │
└────────────────────────────┬──────────────────────────────────────┘
┌─────────────────┐
│ D-Bus Service │
│ Handler │
└────────┬────────┘
```
### TB5: System Integration
```
┌───────────────────────────────────────────────────────────────────┐
│ System Layer │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ TRUST BOUNDARY 5 │ │
│ │ System Integration │ │
│ │ │ │
│ │ Components: │ │
│ │ - systemd service (linux-hello-daemon.service) │ │
│ │ - PAM module execution context │ │
│ │ - Privilege separation │ │
│ │ - Session management │ │
│ │ │ │
│ │ Controls: │ │
│ │ - Service user: linux-hello (unprivileged) │ │
│ │ - PAM conversation validation │ │
│ │ - systemd security features │ │
│ └─────────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────┘
```
---
## Data Flows
### Authentication Flow
```
1. User presents face to camera
2. V4L2 captures frame (IR + RGB)
│ TB3: Hardware Interface
3. Detection module processes frame (ONNX)
│ TB2: Internal processing
4. Anti-spoofing validates liveness
│ TB2: PAD checks
5. Embedding extraction (or placeholder)
│ TB2: Internal processing
6. Template matching (cosine similarity)
│ TB2: Secure comparison
7. IPC response via Unix socket
│ TB1: IPC boundary
8. Result returned to PAM/CLI
```
### Template Storage Flow
```
1. Enrollment triggered (Settings app via D-Bus)
│ TB4: D-Bus
2. IPC call to daemon
│ TB1: IPC
3. Capture face template
│ TB2: Processing
4. Encrypt template (AES-256-GCM)
│ TB2: Encryption boundary
5. Store in ~/.local/share/linux-hello/
│ TB2: Storage boundary
6. Optional: Bind to TPM
│ TB2: TPM boundary
```
---
## Trust Boundary Summary
| Boundary | Location | Trust Transition | Key Controls |
|----------|----------|------------------|---------------|
| TB1 | Unix Socket IPC | Untrusted → Daemon | SO_PEERCRED, rate limit, 0o600 |
| TB2 | Encrypted Storage/TPM | Daemon → Trusted Storage | AES-256-GCM, PBKDF2, TPM |
| TB3 | Hardware Interfaces | Kernel → Hardware | V4L2 validation, device perms |
| TB4 | D-Bus | Untrusted → Daemon | D-Bus policy, caller validation |
| TB5 | System Integration | System → Service | systemd, PAM context |
---
## References
- Architecture: CLAUDE.md sections "Architecture" and "Communication Flow"
- IPC Security: `linux-hello-daemon/src/ipc.rs`
- Template Storage: `linux-hello-daemon/src/secure_template_store.rs`
- TPM Integration: `linux-hello-daemon/src/tpm.rs`
- ONNX Models: `linux-hello-daemon/src/onnx/`
---
*This DFD follows OWASP Threat Dragon methodology and supports STRIDE threat analysis.*

View File

@@ -1,384 +0,0 @@
# Security Control Mapping
**Created:** 2026-02-14
**Based on:** ARCH-04, STRIDE Threats, DFD
**Confidence:** HIGH
---
## Overview
This document maps existing and planned security controls to the threats identified in the STRIDE threat analysis. Each control is documented with its implementation location, threats mitigated, and effectiveness rating.
---
## 1. IPC Security Controls
### 1.1 SO_PEERCRED Credential Validation
| Attribute | Value |
|-----------|-------|
| **Control Type** | Authentication |
| **Implementation** | `linux-hello-daemon/src/ipc.rs` |
| **Threats Mitigated** | UID spoofing via socket, Spoofing threats |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Uses `SO_PEERCRED` socket option to retrieve peer credentials
- Validates UID/GID before processing any request
- Rejects connections from untrusted UIDs
### 1.2 Unix Socket Permissions
| Attribute | Value |
|-----------|-------|
| **Control Type** | Access Control |
| **Implementation** | systemd service, socket activation |
| **Threats Mitigated** | Socket injection, unauthorized access |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Socket path: `/run/linux-hello/auth.sock`
- Permissions: `0o600` (owner read/write only)
- Ownership: `root:linux-hello`
### 1.3 Rate Limiting
| Attribute | Value |
|-----------|-------|
| **Control Type** | DoS Prevention |
| **Implementation** | `linux-hello-daemon/src/ipc.rs` |
| **Threats Mitigated** | Rate limit exhaustion, DoS threats |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Limit: 10 requests per second per UID
- Implements token bucket algorithm
- Gradual backoff on limit exceeded
### 1.4 Message Size Limits
| Attribute | Value |
|-----------|-------|
| **Control Type** | Input Validation |
| **Implementation** | `linux-hello-daemon/src/ipc.rs` |
| **Threats Mitigated** | Buffer overflow, memory exhaustion |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Maximum message size: 64KB
- Validated before processing
---
## 2. Cryptographic Controls
### 2.1 AES-256-GCM Template Encryption
| Attribute | Value |
|-----------|-------|
| **Control Type** | Data at Rest Encryption |
| **Implementation** | `linux-hello-daemon/src/secure_template_store.rs` |
| **Threats Mitigated** | Template exposure, template tampering |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- AES-256-GCM authenticated encryption
- Unique IV per template
- Authenticated decryption (detects tampering)
### 2.2 PBKDF2-HMAC-SHA256 Key Derivation
| Attribute | Value |
|-----------|-------|
| **Control Type** | Key Derivation |
| **Implementation** | `linux-hello-daemon/src/tpm.rs`, secure_template_store.rs |
| **Threats Mitigated** | Brute-force attacks on stored keys |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Iterations: 600,000
- Salt: Unique per installation
- Output: 256-bit key
### 2.3 TPM Key Binding
| Attribute | Value |
|-----------|-------|
| **Control Type** | Hardware Security |
| **Implementation** | `linux-hello-daemon/src/tpm.rs` |
| **Threats Mitigated** | Template extraction, key compromise |
| **Effectiveness** | VERY HIGH (hardware) |
| **Status** | Implemented (with software fallback) |
**Details:**
- Keys bound to TPM 2.0 hardware
- Requires TPM auth value for operations
- Software fallback available (reduced security)
### 2.4 Constant-Time Comparison
| Attribute | Value |
|-----------|-------|
| **Control Type** | Timing Attack Prevention |
| **Implementation** | `linux-hello-daemon/src/matching.rs` |
| **Threats Mitigated** | Timing attacks on template matching |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Uses `subtle` crate for constant-time operations
- Fixed comparison duration regardless of match
---
## 3. Memory Security Controls
### 3.1 mlock for Sensitive Data
| Attribute | Value |
|-----------|-------|
| **Control Type** | Memory Protection |
| **Implementation** | `linux-hello-daemon/src/secure_memory.rs` |
| **Threats Mitigated** | Swapping sensitive data to disk |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Uses `mlock()` to lock sensitive pages in RAM
- Prevents paging to swap
### 3.2 zeroize for Automatic Wiping
| Attribute | Value |
|-----------|-------|
| **Control Type** | Memory Protection |
| **Implementation** | `linux-hello-daemon/src/secure_memory.rs` |
| **Threats Mitigated** | Sensitive data left in memory |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Uses `zeroize` crate for automatic memory wiping
- `SecureBytes` and `SecureEmbedding` types auto-zeroize on drop
### 3.3 SecureBytes Type
| Attribute | Value |
|-----------|-------|
| **Control Type** | Data Handling |
| **Implementation** | `linux-hello-daemon/src/secure_memory.rs` |
| **Threats Mitigated** | Memory exposure, data leakage |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Wraps byte vectors with secure handling
- Automatic zeroization
- No `Debug` or `Display` implementations (prevents accidental logging)
### 3.4 SecureEmbedding Type
| Attribute | Value |
|-----------|-------|
| **Control Type** | Data Handling |
| **Implementation** | `linux-hello-daemon/src/secure_memory.rs` |
| **Threats Mitigated** | Embedding data leakage in memory |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Specialized type for biometric embeddings
- Automatic secure memory handling
---
## 4. Authorization Controls
### 4.1 D-Bus Policy Enforcement
| Attribute | Value |
|-----------|-------|
| **Control Type** | Access Control |
| **Implementation** | `dist/linux-hello.conf` (D-Bus policy) |
| **Threats Mitigated** | D-Bus method injection, unauthorized settings |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- D-Bus policy configuration in `dist/`
- Restricts method calls to authorized callers
- No secrets exposed via D-Bus
### 4.2 PAM Session Validation
| Attribute | Value |
|-----------|-------|
| **Control Type** | Access Control |
| **Implementation** | `pam-module/pam_linux_hello.c` |
| **Threats Mitigated** | PAM bypass, unauthorized login |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Validates PAM conversation
- Returns proper error codes
- Secure error message handling
### 4.3 Peer Credential Verification
| Attribute | Value |
|-----------|-------|
| **Control Type** | Authentication |
| **Implementation** | `linux-hello-daemon/src/ipc.rs` |
| **Threats Mitigated** | UID spoofing, unauthorized access |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Verifies peer credentials on every request
- Maps UIDs to authorized users
---
## 5. Anti-Spoofing / PAD Controls
### 5.1 IR Liveness Detection
| Attribute | Value |
|-----------|-------|
| **Control Type** | Presentation Attack Detection |
| **Implementation** | `linux-hello-daemon/src/anti_spoofing.rs` |
| **Threats Mitigated** | Photo attacks, video replay, fake camera |
| **Effectiveness** | MEDIUM-HIGH |
| **Status** | Implemented |
**Details:**
- Validates IR signature from camera
- Requires IR camera hardware
- Combined with other PAD signals
### 5.2 Frame Format Validation
| Attribute | Value |
|-----------|-------|
| **Control Type** | Input Validation |
| **Implementation** | `linux-hello-daemon/src/camera/` |
| **Threats Mitigated** | Malformed frames, injection attacks |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Validates V4L2 frame format
- Checks resolution, color space
- Rejects malformed frames
### 5.3 Texture Analysis
| Attribute | Value |
|-----------|-------|
| **Control Type** | Presentation Attack Detection |
| **Implementation** | `linux-hello-daemon/src/anti_spoofing.rs` |
| **Threats Mitigated** | 3D mask attacks, silicone faces |
| **Effectiveness** | MEDIUM |
| **Status** | Implemented (ONNX feature) |
**Details:**
- Analyzes surface texture
- Detects artificial materials
- Requires ONNX model
### 5.4 Blink/Movement Detection
| Attribute | Value |
|-----------|-------|
| **Control Type** | Presentation Attack Detection |
| **Implementation** | `linux-hello-daemon/src/anti_spoofing.rs` |
| **Threats Mitigated** | Static photo attacks |
| **Effectiveness** | MEDIUM |
| **Status** | Implemented (ONNX feature) |
**Details:**
- Requires multiple frames
- Detects eye movement/blinking
- Liveness indicator
---
## 6. Configuration Security Controls
### 6.1 Config File Permissions
| Attribute | Value |
|-----------|-------|
| **Control Type** | Access Control |
| **Implementation** | Installation scripts, systemd |
| **Threats Mitigated** | Config tampering, privilege escalation |
| **Effectiveness** | HIGH |
| **Status** | Implemented |
**Details:**
- Location: `/etc/linux-hello/`
- Permissions: `0o600` (root only)
- No secrets stored
### 6.2 Environment Variable Validation
| Attribute | Value |
|-----------|-------|
| **Control Type** | Input Validation |
| **Implementation** | `linux-hello-daemon/src/config.rs` |
| **Threats Mitigated** | Environment injection |
| **Effectiveness** | MEDIUM |
| **Status** | Implemented |
**Details:**
- Validates all environment variables
- Sanitizes input
- No direct use in security-critical paths
---
## Gap Analysis
### Identified Gaps
| Gap | Severity | Recommended Action | Priority |
|-----|----------|-------------------|----------|
| Immutable audit logging | MEDIUM | Implement append-only logging with syslog | Future |
| Model file integrity verification | MEDIUM | Add file hash verification at load time | Future |
| Anti-replay for templates | LOW | Add freshness checks to templates | Future |
| Hardware security key requirement | LOW | Make TPM mandatory for production | Future |
### Controls by STRIDE Category
| STRIDE Category | Controls Applied | Coverage |
|-----------------|------------------|----------|
| Spoofing | SO_PEERCRED, socket permissions, D-Bus policy | HIGH |
| Tampering | AES-256-GCM, file permissions, frame validation | HIGH |
| Repudiation | Logging (partial), syslog integration | MEDIUM |
| Information Disclosure | Secure memory, encryption, constant-time | HIGH |
| Denial of Service | Rate limiting, resource limits, timeouts | HIGH |
| Elevation of Privilege | Privilege separation, PAM validation | HIGH |
---
## References
- STRIDE Analysis: `.planning/phases/01-architecture-threat-modeling/stride-threats.md`
- DFD: `.planning/phases/01-architecture-threat-modeling/dfd.md`
- Attack Surface: `.planning/phases/01-architecture-threat-modeling/attack-surface.md`
- IPC Implementation: `linux-hello-daemon/src/ipc.rs`
- Secure Memory: `linux-hello-daemon/src/secure_memory.rs`
- Anti-Spoofing: `linux-hello-daemon/src/anti_spoofing.rs`
- TPM: `linux-hello-daemon/src/tpm.rs`
---
*This security control mapping supports ARCH-04 and identifies gaps for future enhancement.*

View File

@@ -1,433 +0,0 @@
# STRIDE Threat Analysis
**Created:** 2026-02-14
**Based on:** ARCH-02, DFD, Attack Surface Analysis
**Confidence:** HIGH
---
## Overview
This document applies the STRIDE threat modeling methodology to the Linux Hello system, systematically analyzing threats across each component identified in the Data Flow Diagram. STRIDE categorizes threats into six classes: Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege.
---
## 1. Spoofing Threats
Spoofing threats involve an attacker pretending to be a different entity.
### 1.1 Fake Camera Device Injection
| Attribute | Value |
|-----------|-------|
| **Affected Component** | V4L2 Camera (TB3) |
| **Attack Vector** | Create a virtual camera device that delivers pre-recorded frames |
| **Likelihood** | MEDIUM - Requires root or video group access |
| **Impact** | HIGH - Bypasses biometric authentication |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- IR liveness detection (anti-spoofing module)
- Device permission enforcement
- Frame timestamp validation
### 1.2 UID Spoofing via Socket Manipulation
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Unix Socket IPC (TB1) |
| **Attack Vector** | Manipulate peer credentials or exploit SO_PEERCRED weaknesses |
| **Likelihood** | LOW - Requires socket access control bypass |
| **Impact** | HIGH - Unauthorized authentication |
| **Risk Rating** | MEDIUM (9/25) |
**Mitigation:**
- SO_PEERCRED credential validation
- Socket permissions: 0o600
- UID/GID verification before processing
### 1.3 TPM Hardware Emulation
| Attribute | Value |
|-----------|-------|
| **Affected Component** | TPM2 Device (TB3) |
| **Attack Vector** | Software TPM emulation to bypass hardware binding |
| **Likelihood** | LOW - Requires kernel-level access |
| **Impact** | MEDIUM - Affects key storage only if software fallback used |
| **Risk Rating** | LOW (6/25) |
**Mitigation:**
- Prefer hardware TPM over software fallback
- TPM auth value required for operations
### 1.4 D-Bus Service Impersonation
| Attribute | Value |
|-----------|-------|
| **Affected Component** | D-Bus Interface (TB4) |
| **Attack Vector** | Register fake D-Bus service with same name |
| **Likelihood** | LOW - Requires D-Bus configuration bypass |
| **Impact** | MEDIUM - Could intercept settings operations |
| **Risk Rating** | LOW-MEDIUM (8/25) |
**Mitigation:**
- D-Bus policy configuration
- Bus name verification
- No secrets exposed via D-Bus
---
## 2. Tampering Threats
Tampering threats involve unauthorized modification of data or code.
### 2.1 Modify Templates in Encrypted Storage
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Template Storage (TB2) |
| **Attack Vector** | Tamper with encrypted template files |
| **Likelihood** | LOW - Requires filesystem access |
| **Impact** | HIGH - Could deny service or cause matching errors |
| **Risk Rating** | MEDIUM (9/25) |
**Mitigation:**
- AES-256-GCM authenticated encryption
- Integrity verification on load
- Secure file permissions
### 2.2 Inject Frames into Camera Stream
| Attribute | Value |
|-----------|-------|
| **Affected Component** | V4L2 Camera (TB3) |
| **Attack Vector** | Manipulate V4L2 device or inject frames via driver |
| **Likelihood** | MEDIUM - Requires video group access |
| **Impact** | HIGH - Enables presentation attacks |
| **Risk Rating** | HIGH (15/25) |
**Mitigation:**
- Frame format validation
- IR signature verification
- Anti-spoofing (multi-signal PAD)
### 2.3 Tamper with ONNX Model Files
| Attribute | Value |
|-----------|-------|
| **Affected Component** | ONNX Models (TB2) |
| **Attack Vector** | Replace model files with malicious versions |
| **Likelihood** | LOW - Requires filesystem access |
| **Impact** | HIGH - Could cause incorrect authentication decisions |
| **Risk Rating** | MEDIUM (9/25) |
**Mitigation:**
- Model file permissions
- Runtime model validation
- File integrity checksums
### 2.4 Modify Config Files in /etc/
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Configuration Files (TB2) |
| **Attack Vector** | Modify YAML config files |
| **Likelihood** | LOW - Requires root access |
| **Impact** | MEDIUM - Could change security policies |
| **Risk Rating** | LOW (6/25) |
**Mitigation:**
- Root-only file permissions (0o600)
- Config validation on load
- No secrets in config files
---
## 3. Repudiation Threats
Repudiation threats involve denying that an action occurred.
### 3.1 Delete Authentication Logs
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Logging System |
| **Attack Vector** | Delete or truncate log files |
| **Likelihood** | MEDIUM - Requires user-level access |
| **Impact** | LOW - Audit trail only |
| **Risk Rating** | LOW (4/25) |
**Mitigation:**
- Log file permissions
- syslog integration
- Immutable audit logging (future enhancement)
### 3.2 Modify Audit Records
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Audit System |
| **Attack Vector** | Modify existing audit entries |
| **Likelihood** | LOW - Requires elevated privileges |
| **Impact** | LOW - Forensic impact only |
| **Risk Rating** | LOW (3/25) |
**Mitigation:**
- syslog forwarding
- Audit log integrity checks
### 3.3 No Logging of Failed Attempts
| Attribute | Value |
|-----------|-------|
| **Affected Component** | IPC Handler |
| **Attack Vector** | Exploit missing audit trail |
| **Likelihood** | N/A - Configuration issue |
| **Impact** | MEDIUM - No forensic evidence |
| **Risk Rating** | MEDIUM (8/25) |
**Mitigation:**
- Log all authentication attempts (success and failure)
- Include timestamps, UID, source
---
## 4. Information Disclosure Threats
Information disclosure threats involve exposing sensitive data.
### 4.1 Expose Templates via Filesystem
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Template Storage (TB2) |
| **Attack Vector** | Read encrypted template files |
| **Likelihood** | LOW - Requires filesystem access |
| **Impact** | HIGH - Biometric data exposure |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- AES-256-GCM encryption at rest
- Secure file permissions
- User-level isolation
### 4.2 Leak Embedding Data in Error Messages
| Attribute | Value |
|-----------|-------|
| **Affected Component** | IPC Handler, Matching Service |
| **Attack Vector** | Trigger errors that expose embedding data |
| **Likelihood** | LOW - Requires triggering specific errors |
| **Impact** | MEDIUM - Information leakage |
| **Risk Rating** | LOW-MEDIUM (6/25) |
**Mitigation:**
- Sanitize error messages
- No raw embedding data in logs
- Generic error responses
### 4.3 Timing Attack on Template Matching
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Matching Service (TB2) |
| **Attack Vector** | Measure comparison timing to extract template information |
| **Likelihood** | LOW - Requires many measurements |
| **Impact** | MEDIUM - Template data leakage |
| **Risk Rating** | MEDIUM (8/25) |
**Mitigation:**
- Constant-time comparison using `subtle` crate
- Fixed comparison duration
### 4.4 Config File Permission Escalation
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Configuration Files (TB2) |
| **Attack Vector** | Read sensitive config data |
| **Likelihood** | LOW - Requires permission misconfiguration |
| **Impact** | LOW - No secrets in config |
| **Risk Rating** | LOW (3/25) |
**Mitigation:**
- 0o600 permissions
- No secrets in YAML config
---
## 5. Denial of Service Threats
Denial of service threats involve making a system unavailable.
### 5.1 Exhaust Rate Limiting (10/sec)
| Attribute | Value |
|-----------|-------|
| **Affected Component** | IPC Handler (TB1) |
| **Attack Vector** | Send requests at >10/sec to trigger limit |
| **Likelihood** | HIGH - Easy to send rapid requests |
| **Impact** | HIGH - Legitimate users blocked |
| **Risk Rating** | HIGH (15/25) |
**Mitigation:**
- Per-UID rate limiting
- Gradual backoff
- Alert on rate limit patterns
### 5.2 Camera Resource Exhaustion
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Camera Module (TB3) |
| **Attack Vector** | Repeated camera open/close or malformed frames |
| **Likelihood** | MEDIUM - Requires IPC access |
| **Impact** | HIGH - Camera unavailable for auth |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- Camera open/close limits
- Resource cleanup timeouts
- Frame size limits
### 5.3 Fork Bomb on Daemon
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Daemon Process (TB5) |
| **Attack Vector** | Trigger rapid forking to exhaust resources |
| **Likelihood** | LOW - Requires daemon code execution |
| **Impact** | HIGH - System-wide DoS |
| **Risk Rating** | MEDIUM (9/25) |
**Mitigation:**
- Resource limits via systemd
- Process count limits
- No exec of user-controlled processes
### 5.4 TPM Command Flooding
| Attribute | Value |
|-----------|-------|
| **Affected Component** | TPM2 Device (TB3) |
| **Attack Vector** | Flood TPM with commands |
| **Likelihood** | LOW - Requires TPM access |
| **Impact** | MEDIUM - Hardware unavailability |
| **Risk Rating** | LOW (5/25) |
**Mitigation:**
- TPM operation timeouts
- Command queuing limits
---
## 6. Elevation of Privilege Threats
Elevation of privilege threats involve gaining capabilities beyond what is authorized.
### 6.1 Root to User Privilege Escalation
| Attribute | Value |
|-----------|-------|
| **Affected Component** | System Integration (TB5) |
| **Attack Vector** | Exploit daemon vulnerabilities to gain root |
| **Likelihood** | LOW - Requires code execution vulnerability |
| **Impact** | CRITICAL - Full system compromise |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- Daemon runs as unprivileged user (linux-hello)
- systemd security features
- Minimal privilege principle
### 6.2 Bypass PAM Authorization
| Attribute | Value |
|-----------|-------|
| **Affected Component** | PAM Module (TB1) |
| **Attack Vector** | Bypass PAM conversation or exploit PAM stack |
| **Likelihood** | LOW - Requires PAM configuration access |
| **Impact** | CRITICAL - Unauthenticated system access |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- PAM module validation
- Secure conversation handling
- Systemd service restrictions
### 6.3 Template Replacement Attack
| Attribute | Value |
|-----------|-------|
| **Affected Component** | Template Storage (TB2) |
| **Attack Vector** | Replace stored template with attacker's template |
| **Likelihood** | LOW - Requires filesystem access |
| **Impact** | HIGH - Attacker can now authenticate |
| **Risk Rating** | HIGH (12/25) |
**Mitigation:**
- Template integrity verification
- TPM key binding
- User consent for enrollment
### 6.4 D-Bus Method Injection
| Attribute | Value |
|-----------|-------|
| **Affected Component** | D-Bus Service (TB4) |
| **Attack Vector** | Inject malicious method calls via D-Bus |
| **Likelihood** | LOW - Requires D-Bus policy bypass |
| **Impact** | MEDIUM - Service abuse |
| **Risk Rating** | LOW-MEDIUM (6/25) |
**Mitigation:**
- D-Bus policy configuration
- Input validation on all methods
- No privileged operations via D-Bus
---
## Threat Summary by Component
| Component | Spoofing | Tampering | Repudiation | Info Disclosure | DoS | EoP |
|-----------|----------|-----------|-------------|-----------------|-----|-----|
| Unix Socket IPC | HIGH | - | - | - | HIGH | - |
| D-Bus Interface | LOW | - | - | - | - | LOW |
| Template Storage | - | MEDIUM | - | HIGH | - | HIGH |
| TPM Key Storage | LOW | - | - | - | LOW | - |
| Config Files | - | LOW | - | LOW | - | - |
| V4L2 Camera | HIGH | HIGH | - | - | HIGH | - |
| ONNX Models | - | MEDIUM | - | - | - | - |
| Daemon Process | - | - | - | - | MEDIUM | HIGH |
| Logging/Audit | - | LOW | MEDIUM | - | - | - |
---
## Risk Priority Matrix
| Priority | Threat | Component | Rating |
|----------|--------|-----------|--------|
| 1 | Camera frame injection | V4L2 | HIGH (15/25) |
| 2 | Rate limit exhaustion | IPC | HIGH (15/25) |
| 3 | Fake camera device | Camera | HIGH (12/25) |
| 4 | Template exposure | Storage | HIGH (12/25) |
| 5 | Template replacement | Storage | HIGH (12/25) |
| 6 | PAM bypass | PAM | HIGH (12/25) |
| 7 | Root escalation | Daemon | HIGH (12/25) |
| 8 | ONNX model tampering | Models | MEDIUM (9/25) |
| 9 | UID spoofing | IPC | MEDIUM (9/25) |
| 10 | Fork bomb | Daemon | MEDIUM (9/25) |
---
## References
- DFD: `.planning/phases/01-architecture-threat-modeling/dfd.md`
- Attack Surface: `.planning/phases/01-architecture-threat-modeling/attack-surface.md`
- OWASP STRIDE: https://owasp.org/www-community/Threat_Modeling
- IPC Implementation: `linux-hello-daemon/src/ipc.rs`
- Anti-Spoofing: `linux-hello-daemon/src/anti_spoofing.rs`
---
*This STRIDE threat analysis supports ARCH-02 and enables security control mapping in subsequent planning.*

View File

@@ -1,164 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 01
type: execute
wave: 1
depends_on: []
files_modified: []
autonomous: true
user_setup: []
must_haves:
truths:
- "cargo-audit reports no high/critical vulnerabilities in dependencies"
- "cargo-deny passes all security policy checks (licenses, duplicates, sources)"
- "clippy reports no security-related warnings (with appropriate allowlist)"
- "Miri analysis completes on all unsafe blocks without undefined behavior"
artifacts:
- path: ".planning/phases/02-rust-code-security-review/tool-audit-results.md"
provides: "cargo-audit output documenting vulnerabilities found"
- path: ".planning/phases/02-rust-code-security-review/deny-check-results.md"
provides: "cargo-deny output documenting policy checks"
- path: ".planning/phases/02-rust-code-security-review/clippy-results.md"
provides: "clippy output documenting warnings found"
- path: ".planning/phases/02-rust-code-security-review/miri-results.md"
provides: "Miri output documenting undefined behavior checks"
---
<objective>
Run all security tooling to identify Rust-specific vulnerabilities and code issues
Purpose: Establish baseline security posture by scanning dependencies, enforcing policies, running static analysis, and testing unsafe code for undefined behavior
Output: Tool output files documenting findings for each security scanner
</objective>
<execution_context>
@/home/eliott/.config/opencode/get-shit-done/workflows/execute-plan.md
</execution_context>
<context>
@.planning/ROADMAP.md
@.planning/phases/02-rust-code-security-review/02-RESEARCH.md
</context>
<tasks>
<task type="auto">
<name>Task 1: Run cargo-audit to find dependency vulnerabilities</name>
<files>.planning/phases/02-rust-code-security-review/tool-audit-results.md</files>
<action>
Run `cargo audit` in the project root. Capture full output including:
- Vulnerabilities found (by severity: critical, high, medium, low)
- Patched vs unpatched vulnerabilities
- Any ignored advisories with justification
If vulnerabilities found:
- Document each with CVE/references
- Note if patch available
- Note if false positive
Create markdown file documenting results.
</action>
<verify>
Run `cargo audit` and verify exit code. Create results file.
</verify>
<done>
cargo-audit output captured, no high/critical vulnerabilities OR vulnerabilities documented with remediation plan
</done>
</task>
<task type="auto">
<name>Task 2: Run cargo-deny to enforce security policies</name>
<files>.planning/phases/02-rust-code-security-review/deny-check-results.md</files>
<action>
Run `cargo deny check` in the project root. Capture full output including:
- License checks (allowed/disallowed licenses)
- Duplicate dependencies
- Security advisories (sources)
- Bans (forbidden crates)
Document any failures and proposed resolutions.
Create markdown file documenting results.
</action>
<verify>
Run `cargo deny check` and verify passes all checks.
</verify>
<done>
cargo-deny passes all policy checks OR failures documented with resolution plan
</done>
</task>
<task type="auto">
<name>Task 3: Run clippy for code quality and security lints</name>
<files>.planning/phases/02-rust-code-security-review/clippy-results.md</files>
<action>
Run `cargo clippy --all-targets -- -D warnings` to catch all warnings.
Focus on security-relevant lints:
- Memory safety: dangling_pointer, mem_forget, unsafe_derive_deserialize
- Cryptography: expect_used, unwrap_used in crypto code
- Concurrency: await_holding_lock, arc_with_non_send_sync
Document:
- All warnings found (by category)
- Which are security-relevant vs code quality
- Allowlist entries with justification for security-critical code
Create markdown file documenting results.
</action>
<verify>
Run `cargo clippy --all-targets -- -D warnings` - exit code 0 expected after addressing warnings
</verify>
<done>
clippy runs successfully with no security warnings OR security warnings documented with allowlist
</done>
</task>
<task type="auto">
<name>Task 4: Run Miri on unsafe code blocks</name>
<files>.planning/phases/02-rust-code-security-review/miri-results.md</files>
<action>
Run Miri on the daemon crate to detect undefined behavior:
1. First run: `cargo +nightly miri test -p linux-hello-daemon --no-default-features 2>&1`
(No-default-features because Miri doesn't support ONNX/native libs)
2. Run specifically on modules with unsafe: secure_memory, ipc
3. Use flags: `MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test`
Document:
- All Miri findings (undefined behavior, data races, memory leaks)
- Which unsafe blocks were tested
- Any limitations (unsupported operations, skipped tests)
Create markdown file documenting results.
</action>
<verify>
Run Miri tests - document any undefined behavior found
</verify>
<done>
Miri analysis completes on unsafe blocks, no undefined behavior found OR issues documented
</done>
</task>
</tasks>
<verification>
All four security tools have been run and results documented:
- cargo-audit: dependency vulnerability scan complete
- cargo-deny: policy enforcement scan complete
- clippy: static analysis complete
- Miri: undefined behavior detection complete
</verification>
<success_criteria>
1. cargo-audit reports no high/critical vulnerabilities
2. cargo-deny passes all security policy checks
3. clippy reports no security-related warnings (after allowlisting if needed)
4. Miri analysis completes without undefined behavior
</success_criteria>
<output>
After completion, create `.planning/phases/02-rust-code-security-review/02-01-SUMMARY.md`
</output>

View File

@@ -1,134 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 01
subsystem: security
tags: [rust, security, cargo-audit, cargo-deny, clippy, miri]
# Dependency graph
requires:
- phase: 01-architecture-threat-modeling
provides: Security architecture and threat model
provides:
- cargo-audit results documenting dependency vulnerabilities
- cargo-deny results documenting policy compliance
- clippy results documenting code quality
- miri results documenting undefined behavior checks
affects: [future security phases, code review]
# Tech tracking
tech-stack:
added: [cargo-audit, cargo-deny]
patterns: [security tooling automation]
key-files:
created:
- .planning/phases/02-rust-code-security-review/tool-audit-results.md
- .planning/phases/02-rust-code-security-review/deny-check-results.md
- .planning/phases/02-rust-code-security-review/clippy-results.md
- .planning/phases/02-rust-code-security-review/miri-results.md
modified:
- linux-hello-common/src/config.rs
- linux-hello-common/src/template.rs
- linux-hello-daemon/src/camera/linux.rs
- linux-hello-daemon/src/camera/mod.rs
- linux-hello-daemon/src/ipc.rs
- linux-hello-daemon/src/secure_memory.rs
key-decisions:
- "Used clippy without -D warnings after fixing blocking issues"
- "Documented Miri limitations for system call-heavy code"
patterns-established:
- "Security tooling should run in CI/CD"
- "Miri cannot test code that uses mlock/chmod/process execution"
# Metrics
duration: 40min
completed: 2026-02-14T10:13:45Z
---
# Phase 2 Plan 1: Rust Security Tooling Summary
**Ran cargo-audit, cargo-deny, clippy, and Miri to establish baseline security posture**
## Performance
- **Duration:** ~40 min
- **Started:** 2026-02-14T09:34:14Z
- **Completed:** 2026-02-14T10:13:45Z
- **Tasks:** 4
- **Files modified:** 11 (7 code fixes + 4 result files)
## Accomplishments
- Ran cargo-audit: Found 1 HIGH vulnerability (bytes crate)
- Ran cargo-deny: License policy needs configuration
- Ran clippy: Fixed 7 style warnings, passes with no errors
- Ran Miri: Limited by system call support, unsafe code manually verified
## Task Commits
Each task was committed atomically:
1. **Task 1: cargo-audit** - `f80d051` (docs)
2. **Task 2: cargo-deny** - `f80d051` (docs)
3. **Task 3: clippy** - `fd5d8c8` (fix)
4. **Task 4: Miri** - `f80d051` (docs)
**Plan metadata:** (to be committed with this summary)
## Files Created/Modified
- `.planning/phases/02-rust-code-security-review/tool-audit-results.md` - cargo-audit vulnerability report
- `.planning/phases/02-rust-code-security-review/deny-check-results.md` - cargo-deny policy report
- `.planning/phases/02-rust-code-security-review/clippy-results.md` - clippy lint report
- `.planning/phases/02-rust-code-security-review/miri-results.md` - Miri undefined behavior report
- `linux-hello-common/src/config.rs` - Added Default derive
- `linux-hello-common/src/template.rs` - Simplified iterator
- `linux-hello-daemon/src/camera/linux.rs` - Fixed transmute annotations
- `linux-hello-daemon/src/ipc.rs` - Fixed method name, closures
- `linux-hello-daemon/src/secure_memory.rs` - Used is_multiple_of()
- `tests/integration/phase3_security_test.rs` - Used PI constant
## Decisions Made
- Used clippy without `-D warnings` flag after fixing blocking issues (all remaining warnings are style-related)
- Documented Miri limitations rather than skipping the tool entirely
- Need to create `deny.toml` for cargo-deny to pass
## Deviations from Plan
### Auto-fixed Issues
**1. [Rule 2 - Missing Critical] clippy passes with fixes**
- **Found during:** Task 3 (clippy execution)
- **Issue:** Multiple clippy errors preventing compilation
- **Fix:** Fixed 7 code issues (derive, closures, transmute, naming)
- **Files modified:** config.rs, template.rs, camera/linux.rs, ipc.rs, secure_memory.rs, phase3_security_test.rs
- **Verification:** `cargo clippy --all-targets` passes
- **Committed in:** fd5d8c8
---
**Total deviations:** 1 auto-fixed (1 missing critical)
**Impact on plan:** Fixed clippy errors essential for code quality. No scope creep.
## Issues Encountered
- **Miri limitations**: Cannot test code using mlock, chmod, or process execution - these are essential for security-critical features (secure memory, file permissions, hardware control)
- **cargo-deny**: No configuration exists - need to create deny.toml with license policy
## User Setup Required
None - no external service configuration required.
## Next Phase Readiness
- Security tooling baseline established
- Need to: Create deny.toml with license policy
- Need to: Address bytes crate vulnerability (RUSTSEC-2026-0007)
- Ready for: Manual code review of unsafe blocks
---
*Phase: 02-rust-code-security-review*
*Completed: 2026-02-14*

View File

@@ -1,261 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 02
type: execute
wave: 1
depends_on: []
files_modified: []
autonomous: true
user_setup: []
must_haves:
truths:
- "Unsafe code inventory documents all 12+ unsafe blocks with justification"
- "FFI boundary review identifies potential memory safety issues in tpm.rs, camera/linux.rs"
- "Input validation exists in all modules that process external data"
- "Error handling does not leak sensitive information in error messages"
- "Logging does not expose passwords, templates, or biometric data"
artifacts:
- path: ".planning/phases/02-rust-code-security-review/unsafe-inventory.md"
provides: "Complete inventory of all unsafe blocks with justifications"
- path: ".planning/phases/02-rust-code-security-review/ffi-review.md"
provides: "FFI boundary security review findings"
- path: ".planning/phases/02-rust-code-security-review/input-validation-review.md"
provides: "Input validation review findings"
- path: ".planning/phases/02-rust-code-security-review/error-handling-review.md"
provides: "Error handling security review findings"
- path: ".planning/phases/02-rust-code-security-review/logging-review.md"
provides: "Logging security review findings"
---
<objective>
Manually review Rust code for security issues not caught by tooling
Purpose: Document unsafe code usage, verify FFI safety, check input validation, ensure error messages and logs don't leak sensitive data
Output: Security review documents for each category
</objective>
<execution_context>
@/home/eliott/.config/opencode/get-shit-done/workflows/execute-plan.md
</execution_context>
<context>
@.planning/ROADMAP.md
@.planning/phases/02-rust-code-security-review/02-RESEARCH.md
</context>
<tasks>
<task type="auto">
<name>Task 1: Inventory all unsafe code blocks with justification</name>
<files>.planning/phases/02-rust-code-security-review/unsafe-inventory.md</files>
<action>
Search for all `unsafe` blocks in the Rust codebase:
```bash
grep -rn "unsafe" --include="*.rs" linux-hello-daemon/src/
grep -rn "unsafe" --include="*.rs" linux-hello-common/src/
```
Document each unsafe block:
- File path and line numbers
- Purpose (what it does)
- Safety justification (why it's safe)
- Risk level (LOW/MEDIUM/HIGH)
Focus on these pre-identified areas:
- ipc.rs:94-105 (SO_PEERCRED)
- ipc.rs:142-147 (getpwnam)
- secure_memory.rs:74-79 (slice from_raw_parts)
- secure_memory.rs:293-296,304-307 (ptr::write_volatile)
- secure_memory.rs:318,339-340 (mlock/munlock)
- camera/linux.rs:192-194 (stream lifetime)
- camera/linux.rs:198 (transmute)
Verify each has a safety comment explaining invariants.
</action>
<verify>
All unsafe blocks documented with file, line, purpose, justification
</verify>
<done>
Complete inventory exists with 12+ unsafe blocks documented with justifications
</done>
</task>
<task type="auto">
<name>Task 2: Review FFI boundaries for security</name>
<files>.planning/phases/02-rust-code-security-review/ffi-review.md</files>
<action>
Review all FFI (Foreign Function Interface) boundaries in the codebase:
1. ipc.rs - SO_PEERCRED getsockopt call:
- Verify error handling for getsockopt failures
- Check null pointer handling
2. ipc.rs - getpwnam/getpwuid calls:
- Verify null return checking
- Check buffer handling
3. secure_memory.rs - libc calls (mlock, munlock, memset):
- Verify all return values checked
- Check error handling
4. camera/linux.rs - V4L2 ioctl calls:
- Verify ioctl return handling
- Check buffer bounds
5. tpm.rs - TPM2 API calls (if TPM feature enabled):
- Verify all TPM return codes handled
- Check session handling
Document findings as markdown.
</action>
<verify>
All FFI boundaries reviewed, security issues documented if found
</verify>
<done>
FFI boundary review complete - no memory safety issues OR issues documented with fixes
</done>
</task>
<task type="auto">
<name>Task 3: Check input validation in all modules</name>
<files>.planning/phases/02-rust-code-security-review/input-validation-review.md</files>
<action>
Review all modules that process external data for proper input validation:
1. IPC message parsing (ipc.rs):
- Verify message size limits enforced
- Check deserialization validation
2. Config loading (config.rs):
- Verify path validation
- Check value bounds
3. Camera input (camera/linux.rs):
- Verify frame size validation
- Check buffer bounds
4. D-Bus interface (dbus_service.rs):
- Verify method parameter validation
- Check type conversions
5. Template storage (secure_template_store.rs):
- Verify file path validation
- Check encryption key validation
Search for validation patterns:
```bash
grep -rn "unwrap\|expect" --include="*.rs" linux-hello-daemon/src/
grep -rn "todo\!\|unimplemented" --include="*.rs" linux-hello-daemon/src/
```
Document any missing validation as findings.
</action>
<verify>
Input validation reviewed in all modules, gaps documented
</verify>
<done>
Input validation complete - proper validation exists OR gaps documented with fixes
</done>
</task>
<task type="auto">
<name>Task 4: Verify error handling doesn't leak information</name>
<files>.planning/phases/02-rust-code-security-review/error-handling-review.md</files>
<action>
Review error messages to ensure they don't leak sensitive information:
1. Read linux-hello-common/src/error.rs to understand error types
2. Check all error creation points:
- Error messages should not contain: file paths, internal structure details, crypto keys, template data, user credentials
- Error types can be informative but messages should be generic
3. Search for potentially leaky patterns:
```bash
grep -rn "Error\|err\!(" --include="*.rs" | grep -v "///"
```
4. Focus on these sensitive areas:
- Authentication failures (don't reveal if user exists)
- Crypto errors (don't expose key material)
- Template errors (don't expose template data)
- IPC errors (don't expose peer credentials)
Document any error messages that leak information with proposed fixes.
</action>
<verify>
Error messages reviewed, leaky patterns documented
</verify>
<done>
Error handling review complete - no information leakage OR leaks documented with fixes
</done>
</task>
<task type="auto">
<name>Task 5: Review logging for sensitive data exposure</name>
<files>.planning/phases/02-rust-code-security-review/logging-review.md</files>
<action>
Review all logging statements for sensitive data exposure:
1. Search for tracing/logging calls:
```bash
grep -rn "tracing::\|log::" --include="*.rs" linux-hello-daemon/src/
```
2. Check for sensitive data in logs:
- Passwords/credentials: Should NEVER be logged
- Templates/embeddings: Should NEVER be logged (only metadata)
- Biometric data: Should NEVER be logged
- Internal paths: Should use placeholders, not real paths
- Crypto keys: Should NEVER be logged
3. Check log levels:
- debug/info: Verify no sensitive data
- warn/error: Verify messages are generic
4. Focus areas:
- auth.rs: Login attempts, authentication results
- secure_template_store.rs: Template operations
- ipc.rs: Connection handling
- camera/linux.rs: Frame capture
5. Verify debug logs don't expose:
- Template comparisons scores
- Face embedding values
- TPM key handles
Document any logging that exposes sensitive data with proposed fixes.
</action>
<verify>
Logging reviewed, sensitive data exposure documented
</verify>
<done>
Logging review complete - no sensitive data exposure OR issues documented with fixes
</done>
</task>
</tasks>
<verification>
All five manual review tasks completed:
- Unsafe code inventory created
- FFI boundary review complete
- Input validation reviewed
- Error handling reviewed
- Logging reviewed
</verification>
<success_criteria>
1. Unsafe code inventory documents all unsafe blocks with justification
2. FFI boundary review identifies any potential memory safety issues
3. Input validation exists in all modules that process external data
4. Error handling does not leak sensitive information
5. Logging does not expose passwords, templates, or biometric data
</success_criteria>
<output>
After completion, create `.planning/phases/02-rust-code-security-review/02-02-SUMMARY.md`
</output>

View File

@@ -1,119 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 02
subsystem: security-review
tags: [rust, security, unsafe, ffi, input-validation, error-handling, logging]
# Dependency graph
requires:
- phase: 02-rust-code-security-review
provides: Security tooling results (cargo-audit, clippy, Miri)
provides:
- Unsafe code inventory with justifications
- FFI boundary security analysis
- Input validation gaps documentation
- Error handling security review
- Logging security review
affects: [03-biometric-security-review, 04-crypto-implementation]
# Tech tracking
tech-stack:
added: []
patterns: [security-review, manual-code-audit]
key-files:
created:
- .planning/phases/02-rust-code-security-review/unsafe-inventory.md
- .planning/phases/02-rust-code-security-review/ffi-review.md
- .planning/phases/02-rust-code-security-review/input-validation-review.md
- .planning/phases/02-rust-code-security-review/error-handling-review.md
- .planning/phases/02-rust-code-security-review/logging-review.md
key-decisions:
- "Unsafe code is minimal and well-justified (11 blocks total)"
- "FFI boundaries properly handle errors and null pointers"
- "Input validation is present with minor improvements recommended"
- "Error messages designed to not leak sensitive information"
- "Logging follows security best practices"
# Metrics
duration: 5 min
completed: 2026-02-14
---
# Phase 2 Plan 2: Manual Code Security Review Summary
**Manual Rust code review completed - 5 security review documents created covering unsafe code, FFI boundaries, input validation, error handling, and logging**
## Performance
- **Duration:** ~5 min
- **Started:** 2026-02-14T10:17:19Z
- **Completed:** 2026-02-14T11:23:11Z
- **Tasks:** 5
- **Files created:** 5
## Accomplishments
- Created comprehensive unsafe code inventory documenting all 11 unsafe blocks with justifications and risk levels
- Verified FFI boundaries (SO_PEERCRED, getpwnam, mlock/munlock) have proper error handling
- Reviewed input validation across IPC, config, camera, D-Bus, and template storage modules
- Confirmed error handling doesn't leak sensitive information
- Verified logging doesn't expose credentials, templates, or biometric data
## Task Commits
Each task was committed atomically:
1. **Task 1: Unsafe code inventory** - `8c058c8` (docs)
2. **Task 2: FFI boundary review** - `dee7999` (docs)
3. **Task 3: Input validation review** - `1eb454d` (docs)
4. **Task 4: Error handling review** - `9734d88` (docs)
5. **Task 5: Logging review** - `7cbe13f` (docs)
**Plan metadata:** (docs commit - see below)
## Files Created/Modified
- `unsafe-inventory.md` - Complete inventory of 11 unsafe blocks across ipc.rs, secure_memory.rs, camera/linux.rs
- `ffi-review.md` - FFI boundary security analysis finding all properly handled
- `input-validation-review.md` - Input validation gaps with minor recommendations
- `error-handling-review.md` - Error message security analysis
- `logging-review.md` - Logging security best practices verification
## Decisions Made
- Unsafe code is minimal and follows Rust best practices
- All FFI boundaries properly check return values and handle errors
- IPC has proper message size limits (64KB) and rate limiting (10/sec)
- Error messages designed with security in mind (documented in error.rs)
- Logging doesn't expose sensitive data at info/warn/error levels
## Deviations from Plan
None - plan executed exactly as written.
All five review tasks completed as specified:
1. ✅ Unsafe code inventory documents 11 blocks with justifications
2. ✅ FFI boundary review identifies no memory safety issues
3. ✅ Input validation reviewed with minor recommendations documented
4. ✅ Error handling verified as secure
5. ✅ Logging verified as secure
## Issues Encountered
None - all tasks completed successfully.
## User Setup Required
None - no external service configuration required.
## Next Phase Readiness
- Manual security review complete for Phase 2
- Ready for Phase 3: Biometric Security Review
- All security documents created and committed
---
*Phase: 02-rust-code-security-review*
*Completed: 2026-02-14*

View File

@@ -1,189 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 03
type: execute
wave: 1
depends_on: []
files_modified: []
autonomous: true
user_setup: []
must_haves:
truths:
- "SO_PEERCRED validation is properly implemented in IPC layer"
- "Authorization boundaries are enforced for all IPC operations"
- "Rate limiting prevents brute-force attacks (verified via test)"
- "Message size limits prevent buffer overflow attacks"
artifacts:
- path: ".planning/phases/02-rust-code-security-review/ipc-security-verification.md"
provides: "Complete IPC security verification report"
---
<objective>
Verify IPC security features are properly implemented
Purpose: Confirm SO_PEERCRED, authorization, rate limiting, and message size limits are correctly implemented and effective
Output: IPC security verification report
</objective>
<execution_context>
@/home/eliott/.config/opencode/get-shit-done/workflows/execute-plan.md
</execution_context>
<context>
@.planning/ROADMAP.md
@.planning/phases/02-rust-code-security-review/02-RESEARCH.md
@linux-hello-daemon/src/ipc.rs
</context>
<tasks>
<task type="auto">
<name>Task 1: Verify SO_PEERCRED validation</name>
<files>.planning/phases/02-rust-code-security-review/ipc-security-verification.md</files>
<action>
Verify SO_PEERCRED implementation in ipc.rs:
1. Read ipc.rs to find SO_PEERCRED usage (around lines 88-116)
2. Verify the implementation:
- Uses libc::getsockopt with SO_PEERCRED option
- Properly structures sockaddr_u or peercred structure
- Extracts pid, uid, gid from peer credentials
3. Verify validation:
- SO_PEERCRED result is checked for errors
- Peer credentials are used for authorization decisions
4. Document findings:
- Implementation is correct
- Or issues found with proposed fixes
</action>
<verify>
Code review of SO_PEERCRED implementation complete
</verify>
<done>
SO_PEERCRED validation verified - properly implemented
</done>
</task>
<task type="auto">
<name>Task 2: Review authorization boundaries</name>
<files>.planning/phases/02-rust-code-security-review/ipc-security-verification.md</files>
<action>
Verify authorization model in ipc.rs:
1. Find authorization logic (around lines 123-149)
2. Verify the model:
- Root (UID 0) has full access
- Regular users can only operate on their own account
- Username to UID mapping uses getpwnam correctly
- Null returns from getpwnam are handled
3. Check all IPC methods for authorization:
- Register/template operations
- Authentication operations
- Delete operations
4. Verify authorization checks:
- Are applied to ALL operations
- Cannot be bypassed
Document findings.
</action>
<verify>
Code review of authorization logic complete
</verify>
<done>
Authorization boundaries verified - properly enforced
</done>
</task>
<task type="auto">
<name>Task 3: Verify rate limiting implementation</name>
<files>.planning/phases/02-rust-code-security-review/ipc-security-verification.md</files>
<action>
Verify rate limiting implementation in ipc.rs:
1. Find rate limiter implementation (around lines 152-242)
2. Verify the configuration:
- Rate limit: 10 connections/second per UID (as documented)
- Backoff: Exponential (5s → 60s max)
- Cleanup: After 60s of inactivity
3. Verify implementation:
- Token bucket or sliding window algorithm
- Per-UID tracking (not global)
- Proper cleanup to prevent memory leaks
4. Verify effectiveness:
- Write a simple test script to verify rate limiting
- Or verify test exists in test suite
Document findings.
</action>
<verify>
Code review and test of rate limiter complete
</verify>
<done>
Rate limiting verified - prevents brute-force attacks
</done>
</task>
<task type="auto">
<name>Task 4: Check message size limits</name>
<files>.planning/phases/02-rust-code-security-review/ipc-security-verification.md</files>
<action>
Verify message size limit implementation in ipc.rs:
1. Find MAX_MESSAGE_SIZE definition (should be 64KB)
2. Find message size validation (around lines 71, 492-521)
3. Verify:
- MAX_MESSAGE_SIZE = 65536 (64KB) is defined
- Pre-read validation checks message size BEFORE parsing
- Size check happens BEFORE buffer allocation
- Rejects oversized messages properly
4. Check all receive paths:
- Unix socket recv
- Any other message entry points
5. Verify:
- Cannot trigger buffer overflow via oversized messages
- Memory allocation is bounded
Document findings.
</action>
<verify>
Code review of message size limits complete
</verify>
<done>
Message size limits verified - prevents buffer overflow attacks
</done>
</task>
</tasks>
<verification>
All four IPC security features verified:
- SO_PEERCRED validation correct
- Authorization boundaries enforced
- Rate limiting working
- Message size limits enforced
</verification>
<success_criteria>
1. SO_PEERCRED validation is properly implemented in IPC layer
2. Authorization boundaries are enforced for all IPC operations
3. Rate limiting prevents brute-force attacks (verified via test)
4. Message size limits prevent buffer overflow attacks
</success_criteria>
<output>
After completion, create `.planning/phases/02-rust-code-security-review/02-03-SUMMARY.md`
</output>

View File

@@ -1,96 +0,0 @@
---
phase: 02-rust-code-security-review
plan: 03
subsystem: security
tags: [ipc, socket-security, authorization, rate-limiting]
# Dependency graph
requires:
- phase: 02-rust-code-security-review
provides: Previous code review findings and unsafe block inventory
provides:
- IPC security verification report documenting SO_PEERCRED, authorization, rate limiting, message size limits
affects: [03-crypto-audit, 05-integration-testing]
# Tech tracking
added: []
patterns:
- "SO_PEERCRED for Unix socket peer credential validation"
- "Per-UID rate limiting with exponential backoff"
- "Pre-read message size validation"
key-files:
created: [.planning/phases/02-rust-code-security-review/ipc-security-verification.md]
modified: [linux-hello-daemon/src/ipc.rs]
key-decisions:
- "All four IPC security features are properly implemented and effective"
patterns-established:
- "Authorization model: Root (UID 0) has full access, regular users limited to own account"
- "Rate limiting: 10 req/sec per UID with exponential backoff"
- "Message validation: 64KB max with pre-read size checks"
# Metrics
duration: 1min
completed: 2026-02-14
---
# Phase 2 Plan 3: IPC Security Verification Summary
**SO_PEERCRED, authorization, rate limiting, and message size limits verified in IPC layer**
## Performance
- **Duration:** 1 min
- **Started:** 2026-02-14T10:26:13Z
- **Completed:** 2026-02-14T10:27:44Z
- **Tasks:** 4
- **Files modified:** 1 (verification report created)
## Accomplishments
- Verified SO_PEERCRED validation uses getsockopt with proper error handling
- Confirmed authorization boundaries enforce root has full access, users limited to own account
- Validated rate limiting implementation: 10 req/sec per UID with exponential backoff
- Confirmed message size limits prevent buffer overflow: 64KB max with pre-read validation
## Task Commits
Each task was verified and documented in the security report:
1. **Task 1: Verify SO_PEERCRED validation** - `14ca9b3` (security)
2. **Task 2: Review authorization boundaries** - `14ca9b3` (security)
3. **Task 3: Verify rate limiting implementation** - `14ca9b3` (security)
4. **Task 4: Check message size limits** - `14ca9b3` (security)
**Plan metadata:** `14ca9b3` (docs: verify IPC security features)
## Files Created/Modified
- `.planning/phases/02-rust-code-security-review/ipc-security-verification.md` - Complete IPC security verification report with analysis of all four security features
## Decisions Made
- All IPC security features are properly implemented and require no fixes
- The codebase demonstrates security-conscious design patterns
## Deviations from Plan
None - plan executed exactly as written.
## Issues Encountered
None
## Next Phase Readiness
- IPC security verification complete
- Ready for Phase 3: Cryptographic Implementation Audit
- No blockers identified
---
*Phase: 02-rust-code-security-review*
*Completed: 2026-02-14*
## Self-Check: PASSED
- [x] SUMMARY.md created at .planning/phases/02-rust-code-security-review/02-03-SUMMARY.md
- [x] ipc-security-verification.md created at .planning/phases/02-rust-code-security-review/ipc-security-verification.md
- [x] Commit 14ca9b3 exists (task verification)
- [x] Commit 207111c exists (plan metadata)

View File

@@ -1,287 +0,0 @@
# Phase 2: Rust-Specific Code Security Review - Research
**Researched:** 2026-02-14
**Domain:** Rust Security Audit - Code Review and Tooling
**Confidence:** HIGH
## Summary
This phase focuses on running security tooling (cargo-audit, cargo-deny, clippy, Miri) and manually reviewing code for Rust-specific vulnerabilities in Linux Hello. The codebase has identified unsafe code blocks in 3 main files (ipc.rs, secure_memory.rs, camera/linux.rs) that require Miri testing and manual review. The IPC layer already implements key security features (SO_PEERCRED, rate limiting, message size limits, authorization boundaries) that should be verified. Error handling and logging patterns appear security-conscious but require verification.
**Primary recommendation:** Run security tooling in order: cargo-audit (dependencies) → cargo-deny (policy) → clippy (static analysis) → Miri (unsafe code). Manual review should focus on the 12 identified unsafe blocks and IPC security verification.
<user_constraints>
## User Constraints (from CONTEXT.md)
No CONTEXT.md exists yet - this is initial planning for Phase 2.
### Phase Requirements (from phase description)
**Tool Requirements:**
- TOOL-01: Run cargo-audit to find dependency vulnerabilities
- TOOL-02: Run cargo-deny to enforce security policies
- TOOL-03: Run clippy for code quality/security lints
- TOOL-04: Run Miri on unsafe code blocks
**Code Review Requirements:**
- CODE-01: Inventory all unsafe code blocks
- CODE-02: Review FFI boundaries for security
- CODE-03: Check input validation in all modules
- CODE-04: Verify error handling doesn't leak information
- CODE-05: Review logging for sensitive data exposure
**IPC Security Requirements:**
- IPC-01: Verify SO_PEERCRED validation
- IPC-02: Review authorization boundaries
- IPC-03: Verify rate limiting implementation
- IPC-04: Check message size limits
</user_constraints>
## Standard Stack
### Security Audit Tools
| Tool | Version | Purpose | Why Standard |
|------|---------|---------|--------------|
| cargo-audit | 0.10+ | Scans Cargo.lock for vulnerabilities | Official RustSec tool - essential first step |
| cargo-deny | 0.14+ | Policy enforcement (bans, licenses, sources) | Integrates into build process |
| clippy | Stable (750+ lints) | Static analysis, security lints | Part of Rust toolchain |
| Miri | Nightly | Undefined behavior detection | Official Rust project - essential for unsafe |
### Installation
```bash
# Core tools
cargo install cargo-audit --locked
cargo install cargo-deny
rustup +nightly component add miri
# Run audits
cargo audit # Dependency vulnerabilities
cargo deny check # Policy enforcement
cargo clippy --all-targets -- -D warnings # Static analysis
cargo +nightly miri test # Undefined behavior (nightly only)
```
## Architecture Patterns
### Project Structure
```
linux-hello-daemon/src/
├── ipc.rs # Unix socket IPC - SECURITY CRITICAL
├── secure_memory.rs # Secure data handling - UNSAFE BLOCKS
├── secure_template_store.rs # Encrypted storage
├── tpm.rs # TPM integration - FFI boundary
├── camera/linux.rs # Camera V4L2 - UNSAFE BLOCKS
├── auth.rs # Authentication logic
├── anti_spoofing.rs # Liveness detection
└── dbus_service.rs # D-Bus interface
linux-hello-common/src/
├── error.rs # Error types
├── config.rs # Configuration
└── template.rs # Data types
```
### Unsafe Code Inventory (Pre-identified)
| File | Lines | Purpose | Risk Level |
|------|-------|---------|------------|
| `ipc.rs` | 94-105 | SO_PEERCRED socket option | MEDIUM |
| `ipc.rs` | 142-147 | getpwnam FFI | MEDIUM |
| `secure_memory.rs` | 74-79 | Slice from_raw_parts | LOW |
| `secure_memory.rs` | 293-296 | ptr::write_volatile | LOW |
| `secure_memory.rs` | 304-307 | ptr::write_volatile | LOW |
| `secure_memory.rs` | 318 | libc::mlock | LOW |
| `secure_memory.rs` | 339-340 | libc::munlock | LOW |
| `camera/linux.rs` | 192-194 | Stream lifetime extension | HIGH |
| `camera/linux.rs` | 198 | std::mem::transmute | HIGH |
### IPC Security Implementation (Already Present)
The codebase already implements key IPC security features:
1. **SO_PEERCRED** (ipc.rs:88-116)
- Uses `libc::getsockopt` with `SO_PEERCRED` to get client PID, UID, GID
- Validates peer identity for all operations
2. **Authorization Model** (ipc.rs:123-149)
- Root (UID 0): Full access
- Regular users: Can only operate on their own account
- Uses `getpwnam` for username→UID mapping
3. **Rate Limiting** (ipc.rs:152-242)
- 10 connections/second per UID
- Exponential backoff on failures (5s → 60s max)
- Auto-cleanup after 60s
4. **Message Size Limits** (ipc.rs:71, 492-521)
- MAX_MESSAGE_SIZE = 64KB
- Pre-read validation before parsing
5. **Socket Permissions** (ipc.rs:401-409)
- 0o600 (owner only)
## Don't Hand-Roll
| Problem | Don't Build | Use Instead | Why |
|---------|-------------|-------------|-----|
| Dependency vulnerability scanning | Custom scripts | cargo-audit | RustSec database, auto-updates |
| Policy enforcement | Build script checks | cargo-deny | Integrated, comprehensive |
| Constant-time comparison | Manual implementation | `subtle` crate | Audited, tested |
| Secure memory | Custom zeroization | `zeroize` crate | Well-audited, battle-tested |
| Memory locking | Custom mlock wrapper | Already implemented | Works correctly |
**Key insight:** The project already uses well-audited crates (zeroize, subtle) for security-sensitive operations. Continue using these rather than building custom solutions.
## Common Pitfalls
### Tooling Pitfalls
1. **Miri limitations**
- Doesn't support networking (use `-Zmiri-disable-isolation` carefully)
- Slow execution - run on specific tests first
- Doesn't work with native/C-rate libraries (PAM module)
- Requires nightly toolchain
2. **Clippy false positives**
- Security code may trigger `clippy::dangerous_literal` - review individually
- May need to allow specific lints in security-critical code
3. **cargo-audit ignoring**
- Don't just ignore advisories - evaluate if they affect your security model
- Document why each ignore is acceptable
### Code Review Pitfalls
1. **Unsafe block review**
- Every unsafe block must have a safety comment explaining invariants
- Verify unsafe blocks in camera/linux.rs don't cause UB
2. **Error message leakage**
- Error messages should not expose internal paths, crypto details
- Current error.rs appears designed for this - verify during review
3. **Logging sensitive data**
- Check all tracing calls don't log embeddings, templates, credentials
- Look for debug logs that might expose biometric data
4. **FFI boundary vulnerabilities**
- getpwnam can return null - already handled with null check ✓
- Verify SO_PEERCRED error handling
## Code Examples
### Running Security Tools in Order
```bash
# 1. Dependency vulnerability audit
cargo audit
# 2. Policy enforcement
cargo deny check
# 3. Clippy with strict warnings
cargo clippy --all-targets -- -D warnings -W clippy::all
# 4. Miri on specific crate (requires nightly)
cargo +nightly miri test -p linux-hello-daemon
# 5. Miri on specific test
cargo +nightly miri test -p linux-hello-daemon secure_memory
```
### Security-Relevant Clippy Lints
Run these specifically for security review:
```bash
# Memory safety
cargo clippy -- -W clippy::dangling_pointer
cargo clippy -- -W clippy::mem_forget
cargo clippy -- -W clippy::unsafe_derive_deserialize
# Cryptography
cargo clippy -- -W clippy::expect_used
cargo clippy -- -W clippy::unwrap_used
# Concurrency
cargo clippy -- -W clippy::await_holding_lock
cargo clippy -- -W clippy::arc_with_non_send_sync
```
### Miri Flags for Security Testing
```bash
# Run with stacked borrows (default, recommended)
MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test
# Disable isolation to test file I/O
MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test
# Run multiple seeds for concurrency testing
MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test
```
## State of the Art
| Old Approach | Current Approach | When Changed | Impact |
|--------------|------------------|--------------|--------|
| Manual dependency review | cargo-audit automated scans | Standard since 2019 | Catches vulnerabilities automatically |
| Build script policy | cargo-deny integrated | Standard since 2020 | Enforces policy at build time |
| Guess unsafe code | Miri explicit testing | Standard since 2018 | Catches UB in unsafe blocks |
| Basic clippy | 750+ specialized lints | Continuous | Catches more code issues |
**Current best practice:** Layer multiple tools - no single tool catches everything.
**Deprecated/outdated:**
- `rustsec` crate (replaced by cargo-audit binary)
- Manual audit scripts (replaced by cargo-deny)
## Open Questions
1. **PAM module C code review**
- The PAM module (`pam_linux_hello.c`) is C code not covered by Rust tooling
- Need separate security review for C code
- Recommendation: Use cppcheck or manual review
2. **Miri with ONNX feature**
- Miri doesn't support native libraries (ort)
- Need to test without ONNX feature: `cargo +nightly miri test --no-default-features`
- ONNX code requires different testing approach (integration tests)
3. **Fuzzing after initial review**
- Phase 2 focuses on tooling + manual review
- Fuzzing (cargo-fuzz) could be added in follow-up
- Priority: Template parsing, IPC message parsing
## Sources
### Primary (HIGH confidence)
- https://rustsec.org/ - Official Rust security advisories
- https://github.com/rustsec/rustsec/tree/main/cargo-audit - cargo-audit docs
- https://embarkstudios.github.io/cargo-deny/ - cargo-deny docs
- https://github.com/rust-lang/miri - Miri undefined behavior detector
- https://doc.rust-lang.org/clippy/ - Clippy lints (750+)
### Secondary (HIGH confidence)
- STACK.md - Previously researched security tooling stack
- linux-hello-daemon/src/ipc.rs - IPC implementation with security features
- linux-hello-daemon/src/secure_memory.rs - Secure memory implementation
- linux-hello-common/src/error.rs - Error handling
### Code Inspection
- Unsafe blocks identified via grep - 12 total across 3 files
- IPC security features documented in ipc.rs module docs
- Logging patterns analyzed via grep tracing::
## Metadata
**Confidence breakdown:**
- Standard stack: HIGH - All tools well-documented, standard Rust ecosystem tools
- Architecture: HIGH - Code structure analyzed directly, unsafe blocks identified
- Pitfalls: HIGH - Based on official documentation and code review
**Research date:** 2026-02-14
**Valid until:** 30 days for stable tools (cargo-audit, cargo-deny, clippy), 7 days for Miri (nightly-dependent)

View File

@@ -1,74 +0,0 @@
# Clippy Results
**Date:** 2026-02-14
**Tool:** cargo-clippy 1.92.0
## Summary
| Status | Warnings |
|--------|----------|
| PASS (with warnings) | Multiple style warnings |
Clippy runs successfully. No security-related warnings found. All warnings are code style issues.
## Security-Relevant Lints Check
Checked the following security-relevant lints:
| Lint Category | Status | Notes |
|---------------|--------|-------|
| `dangling_pointer` | PASS | No issues |
| `mem_forget` | PASS | No issues |
| `unsafe_derive_deserialize` | PASS | No issues |
| `expect_used` | PASS | No critical issues |
| `unwrap_used` | PASS | No critical issues |
| `await_holding_lock` | PASS | No issues |
| `arc_with_non_send_sync` | PASS | No issues |
## Warnings Found (Style Only)
### linux-hello-daemon
| Warning | File | Line | Severity |
|---------|------|------|----------|
| `needless_range_loop` | anti_spoofing.rs | 711 | style |
| `field_reassign_with_default` | anti_spoofing.rs | 769, 811 | style |
| `field_reassign_with_default` | benchmarks.rs | 302 | style |
| `useless_vec` | matching.rs | 250, 255 | style |
| `unused_imports` | examples/tpm_test.rs | 8 | style |
### linux-hello-tests
| Warning | File | Line | Severity |
|---------|------|------|----------|
| `useless_vec` | phase2_auth_test.rs | 186, 192, 196 | style |
| `field_reassign_with_default` | phase3_security_test.rs | 300, 325, 346 | style |
## Fixed Issues
During the scan, the following issues were fixed to make clippy pass:
1. **config.rs** - Added `Default` derive to `Config` struct, removed manual implementation
2. **template.rs** - Simplified iterator using `.flatten()`
3. **camera/linux.rs** - Added transmute type annotations
4. **ipc.rs** - Renamed `default()` to `with_default_path()` to avoid trait confusion
5. **ipc.rs** - Simplified redundant closures
6. **secure_memory.rs** - Used `is_multiple_of(4)` instead of `% 4 != 0`
7. **camera/mod.rs** - Added allow directive for unused imports
8. **camera/linux.rs** - Fixed doc comment syntax (`//!` not `/!`)
9. **tests/phase3_security_test.rs** - Used `std::f32::consts::PI` instead of literal
## Recommendations
These warnings are all style-related and don't affect security. Options:
1. **Ignore** - These are minor style issues, clippy passes
2. **Fix** - Run `cargo clippy --fix` to auto-apply suggestions
3. **Allowlist** - Add `#[allow(clippy::...)]` directives for intentional patterns
## Notes
- No security-relevant clippy warnings found
- The codebase follows good security practices
- Unsafe blocks are properly documented with safety comments
- No deprecated or unsafe patterns detected in crypto code

View File

@@ -1,99 +0,0 @@
# Cargo Deny Results
**Date:** 2026-02-14
**Tool:** cargo-deny v0.19.0
## Summary
| Check | Status |
|-------|--------|
| Licenses | FAILED - Multiple crates rejected |
| Security Advisories | WARN - No config found |
| Bans | WARN - No config found |
| Sources | WARN - No config found |
| Duplicates | Not checked - Config missing |
## Issues Found
### 1. License Check Failures
The project has no `deny.toml` configuration file, so cargo-deny is using its default policy which is very restrictive. The following license categories are causing failures:
**Failing licenses (not in allowlist):**
- MIT OR Apache-2.0 (many crates)
- Apache-2.0 OR MIT (many crates)
- BSD-3-Clause
- MIT/Apache-2.0
- Apache-2.0/MIT
- Zlib OR Apache-2.0 OR MIT
- Unlicense OR MIT
- MIT (standalone)
- BSD-2-Clause
**Affected critical dependencies:**
- `aes-gcm v0.10.3` (encryption - MIT OR Apache-2.0)
- `aes v0.8.4` (encryption - MIT OR Apache-2.0)
- `aead v0.5.2` (AEAD - MIT OR Apache-2.0)
- `tokio` ecosystem (async runtime - various MIT/Apache)
- `zbus` (D-Bus - Apache-2.0 OR MIT)
- `image` (image processing - MIT/Apache-2.0)
- `tss-esapi` (TPM - multiple licenses)
- `gtk4` ecosystem (MIT)
- `libadwaita` (MIT)
### 2. Configuration Missing
The project does not have a `deny.toml` configuration file. This is expected for initial projects - the security policy needs to be defined.
## Remediation Plan
### Option A: Create deny.toml with Permissive License Policy (Recommended)
Create a `deny.toml` that allows OSI-approved licenses commonly used in Rust ecosystem:
```toml
[licenses]
version = 2
allow = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"MPL-2.0",
"Unicode-3.0",
"Unlicense",
"Zlib",
]
[[licenses.clarify]]
name = "openssl"
expression = "Apache-2.0 OR Artistic-2.0"
license-files = [{ path = "LICENSE", hash = 0x00000000 }]
[licenses.allow-yanked]
version = "err"
```
### Option B: Use Existing Common Policy
Many Rust projects use the following permissive policy in deny.toml:
- Allow all OSI-approved licenses
- Allow FSF-approved licenses
- Only ban specific problematic licenses (e.g., GPL-2.0, SSPL)
## Actions Required
1. Create `deny.toml` in project root with appropriate license policy
2. Re-run `cargo deny check` to verify configuration
3. Document license policy in project documentation
4. Commit deny.toml to repository
## Notes
- All rejected licenses are OSI-approved and commonly used in Rust ecosystem
- These are false positives due to missing configuration
- The cryptography crates (aes-gcm, aes, aead) are essential for the project
- GTK/Adwaita dependencies are required for the settings app
- After creating deny.toml, cargo-deny should pass

View File

@@ -1,149 +0,0 @@
# Error Handling Security Review
## Overview
This document reviews error messages and handling to ensure they don't leak sensitive information like file paths, cryptographic keys, templates, or user credentials.
## Error Type Analysis
### Error Types in error.rs
| Error Type | Message Pattern | Potential Leakage |
|------------|-----------------|------------------|
| `AuthenticationFailed` | "Authentication failed" | None - generic |
| `UserNotEnrolled(String)` | "User not enrolled: {0}" | Username exposed |
| `Camera(String)` | "Camera error: {0}" | System error details |
| `Detection(String)` | "Face detection error: {0}" | Model/directory paths |
| `ModelLoad(String)` | "Model loading error: {0}" | File paths |
| `Config(String)` | "Configuration error: {0}" | Config details |
| `Tpm(String)` | "TPM error: {0}" | TPM-specific info |
| `Io(std::io::Error)` | "IO error: {0}" | File paths |
| `Serialization(String)` | "Serialization error: {0}" | JSON details |
---
## Security Analysis by Category
### 1. Authentication Errors
**File:** `linux-hello-daemon/src/auth.rs`
**Finding:** ✅ SECURE
- `AuthenticationFailed` - Returns generic message, doesn't reveal if user exists
- `UserNotEnrolled(String)` - Exposes username, but username is generally not sensitive
- No information leakage about template data or matching scores in error messages
**Code:**
```rust
return Err(linux_hello_common::Error::UserNotEnrolled(user.to_string()));
return Err(linux_hello_common::Error::AuthenticationFailed);
```
---
### 2. Camera/Device Errors
**File:** `linux-hello-daemon/src/camera/linux.rs`
**Potential Issue:** ⚠️ MINOR
Some error messages include device paths:
```rust
Error::Camera(format!("Invalid device path: {}", device_path))
Error::Camera(format!("Failed to open device: {}", e))
```
**Analysis:**
- Device paths like `/dev/video0` are system information, not highly sensitive
- Leaking `/dev/video0` doesn't compromise security
- Standard practice in Linux applications
**Risk:** LOW
---
### 3. Template Storage Errors
**Finding:** ✅ SECURE
- Errors don't expose template data or encryption keys
- Generic messages like "User not enrolled" used
- No template contents in error messages
---
### 4. Crypto/TPM Errors
**File:** `linux-hello-daemon/src/tpm.rs`
**Finding:** ⚠️ INFORMATIONAL
TPM errors include detailed messages:
```rust
Error::Tpm(format!("Failed to create TPM context: {}", e))
Error::Tpm(format!("Failed to load primary key: {}", e))
```
**Analysis:**
- These errors are technical but don't expose key material
- They describe *what* failed, not sensitive data
- TPM errors are usually only visible to admins
**Risk:** LOW
---
### 5. Logging vs Error Messages
**Key Distinction:** Error messages are what the user/consumer sees. Logging is what appears in logs.
**Logging Analysis:**
| Location | Level | Content | Risk |
|----------|-------|---------|------|
| auth.rs:59 | warn | "User {} is not enrolled" | LOW - audit info |
| auth.rs:74 | warn | "Anti-spoofing check failed for user {}" | LOW - audit info |
| auth.rs:85-88 | debug | Match similarity score | LOW - debug only |
**Finding:** ✅ ACCEPTABLE
Debug-level logging of similarity scores is acceptable - it's behind a debug flag and doesn't go to users.
---
## Summary of Findings
### No Leakage Found
| Category | Status | Notes |
|----------|--------|-------|
| Authentication | ✅ SECURE | Generic errors, doesn't reveal user existence |
| Templates | ✅ SECURE | No template data in errors |
| Crypto keys | ✅ SECURE | Key material never exposed |
| Matching scores | ✅ SECURE | Not in error messages |
### Minor Issues Found
| Issue | Location | Risk | Recommendation |
|-------|----------|------|----------------|
| Device path in errors | camera/linux.rs | LOW | Acceptable - system info |
| Username in errors | auth.rs, error.rs | LOW | Acceptable - not sensitive |
| Debug logging | auth.rs | LOW | Acceptable - debug only |
---
## Conclusion
**Overall Assessment:** ✅ SECURE
The error handling is designed with security in mind:
1. Generic `AuthenticationFailed` error doesn't reveal if user exists
2. No template or embedding data in error messages
3. No cryptographic key material exposed
4. Debug logging is appropriately gated
The codebase follows the security principle documented in error.rs:
> "Error messages intentionally avoid including sensitive information like internal paths or cryptographic details to prevent information disclosure."
**Risk Level:** LOW - No actionable security issues found.

View File

@@ -1,209 +0,0 @@
# FFI Boundary Security Review
## Overview
This document reviews all Foreign Function Interface (FFI) boundaries in the Linux Hello codebase to identify potential memory safety issues and security vulnerabilities.
## FFI Boundaries Identified
### 1. IPC - SO_PEERCRED Socket Option
**File:** `linux-hello-daemon/src/ipc.rs:90-116`
**Purpose:** Retrieve peer credentials (PID, UID, GID) from connected Unix socket
**Code Reviewed:**
```rust
pub fn from_stream(stream: &UnixStream) -> Result<Self> {
let fd = stream.as_raw_fd();
let mut ucred: libc::ucred = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
let ret = unsafe {
libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_PEERCRED,
&mut ucred as *mut _ as *mut libc::c_void,
&mut len,
)
};
if ret != 0 {
return Err(Error::Io(std::io::Error::last_os_error()));
}
// ...
}
```
**Security Analysis:**
| Aspect | Status | Notes |
|--------|--------|-------|
| Zeroed initialization | ✅ SAFE | `ucred` is immediately overwritten by getsockopt |
| Pointer casting | ✅ SAFE | Standard pattern for syscall wrappers |
| Return value check | ✅ SAFE | `ret != 0` checked, error converted to Result |
| Null pointer handling | ✅ N/A | No pointer returns from this call |
| Buffer bounds | ✅ SAFE | Fixed size struct `libc::ucred` |
**Finding:** No issues. Proper error handling and safe patterns used.
---
### 2. IPC - getpwnam User Lookup
**File:** `linux-hello-daemon/src/ipc.rs:138-149`
**Purpose:** Look up user UID by username for authorization
**Code Reviewed:**
```rust
fn get_uid_for_username(username: &str) -> Option<u32> {
use std::ffi::CString;
let c_username = CString::new(username).ok()?;
let passwd = unsafe { libc::getpwnam(c_username.as_ptr()) };
if passwd.is_null() {
None
} else {
Some(unsafe { (*passwd).pw_uid })
}
}
```
**Security Analysis:**
| Aspect | Status | Notes |
|--------|--------|-------|
| Input validation | ✅ SAFE | `CString::new(username).ok()?` ensures null-terminated |
| Null return check | ✅ SAFE | `passwd.is_null()` checked before dereference |
| Field access | ✅ SAFE | Only `pw_uid` accessed after null check |
| Memory ownership | ✅ SAFE | No ownership transferred, C string freed by CString |
**Finding:** No issues. Proper null checking and input validation.
---
### 3. Secure Memory - mlock/munlock
**File:** `linux-hello-daemon/src/secure_memory.rs:315-343`
**Code Reviewed:**
```rust
#[cfg(target_os = "linux")]
pub fn lock_memory(data: &[u8]) -> Result<bool> {
use std::ffi::c_void;
let result = unsafe { libc::mlock(data.as_ptr() as *const c_void, data.len()) };
if result == 0 {
Ok(true)
} else {
tracing::warn!("Failed to lock memory: {}", std::io::Error::last_os_error());
Ok(false)
}
}
#[cfg(target_os = "linux")]
pub fn unlock_memory(data: &[u8]) -> Result<()> {
use std::ffi::c_void;
unsafe {
libc::munlock(data.as_ptr() as *const c_void, data.len());
}
Ok(())
}
```
**Security Analysis:**
| Aspect | Status | Notes |
|--------|--------|-------|
| Pointer validity | ✅ SAFE | `data.as_ptr()` is valid for the slice length |
| Length | ✅ SAFE | `data.len()` matches slice length |
| mlock return check | ✅ SAFE | Return value checked, graceful degradation |
| munlock return | ✅ ACCEPTABLE | Return ignored - failure to unlock is not security issue |
**Finding:** No issues. Proper pointer handling and error handling. The munlock return value is intentionally ignored because failure to unlock is not a security concern (memory will be freed on process exit anyway).
---
### 4. TPM2 API Calls (Feature-gated)
**File:** `linux-hello-daemon/src/tpm.rs`
**Analysis:**
- Uses `tss-esapi` crate (official TPM2 Software Stack)
- High-level Rust bindings, not direct FFI
- All unsafe operations contained within the library
- No direct `libc::` calls in this module
**Security Analysis:**
| Aspect | Status | Notes |
|--------|--------|-------|
| Direct FFI | ✅ NONE | Uses tss-esapi safe abstractions |
| Error handling | ✅ VERIFIED | TPM return codes converted to Result |
| Session management | ✅ VERIFIED | Session handles properly managed |
| Memory safety | ✅ VERIFIED | Library handles all memory |
**Finding:** No issues. TPM operations use safe high-level API.
---
### 5. Camera - V4L2 ioctl Calls
**File:** `linux-hello-daemon/src/camera/linux.rs`
**Analysis:**
- Uses `v4l` crate for V4L2 operations
- The crate wraps ioctl system calls in safe Rust
- Unsafe block in code is for lifetime extension, not ioctl
**Code Reviewed:**
```rust
let device_ptr = &self.device as *const Device;
let stream = unsafe {
Stream::with_buffers(&*device_ptr, Type::VideoCapture, 4)
// ...
};
```
**Security Analysis:**
| Aspect | Status | Notes |
|--------|--------|-------|
| Direct ioctl | ✅ NONE | v4l crate handles safely |
| Buffer bounds | ✅ VERIFIED | Crate manages buffer allocation |
| Stream lifetime | ⚠️ NOTE | Lifetime extension - see unsafe inventory |
**Finding:** No memory safety issues. The unsafe block is for lifetime extension, not V4L2 ioctl.
---
## Summary
### FFI Boundaries Reviewed
| Location | Purpose | Issues Found |
|----------|---------|--------------|
| ipc.rs:94-105 | SO_PEERCRED | None |
| ipc.rs:142-147 | getpwnam | None |
| secure_memory.rs:318 | mlock | None |
| secure_memory.rs:340 | munlock | None |
| tpm.rs | TPM2 API | None (uses safe bindings) |
| camera/linux.rs | V4L2 | None (uses safe crate) |
### Memory Safety Verification
All FFI boundaries:
- ✅ Use valid pointers with proper lifetime
- ✅ Check return values for errors
- ✅ Handle null returns appropriately
- ✅ Use appropriate integer types for system calls
- ✅ Don't leak memory or file descriptors
### Conclusion
**No memory safety issues found in FFI boundaries.** All unsafe operations are properly justified, documented, and have appropriate error handling. The codebase follows Rust FFI best practices.
**Risk Assessment:** LOW - All FFI boundaries are properly secured.

View File

@@ -1,192 +0,0 @@
# Input Validation Security Review
## Overview
This document reviews input validation across all modules that process external data to identify gaps in validation that could lead to security vulnerabilities.
## Modules Reviewed
1. IPC Message Parsing (ipc.rs)
2. Config Loading (config.rs)
3. Camera Input (camera/linux.rs)
4. D-Bus Interface (dbus_service.rs)
5. Template Storage (secure_template_store.rs)
---
## 1. IPC Message Parsing
**File:** `linux-hello-daemon/src/ipc.rs`
### Findings
| Aspect | Status | Notes |
|--------|--------|-------|
| Message size limits | ✅ SECURE | MAX_MESSAGE_SIZE = 64KB enforced |
| Rate limiting | ✅ SECURE | MAX_CONNECTIONS_PER_SECOND = 10 |
| Buffer allocation | ✅ SECURE | Pre-allocated buffer prevents exhaustion |
| Connection limits | ✅ SECURE | Rate limiter tracks per-UID |
**Code Evidence:**
```rust
const MAX_MESSAGE_SIZE: usize = 64 * 1024;
const MAX_CONNECTIONS_PER_SECOND: u32 = 10;
// In message handling:
let mut buffer = vec![0u8; MAX_MESSAGE_SIZE];
if n >= MAX_MESSAGE_SIZE {
// Reject oversized messages
}
```
**Finding:** No issues. Proper message size limits and rate limiting implemented.
---
## 2. Config Loading
**File:** `linux-hello-common/src/config.rs`
### Findings
| Aspect | Status | Notes |
|--------|--------|-------|
| Path validation | ⚠️ MINOR | Uses `AsRef<Path>` but no traversal check |
| Value bounds | ⚠️ MINOR | No explicit range validation |
| Deserialization | ✅ SECURE | Uses serde with type-safe parsing |
| Defaults | ✅ SECURE | Default values for all optional fields |
**Observations:**
- Config uses `#[serde(default)]` for all fields
- No explicit `validate()` method on Config struct
- Values like `timeout_seconds`, `resolution`, `fps` have no bounds checking
**Potential Improvement:**
Consider adding a `validate()` method to check:
- `timeout_seconds` > 0 and reasonable (e.g., < 300)
- `resolution` values are valid (e.g., > 0, < 8192)
- `fps` is reasonable (e.g., 1-120)
**Risk Assessment:** LOW - Config is typically admin-controlled, not user input.
---
## 3. Camera Input
**File:** `linux-hello-daemon/src/camera/linux.rs`
### Findings
| Aspect | Status | Notes |
|--------|--------|-------|
| Frame size validation | ✅ SECURE | V4L2 driver handles buffer allocation |
| Buffer bounds | ✅ SECURE | Crate manages buffer bounds |
| Device path | ⚠️ MINOR | Uses device path from enumeration |
| Error handling | ✅ SECURE | Errors propagated properly |
**Observations:**
- Camera device paths come from enumeration, not user input directly
- Frame capture uses V4L2 crate which handles buffer management safely
- No user-controllable size parameters
**Finding:** No issues. Camera input is controlled through enumeration.
---
## 4. D-Bus Interface
**File:** `linux-hello-daemon/src/dbus_service.rs`
### Findings
| Aspect | Status | Notes |
|--------|--------|-------|
| Parameter validation | ⚠️ NEEDS REVIEW | Should verify all D-Bus method params |
| Type conversion | ✅ SECURE | Uses zbus type conversions |
| Error handling | ✅ SECURE | Errors converted to proper types |
**Note:** This review recommends verifying D-Bus method handlers validate all string parameters.
---
## 5. Template Storage
**File:** `linux-hello-daemon/src/secure_template_store.rs`
### Findings
| Aspect | Status | Notes |
|--------|--------|-------|
| Path validation | ⚠️ POTENTIAL ISSUE | No path traversal check |
| File operations | ✅ SECURE | Uses standard filesystem APIs |
| Directory creation | ✅ SECURE | create_dir_all with user directory |
| Encryption | ✅ SECURE | AES-256-GCM encryption |
**Code Under Review:**
```rust
fn secure_template_path(&self, user: &str, label: &str) -> PathBuf {
self.base_path
.join(user)
.join(format!("{}.secure.json", label))
}
```
**Potential Issue:**
- No validation that `user` or `label` don't contain path traversal sequences (`../`, `..\\`)
- However, these values come from `FaceTemplate` struct set internally, not directly from D-Bus callers
**Recommendation:** Add validation:
```rust
fn validate_path_component(s: &str) -> bool {
!s.contains("..") && !s.contains('/') && !s.contains('\\') && !s.starts_with('.')
}
```
**Risk Assessment:** LOW-MEDIUM - Currently mitigated by internal API design, but defensive validation recommended.
---
## Unwrap/Expect Analysis
Searched for `unwrap()` and `expect()` in daemon code:
| Location | Count | Context |
|----------|-------|---------|
| Test code | ~50 | Expected in tests |
| Documentation | ~10 | Doc examples |
| Internal logic | ~30 | Invariant-guaranteed paths |
**Analysis:**
- Most unwraps are in test code or documentation
- Internal unwraps are on paths where the caller guarantees validity
- No exploitable unwrap-on-user-input patterns found
---
## Summary
### Input Validation Status
| Module | Validation Status | Risk |
|--------|------------------|------|
| IPC Message Parsing | ✅ Complete | LOW |
| Config Loading | ⚠️ Basic | LOW |
| Camera Input | ✅ Complete | LOW |
| D-Bus Interface | ⚠️ Needs review | LOW-MEDIUM |
| Template Storage | ⚠️ Recommend addition | LOW |
### Recommendations
1. **Medium Priority:** Add `validate()` method to Config struct for bounds checking
2. **Low Priority:** Add path traversal checks in `secure_template_path()`
3. **Low Priority:** Review D-Bus method handlers for parameter validation
### Overall Assessment
**Risk Level:** LOW
The codebase has good input validation practices:
- IPC has proper size limits and rate limiting
- Camera input is controlled through enumeration
- Most internal unwraps are on invariant-guaranteed paths
- Only minor improvements recommended

View File

@@ -1,223 +0,0 @@
# IPC Security Verification Report
**Phase:** 02-rust-code-security-review (Plan 02-03)
**Date:** 2026-02-14
**Target:** linux-hello-daemon/src/ipc.rs
---
## Task 1: SO_PEERCRED Validation
### Implementation Location
- `ipc.rs` lines 88-116: `PeerCredentials::from_stream`
### Verification Result: PASS
### Analysis
- Uses `libc::getsockopt` with `SOL_SOCKET` and `SO_PEERCRED` option
- Properly structures `libc::ucred` for peer credentials
- Extracts pid, uid, gid from peer credentials (lines 111-115)
- Error handling: Returns `Err(Error::Io(...))` if getsockopt fails (lines 107-109)
- Credentials are used for authorization decisions via `can_operate_on_user()`
### Code Reference
```rust
let ret = unsafe {
libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_PEERCRED,
&mut ucred as *mut _ as *mut libc::c_void,
&mut len,
)
};
if ret != 0 {
return Err(Error::Io(std::io::Error::last_os_error()));
}
```
### Conclusion
SO_PEERCRED validation is **properly implemented** with correct error handling.
---
## Task 2: Authorization Boundaries
### Implementation Location
- `ipc.rs` lines 123-149: `PeerCredentials::can_operate_on_user`
- Applied to: Enroll (line 584), List (line 635), Remove (line 677)
### Verification Result: PASS
### Analysis
1. **Root (UID 0) has full access:**
- Line 126-128: `if self.is_root() { return true; }`
2. **Regular users can only operate on their own account:**
- Lines 131-134: Uses `get_uid_for_username()` to look up target user's UID
- Compares peer UID with target UID
3. **Username to UID mapping uses getpwnam correctly:**
- Lines 138-149: `get_uid_for_username()` function
- Uses `libc::getpwnam` with proper CString conversion
4. **Null returns from getpwnam are handled:**
- Lines 144-145: `if passwd.is_null() { None }` - denies access if user doesn't exist
5. **Authorization checks applied to ALL operations:**
- Enroll: `if !peer_creds.can_operate_on_user(&user)` (line 584)
- List: `if !peer_creds.can_operate_on_user(&user)` (line 635)
- Remove: `if !peer_creds.can_operate_on_user(&user)` (line 677)
### Code Reference
```rust
pub fn can_operate_on_user(&self, target_username: &str) -> bool {
if self.is_root() {
return true;
}
// Look up the target user's UID
match Self::get_uid_for_username(target_username) {
Some(target_uid) => self.uid == target_uid,
None => false, // User doesn't exist, deny access
}
}
```
### Conclusion
Authorization boundaries are **properly enforced** for all IPC operations. Cannot be bypassed.
---
## Task 3: Rate Limiting Implementation
### Implementation Location
- `ipc.rs` lines 152-242: `RateLimiter` struct and methods
### Verification Result: PASS
### Analysis
1. **Configuration:**
- `MAX_CONNECTIONS_PER_SECOND = 10` (line 73)
- `RATE_LIMIT_BACKOFF = Duration::from_secs(5)` (line 77)
- Max backoff: 60 seconds (line 223)
- Cleanup: After 60 seconds of inactivity (lines 228-235)
2. **Algorithm:**
- Token bucket / sliding window approach (lines 168-207)
- Per-UID tracking (not global) - line 174: `self.connections.entry(uid)`
3. **Implementation:**
- `check_rate_limit()` method (lines 168-207): Enforces 10 req/sec limit
- `record_failure()` method (lines 210-226): Implements exponential backoff
- `cleanup_old_entries()` method (lines 228-235): Prevents memory leaks
4. **Integration:**
- Rate limit check happens before processing (lines 425-437)
- Failed auth attempts trigger backoff (lines 546-559)
### Code Reference
```rust
pub fn check_rate_limit(&mut self, uid: u32) -> std::result::Result<(), String> {
// ... cleanup old entries ...
if entry.0 > MAX_CONNECTIONS_PER_SECOND {
// Enter backoff period
entry.2 = Some(now + RATE_LIMIT_BACKOFF);
return Err(format!(
"Rate limit exceeded. Backing off for {} seconds",
RATE_LIMIT_BACKOFF.as_secs()
));
}
Ok(())
}
pub fn record_failure(&mut self, uid: u32) {
// ... apply exponential backoff ...
// Double the backoff, max 60 seconds
let new_backoff = std::cmp::min(current_backoff * 2, Duration::from_secs(60));
entry.2 = Some(now + new_backoff);
}
```
### Conclusion
Rate limiting is **properly implemented** and prevents brute-force attacks with:
- 10 connections/second per UID limit
- Exponential backoff (5s → 60s max)
- Automatic cleanup after 60s of inactivity
---
## Task 4: Message Size Limits
### Implementation Location
- `ipc.rs` lines 71, 492-521
### Verification Result: PASS
### Analysis
1. **MAX_MESSAGE_SIZE definition:**
- Line 71: `const MAX_MESSAGE_SIZE: usize = 64 * 1024;` (65536 = 64KB)
2. **Message size validation:**
- Line 494: Pre-allocates buffer of MAX_MESSAGE_SIZE
- Lines 501-521: Validates size BEFORE parsing
- Size check happens BEFORE buffer allocation (actually allocation is fixed-size)
3. **Oversized message handling:**
- Lines 502-521: Rejects messages that reach the limit
- Returns error response with proper message
4. **All receive paths covered:**
- Unix socket read in `handle_client()` (line 495)
- Client send_request also uses bounded buffer (line 831)
### Code Reference
```rust
// SECURITY: Read message with size validation
// First, read up to MAX_MESSAGE_SIZE bytes
let mut buffer = vec![0u8; MAX_MESSAGE_SIZE];
let n = stream.read(&mut buffer).await?;
// SECURITY: Validate message size
if n >= MAX_MESSAGE_SIZE {
warn!(
"Message size limit exceeded from UID {} (PID {}), rejecting",
peer_creds.uid, peer_creds.pid
);
// Send error response and close
return Ok(());
}
```
### Conclusion
Message size limits are **properly enforced** preventing buffer overflow attacks:
- 64KB limit defined and enforced
- Pre-read validation before parsing
- Rejects oversized messages with error response
---
## Overall IPC Security Assessment
| Security Feature | Status | Location |
|-----------------|--------|----------|
| SO_PEERCRED Validation | PASS | ipc.rs:88-116 |
| Authorization Boundaries | PASS | ipc.rs:123-149, 584, 635, 677 |
| Rate Limiting | PASS | ipc.rs:152-242 |
| Message Size Limits | PASS | ipc.rs:71, 492-521 |
| Socket Permissions | PASS | ipc.rs:401-409 (0o600) |
### Additional Security Features Verified
- Socket permissions set to 0o600 (owner only) - line 407
- Error messages do not leak sensitive information
- All IPC operations properly logged for audit
### Conclusion
All four IPC security features are **properly implemented and effective**. The codebase demonstrates security-conscious design with:
- Strong peer credential validation
- Proper authorization boundaries
- Effective rate limiting to prevent brute-force
- Message size limits to prevent buffer overflow
- Restrictive socket permissions

View File

@@ -1,183 +0,0 @@
# Logging Security Review
## Overview
This document reviews all logging statements to ensure they don't expose sensitive data such as passwords, credentials, templates, biometric data, cryptographic keys, or internal paths.
## Logging Framework
The codebase uses the `tracing` crate for structured logging with the following levels:
- `error` - Error conditions
- `warn` - Warning conditions
- `info` - Informational
- `debug` - Debug-level details
## Files Reviewed
| File | Logging Imports | Usage |
|------|----------------|-------|
| auth.rs | debug, info, warn | Authentication flow |
| ipc.rs | error, info, warn | IPC server |
| dbus_service.rs | info, error | D-Bus interface |
| tpm.rs | debug, info, warn | TPM/storage |
| secure_template_store.rs | debug, info, warn | (imported but unused) |
| camera/linux.rs | info, debug | Camera operations |
| camera/ir_emitter.rs | info, debug | IR emitter control |
| secure_memory.rs | warn | Memory locking |
| onnx/detector.rs | debug | Detection logging |
---
## Detailed Analysis
### 1. Authentication Logging (auth.rs)
**Findings:** ✅ SECURE
| Line | Level | Content | Sensitive? |
|-------|-------|---------|-------------|
| 53 | info | "Authenticating user: {}", user | No - username |
| 59 | warn | "User {} is not enrolled", user | No - username |
| 74 | warn | "Anti-spoofing check failed for user {}", user | No - username |
| 85-88 | debug | Match similarity score | No - debug only |
**Analysis:**
- Username is logged, but not passwords or credentials
- Similarity scores logged at debug level only (not production)
- No template or embedding data logged
- No biometric raw data logged
---
### 2. IPC Logging (ipc.rs)
**Findings:** ✅ SECURE
| Line | Level | Content | Sensitive? |
|-------|-------|---------|-------------|
| 411 | info | Socket path | No - system info |
| 420 | warn | Peer credential errors | No - technical |
| 429-431 | warn | Rate limit UID | No - UID only |
| 457 | warn | Client errors | No - technical |
| 462 | error | Accept errors | No - technical |
**Analysis:**
- Only logs peer UID, not credentials or templates
- Socket path is system configuration
- Rate limiting logs UIDs for audit purposes
---
### 3. D-Bus Service Logging (dbus_service.rs)
**Findings:** ✅ SECURE
| Line | Level | Content | Sensitive? |
|-------|-------|---------|-------------|
| 123 | info | Auth request for user | No - username |
| 129 | info | Auth result | No - success/failure |
| 133 | error | Auth error | No - error message |
| 150 | info | Enroll request | No - username + label |
| 278 | info | List templates | No - username |
| 286 | info | Remove template | No - username + label |
**Analysis:**
- D-Bus interface logs method calls for auditing
- Username logged but no sensitive data
- No template or embedding data
---
### 4. TPM Logging (tpm.rs)
**Findings:** ✅ SECURE
| Line | Level | Content | Sensitive? |
|-------|-------|---------|-------------|
| 184 | debug | "Generated new master secret" | No - status only |
| 283 | warn | Software fallback warning | No - status |
| 362 | debug | "Created software key for user" | No - username |
| 531 | info | TPM key created | No - status |
| 624 | info | User key created | No - username |
| 810 | info | TPM initialized | No - status |
| 872 | warn | TPM not available | No - status |
**Analysis:**
- No cryptographic key material logged
- No template or embedding data
- Username logged in some places for audit
- Clear distinction between hardware TPM and software fallback
---
### 5. Camera Logging (camera/linux.rs, ir_emitter.rs)
**Findings:** ✅ SECURE
| Level | Content | Sensitive? |
|--------|---------|-------------|
| info | Camera device paths | No - system info |
| info | IR emitter device | No - system info |
| debug | Control flow | No - technical |
**Analysis:**
- Device paths logged, not video frames
- No face images or biometric data logged
---
### 6. Secure Memory Logging (secure_memory.rs)
**Findings:** ✅ SECURE
| Level | Content | Sensitive? |
|--------|---------|-------------|
| warn | Memory locking failures | No - technical |
**Analysis:**
- No sensitive data logged
- Failures logged for debugging only
---
## What is NOT Logged (Good Practices)
The following sensitive data is **NOT** logged:
- ❌ Face images or frames
- ❌ Face embeddings or templates
- ❌ Template comparison scores in production logs
- ❌ Cryptographic keys or key material
- ❌ Passwords or PAM credentials
- ❌ TPM key handles in detail
- ❌ Internal file paths with sensitive data
---
## Summary
### Logging Security Assessment
| Category | Status | Notes |
|----------|--------|-------|
| Credentials | ✅ SAFE | No passwords logged |
| Templates/Embeddings | ✅ SAFE | Never logged |
| Biometric data | ✅ SAFE | Never logged |
| Crypto keys | ✅ SAFE | Not logged |
| Usernames | ✅ ACCEPTABLE | Logged for auditing |
| UID/GID | ✅ ACCEPTABLE | Logged for rate limiting |
| Device paths | ✅ ACCEPTABLE | System info |
| Similarity scores | ✅ ACCEPTABLE | Debug level only |
### Risk Assessment
**Overall Risk:** LOW
All logging follows security best practices:
1. No sensitive biometric data logged
2. No cryptographic key material logged
3. Template matching scores only at debug level
4. Username logging is appropriate for auditing
### Recommendations
None required. Current logging is secure.

View File

@@ -1,98 +0,0 @@
# Miri Results
**Date:** 2026-02-14
**Tool:** Miri (nightly)
**Command:** `cargo +nightly miri test -p linux-hello-daemon --no-default-features`
## Summary
| Status | Tests Passed | Tests Failed | Notes |
|--------|-------------|-------------|-------|
| PARTIAL | 12+ | 4+ | Miri limitations prevent full analysis |
## Test Results
### Unit Tests
| Test Module | Status | Notes |
|-------------|--------|-------|
| anti_spoofing | PASS | All 6 tests pass |
| camera::ir_emitter (partial) | FAIL | Requires process execution (not supported) |
| secure_memory (partial) | FAIL | Requires mlock (not supported) |
| secure_template_store | PASS | All 6 tests pass |
| tpm (partial) | FAIL | Requires chmod (not supported) |
| ipc | PASS | Tests pass (mock mode) |
### Doctests
| File | Status | Notes |
|------|--------|-------|
| detection/mod.rs | PASS | |
| embedding.rs | PASS | |
| secure_memory.rs | FAIL | Requires mlock (not supported) |
## Miri Limitations Encountered
Miri does not support the following operations that are essential to this project's security features:
1. **`mlock` / `munlock`** - Memory locking for secure data
- Used in: `secure_memory.rs` for locking sensitive data in RAM
- Impact: Cannot verify memory safety of SecureEmbedding's secure memory handling
2. **`chmod`** - File permission changes
- Used in: `tpm.rs` for setting secure file permissions
- Impact: Cannot test software TPM fallback initialization
3. **Process execution (`posix_spawn`)**
- Used in: `ir_emitter.rs` for controlling IR hardware
- Impact: Cannot test IR emitter control
4. **File system operations (some)**
- Various file operations restricted in Miri's isolated mode
## Unsafe Code Analysis
The project has unsafe blocks in the following locations (from research):
| File | Lines | Purpose | Miri Testable? |
|------|-------|---------|----------------|
| `ipc.rs` | 94-105 | SO_PEERCRED socket option | PARTIAL |
| `ipc.rs` | 142-147 | getpwnam FFI | YES |
| `secure_memory.rs` | 74-79 | Slice from_raw_parts | PARTIAL |
| `secure_memory.rs` | 293-296 | ptr::write_volatile | NO (mlock issue) |
| `secure_memory.rs` | 304-307 | ptr::write_volatile | NO (mlock issue) |
| `secure_memory.rs` | 318 | libc::mlock | NO |
| `secure_memory.rs` | 339-340 | libc::munlock | NO |
| `camera/linux.rs` | 192-194 | Stream lifetime | YES |
| `camera/linux.rs` | 198 | std::mem::transmute | YES |
## Security Assessment
Despite Miri limitations, the unsafe code can be manually verified:
1. **secure_memory.rs** - Uses well-audited `zeroize` crate
- `ptr::write_volatile` is used correctly for secure memory operations
- `mlock`/`munlock` are standard Unix APIs with correct error handling
- The code follows best practices for secure memory
2. **ipc.rs** - SO_PEERCRED implementation is standard
- Uses safe FFI bindings from `libc` crate
- Proper error handling for all system calls
- Authorization logic is sound
3. **camera/linux.rs** - Lifetime extension is intentional
- The unsafe block extends stream lifetime for storage
- Safety comment documents the invariant (device outlives stream)
## Recommendations
1. **For CI/CD**: Run Miri on a subset of tests that don't require system calls
2. **For unsafe code**: Manual code review confirms safe usage patterns
3. **For integration testing**: Use actual hardware/integration tests instead of Miri for system call-heavy code
## Notes
- Miri is primarily designed for pure Rust code without system dependencies
- Security-critical code that uses system calls (mlock, chmod) cannot be fully tested in Miri
- The code follows best practices and uses well-audited crates (zeroize, subtle)
- Manual code review confirms unsafe blocks are safe

View File

@@ -1,66 +0,0 @@
# Cargo Audit Results
**Date:** 2026-02-14
**Tool:** cargo-audit v0.22.1
## Summary
| Status | Critical | High | Medium | Low |
|--------|----------|------|--------|-----|
| FAIL | 0 | 1 | 0 | 0 |
## Vulnerabilities Found
### 1. RUSTSEC-2026-0007: Integer overflow in `BytesMut::reserve`
| Field | Value |
|-------|-------|
| **Crate** | bytes |
| **Version** | 1.11.0 |
| **Severity** | HIGH |
| **Date** | 2026-02-03 |
| **ID** | RUSTSEC-2026-0007 |
| **URL** | https://github.com/advisories/GHSA-434x-w66g-qw3r |
| **Solution** | Upgrade to >=1.11.1 |
**Dependency path:**
```
bytes 1.11.0
└── tokio 1.49.0
├── zbus 4.4.0
│ ├── linux-hello-settings 0.1.0
│ └── linux-hello-daemon 0.1.0
│ ├── linux-hello-tests 0.1.0
│ └── linux-hello-cli 0.1.0
├── linux-hello-settings 0.1.0
├── linux-hello-daemon 0.1.0
└── linux-hello-cli 0.1.0
```
**Vulnerability Description:**
An integer overflow vulnerability exists in `BytesMut::reserve` which could lead to buffer overflow or denial of service attacks.
**Remediation Plan:**
Update `bytes` crate to version >=1.11.1. This requires updating tokio or allowing the vulnerability temporarily while waiting for tokio to update.
## Actions Required
1. **Option A (Recommended):** Update bytes directly by adding to Cargo.toml:
```toml
[patch.crates-io]
bytes = { version = ">=1.11.1" }
```
2. **Option B:** Wait for tokio to release a new version with the fixed bytes crate, then update tokio.
3. **Option C (Temporary):** If the vulnerability cannot be immediately addressed, document the risk and add an ignore with justification:
```bash
cargo audit --ignore RUSTSEC-2026-0007
```
## Notes
- This is a transitive dependency vulnerability (not directly used by Linux Hello)
- The vulnerability is in tokio's dependency chain
- The attack requires the attacker to control the size parameter to `reserve()`
- Update: bytes 1.11.1+ contains the fix

View File

@@ -1,294 +0,0 @@
# Unsafe Code Inventory
## Overview
This document catalogs all unsafe code blocks in the Linux Hello codebase with their justifications and risk assessments.
## Summary
| File | Unsafe Blocks | Risk Level |
|------|--------------|------------|
| `ipc.rs` | 4 | LOW |
| `secure_memory.rs` | 5 | LOW |
| `camera/linux.rs` | 2 | LOW-MEDIUM |
| **Total** | **11** | - |
---
## Detailed Inventory
### 1. ipc.rs - SO_PEERCRED (Lines 94-105)
**Location:** `linux-hello-daemon/src/ipc.rs:94-105`
**Code:**
```rust
let mut ucred: libc::ucred = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
let ret = unsafe {
libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_PEERCRED,
&mut ucred as *mut _ as *mut libc::c_void,
&mut len,
)
};
```
**Purpose:** Retrieve peer credentials (PID, UID, GID) from a connected Unix socket.
**Safety Justification:**
- `std::mem::zeroed()` is safe here because the struct is immediately fully initialized by `getsockopt`
- `getsockopt` with `SO_PEERCRED` is a well-defined Linux kernel interface
- The pointer casting is standard practice for syscall wrappers
- Error handling checks return value and converts errors to `Result`
**Risk Level:** LOW
---
### 2. ipc.rs - getpwnam (Line 142)
**Location:** `linux-hello-daemon/src/ipc.rs:142`
**Code:**
```rust
let passwd = unsafe { libc::getpwnam(c_username.as_ptr()) };
```
**Purpose:** Look up user by username to get UID for authorization.
**Safety Justification:**
- Input is validated: `CString::new(username).ok()?` ensures null-termination
- Null check performed: `if passwd.is_null()`
- Standard C library function with well-defined behavior
**Risk Level:** LOW
---
### 3. ipc.rs - passwd dereference (Line 147)
**Location:** `linux-hello-daemon/src/ipc.rs:147`
**Code:**
```rust
Some(unsafe { (*passwd).pw_uid })
```
**Purpose:** Extract UID from the passwd struct after null check.
**Safety Justification:**
- Preceded by null check: `if passwd.is_null()`
- Only accesses `pw_uid` field which is always valid when struct is non-null
- Standard C library struct access pattern
**Risk Level:** LOW
---
### 4. secure_memory.rs - slice::from_raw_parts (Lines 74-79)
**Location:** `linux-hello-daemon/src/secure_memory.rs:74-79`
**Code:**
```rust
let byte_slice = unsafe {
std::slice::from_raw_parts(
self.data.as_ptr() as *const u8,
self.data.len() * std::mem::size_of::<f32>(),
)
};
```
**Purpose:** Convert f32 slice to byte slice for memory locking operations.
**Safety Justification:**
- Creates slice from valid pointer: `self.data.as_ptr()` is always valid
- Length calculation is correct: element count × element size
- Slice is only used for reading (mlock), not mutated
- Reference validity is guaranteed by Rust's borrow rules
**Risk Level:** LOW
---
### 5. secure_memory.rs - write_volatile for u8 (Lines 293-296)
**Location:** `linux-hello-daemon/src/secure_memory.rs:293-296`
**Code:**
```rust
pub fn secure_zero(data: &mut [u8]) {
for byte in data.iter_mut() {
unsafe {
ptr::write_volatile(byte, 0);
}
}
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
}
```
**Purpose:** Securely zero memory to prevent compiler optimization from removing zeroing.
**Safety Justification:**
- `ptr::write_volatile` prevents compiler from optimizing away the write
- Fence ensures all writes complete before function returns
- This is the recommended pattern for secure memory clearing
- Standard practice from cryptographic libraries
**Risk Level:** LOW
---
### 6. secure_memory.rs - write_volatile for f32 (Lines 304-307)
**Location:** `linux-hello-daemon/src/secure_memory.rs:304-307`
**Code:**
```rust
pub fn secure_zero_f32(data: &mut [f32]) {
for val in data.iter_mut() {
unsafe {
ptr::write_volatile(val, 0.0);
}
}
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
}
```
**Purpose:** Securely zero f32 array (face embeddings) to prevent compiler optimization.
**Safety Justification:**
- Same pattern as `secure_zero` for byte arrays
- Fence ensures complete clearing before return
- Essential for biometric data protection
**Risk Level:** LOW
---
### 7. secure_memory.rs - mlock (Line 318)
**Location:** `linux-hello-daemon/src/secure_memory.rs:318`
**Code:**
```rust
let result = unsafe { libc::mlock(data.as_ptr() as *const c_void, data.len()) };
```
**Purpose:** Lock memory pages to prevent swapping to disk (protects sensitive data).
**Safety Justification:**
- Standard mlock usage with valid pointer and length
- Return value is properly checked: `if result == 0`
- Error is handled gracefully (warning logged, not fatal)
- Failure to lock doesn't compromise security, just reduces protection
**Risk Level:** LOW
---
### 8. secure_memory.rs - munlock (Lines 339-340)
**Location:** `linux-hello-daemon/src/secure_memory.rs:339-340`
**Code:**
```rust
unsafe {
libc::munlock(data.as_ptr() as *const c_void, data.len());
}
```
**Purpose:** Unlock previously locked memory pages.
**Safety Justification:**
- Standard munlock usage with valid pointer and length
- Return value intentionally ignored: failure to unlock is not a security issue
- Called during cleanup/drop, best effort
**Risk Level:** LOW
---
### 9. camera/linux.rs - Stream creation (Lines 192-194)
**Location:** `linux-hello-daemon/src/camera/linux.rs:192-194`
**Code:**
```rust
let device_ptr = &self.device as *const Device;
let stream = unsafe {
Stream::with_buffers(&*device_ptr, Type::VideoCapture, 4)
.map_err(|e| Error::Camera(format!("Failed to create stream: {}", e)))?
};
```
**Purpose:** Create a video stream from a V4L2 device.
**Safety Justification:**
- `device_ptr` is a valid pointer to `self.device`
- `Stream::with_buffers` is from the `v4l` crate, which handles V4L2 safely
- Error handling ensures stream creation failures are caught
- The comment acknowledges the lifetime concern: "Need to use unsafe to extend lifetime"
**Risk Level:** LOW-MEDIUM (lifetime extension)
---
### 10. camera/linux.rs - transmute to 'static (Line 198)
**Location:** `linux-hello-daemon/src/camera/linux.rs:198`
**Code:**
```rust
self.stream = Some(unsafe { std::mem::transmute::<Stream<'_>, Stream<'static>>(stream) });
```
**Purpose:** Store stream with 'static lifetime in struct that manages its own lifetime.
**Safety Justification:**
- Stream is stored with device reference
- Drop order ensures device is dropped after stream (reverse declaration order)
- The code comment acknowledges: "we ensure device outlives stream"
- This is a known pattern in Rust for self-referential-like structures
**Risk Level:** MEDIUM (requires careful lifetime management)
---
## Risk Assessment Summary
| Risk Level | Count | Blocks |
|------------|-------|--------|
| LOW | 9 | ipc.rs (3), secure_memory.rs (5), camera/linux.rs (1) |
| LOW-MEDIUM | 1 | camera/linux.rs (stream creation) |
| MEDIUM | 1 | camera/linux.rs (transmute) |
| HIGH | 0 | - |
---
## Recommendations
1. **camera/linux.rs lifetime issue (Line 198):** Consider using `Pin` or `ouroboros` crate for self-referential structs. The current pattern relies on drop order guarantees which could be fragile.
2. **All other unsafe blocks:** Are well-justified and follow standard Rust patterns for:
- FFI calls (libc)
- Secure memory operations (volatile writes, memory locking)
- System credential retrieval
3. **Safety comments:** Most unsafe blocks have inline comments explaining the safety invariant. Consider adding explicit `SAFETY:` doc comments to each unsafe block for better documentation.
---
## Verification
All unsafe blocks have been verified to:
1. Have explicit safety justifications in comments
2. Use standard, well-understood patterns
3. Have proper error handling
4. Not expose undefined behavior risks
**Total unsafe blocks documented: 11**

View File

@@ -1,379 +0,0 @@
# Security Audit Architecture: Rust Biometric Authentication System
**Project:** Linux Hello - Biometric Authentication for Linux
**Domain:** Security Audit Framework
**Researched:** 2026-02-14
**Confidence:** HIGH
## Executive Summary
This document defines the recommended architecture for conducting a security audit of Linux Hello, a Rust-based biometric authentication system. The audit framework follows a phased approach combining OWASP methodologies with Rust-specific security considerations and biometric authentication domain expertise.
**Key recommendation:** Structure the audit in five sequential phases: **Architecture Review → Code Analysis → Cryptographic Review → Biometric Specific Audit → Integration Testing**. This ordering ensures foundational issues are identified before detailed component-specific analysis.
---
## 1. Audit Phase Structure
### Phase 1: Architecture & Threat Modeling (Week 1-2)
**Purpose:** Establish security context and identify attack surface before code review.
| Activity | Deliverable | Tools |
|----------|-------------|-------|
| System architecture documentation | Current DFD with trust boundaries | OWASP Threat Dragon, draw.io |
| Threat modeling session | STRIDE analysis per component | Microsoft Threat Modeling Tool |
| Attack surface enumeration | List of entry points and trust boundaries | Manual + grep |
| Existing security controls review | Control mapping document | Code analysis |
**Key components to model:**
- Unix socket IPC (`/run/linux-hello/auth.sock`)
- D-Bus interface for settings app
- Camera capture pipeline (V4L2)
- TPM/software encryption layer
- PAM module integration
- Template storage filesystem
**Timeline:** 2 weeks for initial codebase familiarity and threat modeling.
---
### Phase 2: Rust-Specific Code Security Review (Week 2-4)
**Purpose:** Identify Rust-specific security vulnerabilities and unsafe code issues.
#### 2.1 Unsafe Rust Audit
| Check | What to Look For | Risk |
|-------|------------------|------|
| `unsafe` blocks | Unnecessary unsafe code, missing safety comments | Memory safety |
| FFI boundaries | Native code interactions, C library bindings | Buffer overflows |
| `unsafe fn` functions | Missing safety invariants documentation | Undefined behavior |
| Raw pointer dereference | Manual memory management | Use-after-free |
| `mem::transmute` | Type punning without alignment | Memory corruption |
**Rust security focus areas:**
- **The Rustonomicon** patterns: https://doc.rust-lang.org/nomicon/index.html
- Verify all `unsafe` blocks have safety comments explaining invariants
- Check FFI (`extern "C"`) for proper bounds checking
- Review `#[no_mangle]` functions for exported interfaces
#### 2.2 Standard Vulnerability Patterns
Following OWASP Secure Code Review patterns:
| Category | Linux Hello Focus | Files to Review |
|----------|-------------------|-----------------|
| Input Validation | Camera frame validation, D-Bus message parsing | `camera/`, `ipc.rs` |
| Authentication | PAM module communication, peer credential verification | `ipc.rs`, `auth.rs` |
| Authorization | User UID verification, operation permission checks | `ipc.rs` |
| Cryptography | TPM integration, template encryption, key derivation | `tpm.rs`, `secure_template_store.rs` |
| Error Handling | Error message leakage, graceful degradation | All modules |
| Memory Safety | SecureBytes zeroization, mlock behavior | `secure_memory.rs` |
**Timeline:** 2-3 weeks for comprehensive code review.
---
### Phase 3: Cryptographic Implementation Audit (Week 4-5)
**Purpose:** Verify cryptographic implementations follow best practices.
#### 3.1 Algorithm Selection
Per OWASP Cryptographic Storage Cheat Sheet:
| Component | Current Implementation | Audit Check |
|-----------|------------------------|-------------|
| Template encryption | AES-256-GCM (software), TPM-wrapped (hardware) | Verify GCM mode, proper IV handling |
| Key derivation | PBKDF2-HMAC-SHA256 (600k iterations) | Verify iteration count, salt randomness |
| Random generation | CSPRNG via `rand::prng::chacha::ChaChaRng` | Verify CSPRNG usage, not PRNG |
| TPM operations | RSA key wrapping, optional PCR binding | Verify key sizes, PCR policy |
#### 3.2 Key Management Review
| Area | Audit Item | Expected |
|------|------------|----------|
| Key storage | TPM-backed vs software fallback | TPM preferred |
| Key separation | DEK/KEK separation | Separate keys per user |
| Key lifecycle | Rotation mechanism | Configurable rotation |
| Key memory | SecureBytes for keys in RAM | Zeroized on drop |
#### 3.3 Constant-Time Operations
Per OWASP guidance on timing attacks:
| Operation | Implementation | Audit Check |
|-----------|----------------|-------------|
| Template matching | `subtle::ConstantTimeEq` | Verify usage in `matching.rs` |
| Secure comparison | `SecureBytes::constant_time_eq()` | No early-exit comparisons |
**Timeline:** 1-2 weeks.
---
### Phase 4: Biometric-Specific Security Audit (Week 5-6)
**Purpose:** Address unique biometric authentication security concerns.
#### 4.1 Anti-Spoofing Review
| Attack Vector | Current Implementation | Audit Focus |
|---------------|----------------------|-------------|
| Photo attack | IR camera detection | Verify IR-based liveness |
| 3D mask attack | Depth/structure analysis | Review anti_spoofing.rs |
| Replay attack | Session-specific challenges | Verify temporal validation |
| Deepfake | Texture/pattern analysis | ONNX model robustness |
**Audit checklist:**
- [ ] Review `anti_spoofing.rs` for bypass scenarios
- [ ] Verify IR emitter control integration
- [ ] Check for blind spots in spoof detection
- [ ] Assess ONNX model integrity (model poisoning)
#### 4.2 Template Security
Biometric templates require special protection:
| Concern | Current Protection | Audit Check |
|---------|-------------------|-------------|
| Template extraction | TPM/software encryption at rest | Verify encryption in `secure_template_store.rs` |
| Template in memory | SecureBytes + mlock | Verify memory locking, zeroization |
| Template revocability | Not applicable (biometric) | Document limitation |
| Template linkage | Per-user key isolation | Verify key separation |
#### 4.3 Liveness Detection
Per FIDO standards and OWASP Authentication guidance:
| Check | Implementation | Audit Focus |
|-------|---------------|-------------|
| Random challenge | Motion/blink detection | Verify challenge randomness |
| Multi-frame analysis | Temporal consistency | Review frame buffer handling |
| IR depth verification | IR camera integration | Verify depth data usage |
**Timeline:** 1-2 weeks.
---
### Phase 5: Integration & Penetration Testing (Week 6-8)
**Purpose:** Validate security in realistic attack scenarios.
#### 5.1 Component Integration Testing
| Interface | Test Scenarios | Priority |
|-----------|---------------|----------|
| PAM module → Daemon | Privilege escalation, credential passing | High |
| D-Bus API | D-Bus message injection, spoofing | High |
| Camera capture | Frame injection, camera enumeration | Medium |
| Settings app | Unintended data exposure | Medium |
#### 5.2 Attack Scenarios
| Attack | Test Method | Success Criteria |
|--------|-------------|------------------|
| Socket hijacking | Connect to auth.sock as non-root | Connection refused |
| Template theft | Access template files directly | Files encrypted, unreadable |
| Memory dump | Inspect process memory | Sensitive data not present |
| Timing attack | Measure auth timing | No correlation with template match |
| Replay attack | Capture and replay auth request | Request rejected |
| DoS | Flood authentication requests | Rate limiting prevents exhaustion |
#### 5.3 Fuzz Testing
| Target | Fuzzer | Focus |
|--------|--------|-------|
| IPC message parsing | cargo-fuzz | Malformed JSON handling |
| D-Bus interface | dbus-send fuzzing | Invalid method calls |
| Camera frame processing | libfuzzer | Edge case frames |
**Timeline:** 2-3 weeks.
---
## 2. Workflow Summary
```
┌─────────────────────────────────────────────────────────────────┐
│ PHASE 1: Architecture & Threat Modeling (Week 1-2) │
│ - Document system boundaries │
│ - STRIDE threat identification │
│ - Attack surface enumeration │
└────────────────────────────┬────────────────────────────────────┘
┌────────────────────────────▼────────────────────────────────────┐
│ PHASE 2: Rust Code Security Review (Week 2-4) │
│ - Unsafe Rust audit │
│ - OWASP vulnerability patterns │
│ - Input validation verification │
└────────────────────────────┬────────────────────────────────────┘
┌────────────────────────────▼────────────────────────────────────┐
│ PHASE 3: Cryptographic Audit (Week 4-5) │
│ - Algorithm verification │
│ - Key management review │
│ - Constant-time operations check │
└────────────────────────────┬────────────────────────────────────┘
┌────────────────────────────▼────────────────────────────────────┐
│ PHASE 4: Biometric-Specific Audit (Week 5-6) │
│ - Anti-spoofing verification │
│ - Template security review │
│ - Liveness detection assessment │
└────────────────────────────┬────────────────────────────────────┘
┌────────────────────────────▼────────────────────────────────────┐
│ PHASE 5: Integration Testing (Week 6-8) │
│ - Component interaction testing │
│ - Penetration testing │
│ - Fuzzing campaign │
└─────────────────────────────────────────────────────────────────┘
```
---
## 3. Risk-Based Prioritization
### Critical Priority (Audit First)
| Area | Reason | Files |
|------|--------|-------|
| IPC authorization | Privilege escalation vector | `ipc.rs` |
| Template encryption | Data breach impact | `tpm.rs`, `secure_template_store.rs` |
| Secure memory handling | Memory extraction risk | `secure_memory.rs` |
| PAM integration | Login bypass potential | pam-module/ |
### High Priority
| Area | Reason | Files |
|------|--------|-------|
| Anti-spoofing | Authentication bypass | `anti_spoofing.rs` |
| TPM fallback | Weak security mode | `tpm.rs` |
| Rate limiting | Brute force vector | `ipc.rs` |
### Medium Priority
| Area | Reason | Files |
|------|--------|-------|
| Camera access control | Local DoS | `camera/` |
| D-Bus interface | Settings manipulation | `dbus_service.rs` |
| Error messages | Information disclosure | All modules |
---
## 4. Tools & Techniques
### Static Analysis
| Tool | Purpose | Integration |
|------|---------|-------------|
| `cargo clippy` | Linting, anti-patterns | CI pipeline |
| `cargo audit` | Dependency vulnerabilities | CI pipeline |
| `cargo-geiger` | Unsafe code inventory | Manual |
| `rustsec` | Security advisories | CI pipeline |
### Dynamic Analysis
| Tool | Purpose | Phase |
|------|---------|-------|
| `cargo-fuzz` | Fuzzing IPC, parsing | Phase 5 |
| Valgrind | Memory safety | Phase 2 |
| `strace`/`ltrace` | System call analysis | Phase 5 |
### Manual Review
| Technique | Focus | Phase |
|-----------|-------|-------|
| Code pattern search | Dangerous patterns | Phase 2 |
| Data flow tracing | Sensitive data | Phase 2 |
| Attack tree analysis | Complex attack paths | Phase 1 |
---
## 5. Audit Documentation Template
### Finding Report Format
```markdown
## Finding: [Title]
**Severity:** [Critical|High|Medium|Low|Info]
**Component:** [File/Module]
**CWE:** [CWE-ID if applicable]
### Description
[Detailed explanation of the vulnerability]
### Impact
[Security implications and attack scenarios]
### Proof of Concept
[Steps to reproduce or exploit]
### Recommendation
[Specific remediation guidance]
### References
- CWE: [link]
- OWASP: [link]
- Related code: [file:line]
```
### Summary Report Structure
```markdown
# Security Audit Report: Linux Hello
## Executive Summary
[Overall risk assessment]
## Scope
[Components reviewed, dates, methodology]
## Findings Summary
| Severity | Count |
|----------|-------|
| Critical | X |
| High | X |
| Medium | X |
| Low | X |
## Key Recommendations
1. [Priority finding]
2. [Priority finding]
## Detailed Findings
[Findings by category]
## Appendices
- Tool outputs
- Code review notes
- Threat model diagrams
```
---
## 6. Timeline Summary
| Phase | Duration | Cumulative |
|-------|----------|------------|
| 1. Architecture & Threat Modeling | 2 weeks | 2 weeks |
| 2. Rust Code Security Review | 2-3 weeks | 4-5 weeks |
| 3. Cryptographic Audit | 1-2 weeks | 5-7 weeks |
| 4. Biometric-Specific Audit | 1-2 weeks | 6-9 weeks |
| 5. Integration Testing | 2-3 weeks | 8-12 weeks |
**Estimated total: 8-12 weeks** depending on team size and findings depth.
---
## 7. Sources
- **OWASP Secure Code Review Guide:** https://cheatsheetseries.owasp.org/cheatsheets/Secure_Code_Review_Cheat_Sheet.html
- **OWASP Threat Modeling Guide:** https://cheatsheetseries.owasp.org/cheatsheets/Threat_Modeling_Cheat_Sheet.html
- **OWASP Authentication Guide:** https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- **OWASP Cryptographic Storage Guide:** https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
- **The Rustonomicon:** https://doc.rust-lang.org/nomicon/index.html
- **Rust Rand CSPRNG:** https://docs.rs/rand/0.5.0/rand/prng/index.html#cryptographically-secure-pseudo-random-number-generators-csprngs
- **FIDO Authentication Standards:** https://fidoalliance.org/
- **NIST SP 800-63B (Digital Identity Guidelines):** https://pages.nist.gov/800-63-4/sp800-63b.html

View File

@@ -1,197 +0,0 @@
# Security Audit Feature Research
**Domain:** Biometric Authentication System Security Audit
**Researched:** 2026-02-14
**Confidence:** HIGH
## Executive Summary
This document identifies the critical security areas to audit in a biometric authentication system, specifically for Linux Hello (a Windows Hello-equivalent for Linux with face detection, TPM integration, secure memory, and encrypted template storage). Drawing from NIST SP 800-63B/63-4 and FIDO Biometrics Requirements v4.1, this research categorizes audit areas into **Critical** (must audit) and **Optional** (nice-to-audit) domains with specific vulnerability categories relevant to this Rust-based implementation.
## Critical Audit Areas (Must Audit)
These areas represent the core security boundaries. Failure to properly audit them could result in complete authentication bypass, credential theft, or system compromise.
### 1. Biometric Presentation Attack Detection (PAD)
| Audit Item | Vulnerability Category | Why Critical | Linux Hello Relevance |
|------------|----------------------|--------------|----------------------|
| IR Liveness Check Bypass | Spoofing Attack | Attacker uses printed photo with IR reflection | Anti-spoofing module implements IR check with 1.5x weight |
| Depth Estimation Bypass | 3D Mask Attack | Attacker uses 3D-printed mask | Anti-spoofing module has depth check (1.2x weight) |
| Texture Analysis Bypass | Screen Replay Attack | Attacker displays face on screen | LBP texture detection implemented |
| Blink Detection Bypass | Static Image Attack | Static photo can pass if blink skipped | Blink check implemented (0.8x weight) |
| Movement Check Bypass | Video Loop Attack | Pre-recorded video with movement | Movement analysis implemented (0.8x weight) |
| Deepfake Injection | AI-Generated Face | Neural network-generated face bypasses PAD | FIDO requires testing for deepfake video (2024 update) |
**Specific Vulnerabilities to Check:**
- Does the IR check properly validate IR reflection patterns vs. printed photos?
- Can multiple frames be captured and averaged to bypass movement detection?
- Is there protection against frame injection attacks (PAI species: replay)?
- Does the PAD threshold (0.7 default) provide adequate security vs. usability trade-off?
**Audit Standards:** FIDO Biometrics Requirements v4.1 Section 3.5 (IAPAR < 7% for Level 2), NIST SP 800-63-4 Section 3.2.3
### 2. Template Storage Encryption
| Audit Item | Vulnerability Category | Why Critical | Linux Hello Relevance |
|------------|----------------------|--------------|----------------------|
| Encryption Key Management | Key Extraction | Attackers extract templates from disk | TPM module with AES-256-GCM (software fallback) |
| TPM Binding Verification | Hardware-Bound Key Bypass | Templates accessible without TPM | Primary key bound to TPM handle |
| Software Fallback Security | Weak Cryptography | Fallback provides inadequate protection | PBKDF2-HMAC-SHA256 with 600k iterations |
| Key Derivation | Password Cracking | Attacker derives key from salt+password | Salt and iteration count must be validated |
| IV/Nonce Reuse | Cryptographic Oracle | Reusing IV leaks plaintext | Each encryption generates new IV |
**Specific Vulnerabilities to Check:**
- Is the TPM primary key properly protected with auth value?
- Does the software fallback use sufficient PBKDF2 iterations (NIST recommends 600k+ for AAL3)?
- Are salts generated with a CSPRNG?
- Can encrypted templates be decrypted on a different machine (should not for TPM, should not for software)?
- Is the encrypted template format properly versioned for migration?
**Audit Standards:** NIST SP 800-63-4 Section 3.1.1.2 (password storage), FIPS 140 requirements
### 3. Secure Memory Handling
| Audit Item | Vulnerability Category | Why Critical | Linux Hello Relevance |
|------------|----------------------|--------------|----------------------|
| Memory Zeroization | Data Persistence | Biometric embeddings remain in memory after use | SecureEmbedding uses zeroize crate |
| Swap Prevention | Disk Disclosure | mlock() failure exposes data to swap | try_lock_memory() implemented |
| Timing Attacks | Side-Channel Leakage | Constant-time comparison bypassed | Uses subtle crate for constant-time eq |
| Debug Information Leak | Memory Dump | Sensitive data in debug output | Debug redact implemented |
| Copy-on-Write Memory | Fork Exposure | Child processes inherit memory pages | mlock should prevent this |
**Specific Vulnerabilities to Check:**
- Does every code path through SecureEmbedding/SecureBytes properly zero memory?
- Is there any code path that copies sensitive data without zeroizing source?
- Are there any Vec::push or concatenation operations that could leave copies?
- Does the SecureEmbedding Drop implementation properly zeroize?
- Are there any timing variations in comparison that could leak information?
**Audit Standards:** NIST SP 800-63-4 Section 3.2.5 (verifier compromise resistance)
### 4. IPC Authorization and Rate Limiting
| Audit Item | Vulnerability Category | Why Critical | Linux Hello Relevance |
|------------|----------------------|--------------|----------------------|
| Peer Credential Validation | Privilege Escalation | Attacker spoofing UID to access other users' data | SO_PEERCRED implemented |
| Authorization Boundary | Unauthorized Access | User A can authenticate as User B | UID 0 (root) vs regular user check |
| Rate Limiting Bypass | Brute-Force Attack | Attacker tries many templates rapidly | MAX_CONNECTIONS_PER_SECOND = 10 |
| Message Size Limits | DoS/Memory Exhaustion | Large messages crash daemon | MAX_MESSAGE_SIZE = 64KB |
| Socket Permission | Local Privilege Escalation | Non-root user accesses socket | File permissions 0o600 |
**Specific Vulnerabilities to Check:**
- Is SO_PEERCRED properly validated before processing requests?
- Can a processspoof its UID through socket options?
- Does the rate limiting correctly track by UID?
- Is there protection against connection exhaustion (DoS)?
- Are all requests validated for proper JSON structure before parsing?
### 5. Face Detection and Matching Security
| Audit Item | Vulnerability Category | Why Critical | Linux Hello Relevance |
|------------|----------------------|--------------|----------------------|
| False Accept Rate (FAR) | Unauthorized Access | System accepts wrong face | Must meet FIDO requirements (<1% Level 1, <0.01% Level 2) |
| False Reject Rate (FRR) | Denial of Service | System rejects legitimate user | Should be <7% per FIDO |
| Template Unlinkability | Privacy Bypass | Templates can be linked across services | Each user has separate encrypted template |
| Embedding Extraction | Inverse Attack | Attacker reconstructs face from embedding | Embeddings stored encrypted |
| ONNX Model Security | Model Tampering | Attacker substitutes model for bypass | Model integrity not explicitly verified |
**Specific Vulnerabilities to Check:**
- What is the actual FAR/FRR of the matching algorithm?
- Are similarity thresholds properly calibrated for security?
- Can embeddings be extracted from memory in plaintext?
- Is the ONNX model loaded from a trusted path?
- Are there any issues with the cosine similarity implementation?
**Audit Standards:** FIDO Biometrics Requirements v4.1 Section 3.4 (FAR/FRR requirements), NIST SP 800-63B Section 5.2.3
## Optional Audit Areas (Nice to Audit)
These areas are important for defense-in-depth but represent lower-risk attack surfaces or are already partially addressed.
### 6. TPM Hardware Security (Feature-Gated)
| Audit Item | Vulnerability Category | Notes |
|------------|----------------------|-------|
| TPM Firmware Vulnerabilities | Hardware Compromise | Requires physical access, TPM vendor updates |
| PCR Binding Bypass | Boot Tampering | Optional feature, not enabled by default |
| TPM Key Extraction | Key Dumping | TPM should prevent extraction by design |
| TPM Availability Detection | DoS | Graceful fallback exists |
**Audit Approach:** Verify TPM is available, verify fallback works correctly when TPM absent
### 7. Camera Subsystem Security
| Audit Item | Vulnerability Category | Notes |
|------------|----------------------|-------|
| Camera Enumeration | Information Disclosure | Lists available devices, low risk |
| Frame Injection | Spoofing Input | Could inject pre-recorded frames |
| IR Emitter Control | Hardware Access | Affects PAD effectiveness |
**Audit Approach:** Verify camera handles are properly released, verify IR emitter state management
### 8. Session Management
| Audit Item | Vulnerability Category | Notes |
|------------|----------------------|-------|
| Session Token Security | Session Hijacking | Tokens stored securely, not logged |
| Session Timeout | Session Persistence | NIST recommends 12h for AAL3, 24h for AAL2 |
| Re-authentication | Step-up Auth | May need re-auth for sensitive operations |
**Audit Approach:** Verify session lifecycle is properly managed
### 9. D-Bus Interface Security
| Audit Item | Vulnerability Category | Notes |
|------------|----------------------|-------|
| D-Bus Policy | Unauthorized Access | Policy files restrict access |
| Method Call Validation | Injection | All inputs validated |
| Signal Security | Eavesdropping | Communication on system bus |
**Audit Approach:** Verify D-Bus policy restricts to authorized callers
### 10. PAM Module Integration
| Audit Item | Vulnerability Category | Notes |
|------------|----------------------|-------|
| PAM Conversation | Credential Handling | Password fallback if biometric fails |
| Privilege Context | UID Transition | Runs as root during auth |
| Module Path | Tampering | Binary should be protected |
**Audit Approach:** Verify PAM module permissions, verify conversation flow
## Audit Prioritization Matrix
| Priority | Area | Impact if Compromised | Effort to Audit |
|----------|------|----------------------|----------------|
| P1 | Biometric PAD | Complete bypass | High |
| P1 | Template Encryption | Credential theft | High |
| P1 | Secure Memory | Data persistence | Medium |
| P1 | IPC Authorization | Privilege escalation | Medium |
| P2 | Face Matching FAR/FRR | False accepts/rejects | High |
| P2 | TPM Integration | Hardware security | Medium |
| P3 | Camera Subsystem | Limited | Low |
| P3 | Session Management | Session issues | Low |
| P3 | D-Bus Interface | Limited | Low |
| P3 | PAM Module | Limited | Low |
## Sources
- **NIST SP 800-63B** (2017) - Digital Identity Guidelines, Authentication and Lifecycle Management
- **NIST SP 800-63-4** (2025) - Updated authentication guidelines, biometrics requirements
- **FIDO Biometrics Requirements v4.1** (January 2025) - Biometric Component Certification, IdV-Face requirements
- **ISO/IEC 19795-1:2021** - Biometric performance testing and reporting
- **ISO/IEC 30107-1:2023** - Biometric presentation attack detection framework
- **Project Code Analysis** - linux-hello-daemon source code review
## Notes for Audit Execution
1. **FAR/FRR Testing**: Requires large test dataset per FIDO requirements (245 subjects minimum for Level 2)
2. **PAD Testing**: FIDO requires testing with specific PAI species (6 Level A, 8 Level B for face)
3. **Code Review**: Focus on unsafe code blocks, memory management, cryptographic implementations
4. **Penetration Testing**: Focus on IPC, template storage, PAD bypass attempts
---
*Security audit research for: Linux Hello Biometric Authentication*
*Researched: 2026-02-14*

View File

@@ -1,324 +0,0 @@
# Pitfalls Research: Biometric Authentication System Security Audit
**Domain:** Biometric Authentication Security Audit
**Researched:** February 14, 2026
**Confidence:** HIGH
---
## Critical Pitfalls
### Pitfall 1: Inadequate Presentation Attack Detection (PAD) Testing
**What goes wrong:**
Auditors assume that if biometric matching works, the system is secure. However, presentation attacks (also known as spoofing) are the primary attack vector against biometric systems. Without proper PAD testing, systems can be defeated by photos, videos, masks, or replayed biometric samples.
**Why it happens:**
- PAD is often treated as an optional "nice-to-have" rather than a core security requirement
- Functional testing (does face unlock work?) takes precedence over security testing (can it be fooled?)
- Many developers lack expertise in adversarial biometric testing
**How to avoid:**
1. Verify the system implements PAD at the sensor level, not just at the matching level
2. Check for multiple PAD signals (liveness detection, texture analysis, IR depth, eye blinking)
3. Test with realistic attack instruments: printed photos, digital displays, 3D masks, deepfakes
4. Verify PAD rate limiting - how many failed attempts before lockout?
**Warning signs:**
- No documented IAPAR (Impostor Attack Presentation Accept Rate) metrics
- PAD relies solely on single signal (e.g., only eye blink)
- No rate limiting on authentication attempts
- System accepts biometric samples without liveness verification
**Phase to address:** Security Architecture Review - ensure PAD is integral to the design
---
### Pitfall 2: Ignoring False Accept Rate (FAR) / False Reject Rate (FRR) Tradeoffs
**What goes wrong:**
Auditors accept stated FAR/FRR numbers without understanding the operational security implications. A system with 0.01% FAR might still be vulnerable to bulk attacks if not properly rate-limited.
**Why it happens:**
- FAR/FRR are often quoted from vendor specifications without independent verification
- The security impact of FAR varies dramatically based on attack model
- FRR is often ignored as "usability" rather than security
**How to avoid:**
1. Verify FAR claims with independent testing - don't trust vendor numbers alone
2. Understand the attack model: is this for consumer use (high FRR tolerance) or high-security (low FAR required)?
3. Check if the system allows FAR/FRR threshold configuration and what the defaults are
4. Verify rate limiting: 0.01% FAR × 100,000 attempts = 10 false accepts
**Warning signs:**
- No documented FAR/FRR testing methodology
- Rate limiting allows unlimited attempts without lockout
- System lacks audit logging for authentication attempts
- No upper bound on authentication attempts before account lockout
**Phase to address:** Metrics Verification - independently verify biometric performance claims
---
### Pitfall 3: Weak Secure Enclave / Template Storage
**What goes wrong:**
Biometric templates (the mathematical representation of biometric data) are stored without proper protection. If stolen, templates cannot be revoked like passwords - the user cannot "change their face."
**Why it happens:**
- Developers underestimate the value of biometric templates
- Encryption at rest is often implemented but key management is weak
- Template binding to device/TPM is not verified
**How to avoid:**
1. Verify templates are encrypted with keys stored in hardware (TPM, Secure Enclave)
2. Check that templates are non-exportable or encrypted with hardware-bound keys
3. Verify templates cannot be used to reconstruct original biometric sample
4. Check for template salting or transformation before storage
5. For software fallback: verify AES-256-GCM encryption with proper key derivation (PBKDF2/Argon2)
**Warning signs:**
- Templates stored in plaintext or with reversible encryption
- Encryption keys derived from weak sources (user password without hardware backing)
- No hardware binding for template protection
- Templates can be exported from the system
**Phase to address:** Cryptographic Review - verify template protection architecture
---
### Pitfall 4: Timing Attack Vulnerabilities in Template Matching
**What goes wrong:**
Template comparison uses naive string comparison or non-constant-time operations, leaking information through timing differences. Attackers can derive template information byte-by-byte.
**Why it happens:**
- Developers use standard library comparison functions not designed for security
- Constant-time operations add performance overhead that seems unnecessary
- Timing attacks are not well-understood outside cryptographic expertise
**How to avoid:**
1. Verify template comparison uses constant-time algorithms
2. Check for use of `subtle` crate or equivalent constant-time operations in Rust
3. Test for timing variations between correct and incorrect template comparisons
4. Verify cosine similarity or other matching algorithms don't leak information
**Warning signs:**
- No constant-time comparison for template matching
- Template comparison timing varies with similarity score
- Standard library comparison functions used without constant-time wrapper
- No cryptographic review of matching algorithm
**Phase to address:** Cryptographic Implementation Review
---
### Pitfall 5: Missing or Inadequate Rate Limiting
**What goes wrong:**
Biometric authentication lacks the rate limiting common in password authentication. Attackers can make unlimited attempts, using statistical attacks to achieve acceptable FAR over time.
**Why it happens:**
- Biometric systems often assume "something you have" provides rate limiting
- Consumer devices may not implement application-level rate limiting
- Re-enrollment without proper authorization can lead to template replacement attacks
**How to avoid:**
1. Verify rate limiting at both device and application levels
2. Check for account lockout after N failed attempts
3. Verify re-enrollment requires strong authentication
4. Check for rate limiting on template updates
5. Verify temporary lockout duration increases with repeated failures
**Warning signs:**
- No documented rate limiting implementation
- Failed attempts don't increment lockout counter
- Re-enrollment allowed without primary factor authentication
- No exponential backoff on failed attempts
**Phase to address:** Authentication Flow Review - verify all authentication paths have rate limiting
---
### Pitfall 6: IPC Security Gaps
**What goes wrong:**
Communication between PAM module, CLI client, and daemon uses unprotected Unix sockets. Local attackers can inject authentication requests or intercept credentials.
**Why it happens:**
- Unix sockets are assumed to be secure because they're filesystem-based
- Peer credentials (SO_PEERCRED) not properly validated
- No message authentication on IPC channels
**How to avoid:**
1. Verify IPC uses authenticated protected channels
2. Check SO_PEERCRED validation for caller identity
3. Verify message signing or encryption for sensitive operations
4. Check for proper authorization checks before sensitive operations
5. Verify rate limiting at the daemon level, not just client side
**Warning signs:**
- No peer credential validation on socket connections
- Messages not signed or encrypted
- No authorization checks beyond authentication
- Daemon accepts requests from any local user
**Phase to address:** IPC Security Review
---
### Pitfall 7: Insecure Camera / Sensor Interface
**What goes wrong:**
Camera input is not properly validated, allowing injection of pre-recorded video, deepfakes, or manipulated frames. The system trusts the camera driver without verification.
**Why it happens:**
- V4L2 interface assumed to provide trusted input
- No frame authenticity verification
- Lack of understanding of camera firmware attack surface
**How to avoid:**
1. Verify camera driver authenticity verification if available
2. Check for frame metadata validation (timestamps, sequence numbers)
3. Verify IR camera vs RGB camera binding
4. Test with injected video files to verify rejection
5. Verify camera enumeration only allows trusted devices
**Warning signs:**
- No frame source verification
- System accepts video file injection
- No IR/RGB camera binding verification
- Camera selection not restricted to trusted devices
**Phase to address:** Sensor Input Validation Review
---
## Technical Debt Patterns
| Shortcut | Immediate Benefit | Long-term Cost | When Acceptable |
|----------|-------------------|----------------|-----------------|
| Software-only template encryption | Faster development, no TPM required | Templates vulnerable to offline attack if device stolen | Only for testing/development, never production |
| Single PAD signal (e.g., blink only) | Simpler implementation | Easily defeated by advanced attacks | Never in production |
| Default FAR threshold at 1% | Fewer false rejects, better UX | Unacceptable security for authentication | Only for low-security screening, never auth |
| No audit logging | Simpler implementation | No forensic capability, cannot detect attacks | Never for security-critical systems |
| Re-enrollment without re-auth | Better UX | Account takeover via template replacement | Never without primary factor verification |
---
## Integration Gotchas
| Integration | Common Mistake | Correct Approach |
|-------------|----------------|------------------|
| TPM Integration | Treating TPM as magic security; not verifying key binding | Verify keys are non-exportable, require user presence for key use |
| D-Bus Interface | Accepting any D-Bus call without caller verification | Validate caller PID/UID, require authentication for sensitive methods |
| PAM Module | Trusting PAM environment without re-validation | Re-validate all security context in daemon |
| ONNX Runtime | Loading models from untrusted paths | Verify model integrity, use signed models |
| Camera Driver | Assuming V4L2 provides sanitized input | Validate frame properties, use trusted camera paths |
---
## Performance Traps
| Trap | Symptoms | Prevention | When It Breaks |
|------|----------|------------|----------------|
| Template matching O(n) | Authentication slows with more enrolled users | Use efficient indexing, limit enrolled templates | At >100 templates per user |
| ONNX model loading | First authentication takes 10+ seconds | Pre-load models at daemon startup | First use after daemon restart |
| No async camera capture | UI blocking during capture | Use async V4L2 or separate capture thread | On slow cameras, high-resolution modes |
| Encryption without hardware acceleration | Authentication takes seconds | Use hardware crypto (AES-NI, ARM CE) | On older CPUs without crypto instructions |
---
## Security Mistakes
| Mistake | Risk | Prevention |
|---------|------|------------|
| Storing raw biometric samples | Reversible, privacy violation | Never store samples; only templates |
| Template encryption with user password only | Offline attack if device stolen | Hardware-bound keys (TPM) or secure enclave |
| No secure memory handling | Biometric data in swap | Use `mlock()` / memory locking, zeroize on drop |
| Ignoring side-channel attacks | Timing analysis reveals template | Constant-time operations, cache attack mitigation |
| Missing downgrade attack prevention | Attacker forces weaker protocol | Require minimum security level, reject legacy modes |
| No firmware verification for camera | Compromised camera firmware | Verify camera firmware if possible, use secure boot |
---
## "Looks Done But Isn't" Checklist
- [ ] **FAR/FRR Metrics:** Often missing independent verification — verify with own test dataset
- [ ] **PAD Testing:** Often limited to simple attacks — verify deepfake/mask testing performed
- [ ] **Template Protection:** Often uses reversible encryption — verify hardware binding
- [ ] **Rate Limiting:** Often missing at application layer — verify daemon-level limits
- [ ] **IPC Security:** Often trusts local socket — verify peer credentials
- [ ] **Secure Memory:** Often leaks to swap — verify mlock + zeroize
- [ ] **Audit Logging:** Often missing or incomplete — verify all auth attempts logged
- [ ] **Key Management:** Often uses weak derivation — verify PBKDF2/Argon2 with adequate iterations
- [ ] **Constant-Time Comparison:** Often missing — verify with timing tests
---
## Recovery Strategies
| Pitfall | Recovery Cost | Recovery Steps |
|---------|---------------|----------------|
| Compromised templates | HIGH | Cannot revoke biometrics; require re-enrollment with in-person verification |
| Timing attack exposure | MEDIUM | Replace constant-time implementation, rotate keys |
| Rate limiting bypass | LOW | Implement proper rate limiting, add account lockout |
| IPC injection | MEDIUM | Add peer credential validation, message signing |
| Deepfake acceptance | HIGH | Add additional PAD signals, require live capture verification |
---
## Pitfall-to-Phase Mapping
| Pitfall | Prevention Phase | Verification |
|---------|------------------|--------------|
| PAD Testing | Security Architecture | Test with presentation attacks |
| FAR/FRR Tradeoffs | Metrics Review | Independent performance testing |
| Template Storage | Cryptographic Review | Key management audit |
| Timing Attacks | Implementation Review | Timing analysis testing |
| Rate Limiting | Authentication Flow | Attempt-based testing |
| IPC Security | Interface Review | Protocol analysis |
| Camera Input | Sensor Integration | Injection testing |
---
## Sources
- **NIST SP 800-63B (2025):** Digital identity guidelines for biometric authentication requirements
- URL: https://pages.nist.gov/800-63-4/sp800-63b.html
- Confidence: HIGH - Official US government specification
- **FIDO Biometrics Requirements v4.1 (2025):** Industry certification requirements for biometric systems
- URL: https://fidoalliance.org/specs/biometric/requirements/Biometrics-Requirements-v4.1-fd-20250106.html
- Confidence: HIGH - Industry standards body specification
- **ISO/IEC 19795-1:2021:** Biometric performance testing principles
- Confidence: HIGH - International standards
- **ISO/IEC 30107-3:2023:** Presentation attack detection testing and reporting
- Confidence: HIGH - International standards
---
## Relevance to Linux Hello Project
The Linux Hello project implements:
- Face detection using ONNX models (with placeholder fallback)
- TPM integration with software fallback
- Secure memory handling with zeroization
- Encrypted template storage using AES-256-GCM
- Unix socket IPC between PAM/CLI and daemon
- D-Bus interface for settings
**Audit priorities for this project:**
1. Verify PAD implementation (anti-spoofing) meets modern standards
2. Check IPC security (peer credentials, message signing)
3. Verify TPM binding vs software fallback security differences
4. Confirm constant-time template matching
5. Validate rate limiting at daemon level
6. Review ONNX model loading security
---
*Pitfalls research for: Biometric Authentication Security Audit*
*Researched: February 14, 2026*

View File

@@ -1,323 +0,0 @@
# Stack Research: Rust Security Audit Tools
**Domain:** Code Security Audit Tooling
**Researched:** 2026-02-14
**Confidence:** HIGH
## Executive Summary
This document catalogs the recommended tools for performing a thorough security audit of a Rust codebase (Linux Hello - a biometric authentication system). The Rust ecosystem provides excellent security tooling maintained by the Rust Secure Code Working Group. The recommended approach layers multiple tools: dependency vulnerability scanning (cargo-audit), dependency management enforcement (cargo-deny), supply chain verification (cargo-vet), static analysis (clippy + Miri), and fuzzing (cargo-fuzz).
## Recommended Stack
### Core Security Audit Tools
| Tool | Version | Purpose | Why Recommended |
|------|---------|---------|-----------------|
| cargo-audit | 0.10+ | Scans Cargo.lock for crates with known security vulnerabilities in the RustSec Advisory Database | Essential first line of defense - catches vulnerable dependencies before deployment |
| cargo-deny | 0.14+ | Lints dependency graph for security policies, licenses, duplicate versions, sources | Enforces organizational security policies at build time |
| cargo-vet | Latest | Audits third-party dependencies via trusted audit sharing | Prevents supply chain attacks by requiring verified dependencies |
| Miri | Nightly | Interprets Rust MIR to detect undefined behavior in unsafe code | Catches memory safety bugs, use-after-free, data races in unsafe blocks |
| cargo-fuzz | Latest | libFuzzer-based fuzzing for Rust | Finds crashes and panics from malformed inputs |
| clippy | Stable | 750+ lints for common mistakes, performance issues, style | Catches code quality issues that could become security problems |
### Supporting Security Tools
| Library | Version | Purpose | When to Use |
|---------|---------|---------|-------------|
| cargo-auditable | Latest | Embeds dependency tree into binaries for production auditing | Critical for auditing deployed binaries |
| bindgen | Latest | Generates Rust FFI bindings from C headers | Required if auditing C PAM module or TPM bindings |
|afl.rs | Latest | American Fuzzy Lop fuzzer alternative | When cargo-fuzz doesn't fit your use case |
| loom | Latest | Permutation testing for concurrent Rust code | For thorough testing of async/TPM concurrency code |
| grcov | Latest | Code coverage for fuzzing | Measuring fuzz test effectiveness |
### Development/Analysis Tools
| Tool | Purpose | Notes |
|------|---------|-------|
| rust-analyzer | IDE integration, LSP for code navigation | Enables deep code inspection during audit |
| cargo-semver-checks | Detects breaking changes in dependencies | Important for upgrade safety |
| cargo-outdated | Checks for outdated dependencies | Part of regular maintenance |
---
## Detailed Tool Analysis
### 1. cargo-audit — Dependency Vulnerability Scanner
**What it does:** Scans Cargo.lock files against the RustSec Advisory Database for known vulnerabilities in dependencies.
**Key capabilities:**
- Detects vulnerable crate versions
- Provides remediation guidance (upgrade paths)
- Supports `--fix` flag for automatic updates
- Can audit compiled binaries via `cargo audit bin`
**For Linux Hello:** Essential for catching vulnerabilities in dependencies like `aes-gcm`, `tokio`, `zbus`, `ort` (ONNX Runtime), and `tss-esapi` (TPM).
**Installation:**
```bash
cargo install cargo-audit --locked
cargo audit
```
**Configuration:** Create `audit.toml` to ignore specific advisories that don't affect your security model:
```toml
[ignore]
RUSTSEC-0000-0000 = "Description of why ignored"
```
---
### 2. cargo-deny — Dependency Policy Enforcement
**What it does:** Lints the entire dependency graph against configurable policies.
**Key capabilities:**
- **advisories check:** Mirror of cargo-audit but integrated into build policy
- **bans check:** Detect and ban specific crates, duplicate versions, or circular deps
- **licenses check:** Enforce allowed license types (critical for compliance)
- **sources check:** Control where dependencies can be downloaded from
**For Linux Hello:** Important for:
- Banning unsafe crates or known-problematic versions
- Enforcing license compliance (project likely uses Apache/MIT)
- Preventing multiple versions of cryptographic libraries
**Installation:**
```bash
cargo install cargo-deny
cargo deny init # Creates deny.toml
cargo deny check
```
---
### 3. cargo-vet — Supply Chain Security
**What it does:** Verifies that third-party dependencies have been audited by trusted entities.
**Key capabilities:**
- Share audits with the community (public crates)
- Record relative audits (version-to-version diffs)
- Wildcard trusts for trusted publishers
- CI integration for enforcement
**For Linux Hello:** Critical for a security-sensitive biometric system:
- Verify ONNX Runtime bindings are properly audited
- Ensure TPM libraries (tss-esapi) are trusted
- Build audit trail for compliance
**Installation:**
```bash
cargo install cargo-vet
cargo vet init
```
**Note:** cargo-vet requires ongoing maintenance - factor into audit timeline.
---
### 4. Miri — Undefined Behavior Detector
**What it does:** Executes Rust code in an interpreter that detects undefined behavior.
**Key capabilities:**
- Detects out-of-bounds memory accesses
- Catches use-after-free and double-free
- Validates unsafe code requirements (Stacked Borrows)
- Detects data races in concurrent code
- Finds uninitialized memory usage
**For Linux Hello:** Critical for auditing:
- `secure_memory.rs` - zeroization and memory locking
- `secure_template_store.rs` - encryption operations
- TPM FFI bindings
- Any unsafe blocks throughout the codebase
**Installation:**
```bash
rustup +nightly component add miri
cargo +nightly miri install
```
**Usage:**
```bash
cargo +nightly miri test
cargo +nightly miri run
```
**Important limitations:**
- No networking support (can be enabled with `-Zmiri-disable-isolation`)
- Slow execution (interpreter)
- Doesn't work with native/C-rate libraries
---
### 5. cargo-fuzz — Fuzz Testing
**What it does:** Provides libFuzzer integration for Rust projects.
**Key capabilities:**
- Structure-aware fuzzing with arbitrary types
- Coverage tracking
- Corpus minimization
- CI integration
**For Linux Hello:** Fuzz target candidates:
- Template parsing/loading (secure_template_store)
- Config file parsing (linux-hello-common)
- D-Bus message handling
- IPC protocol parsing
- Face embedding matching algorithm
**Installation:**
```bash
cargo install cargo-fuzz
```
**Usage:**
```bash
cargo fuzz init # Creates fuzz directory
cargo fuzz run fuzz_target_name
```
---
### 6. clippy — Static Analysis Lints
**What it does:** Provides 750+ lints covering correctness, style, performance, and security.
**Security-relevant lints:**
- `clippy::unwrap_used` - suggests safe alternatives to panics
- `clippy::dangling_pointer` - detects potential dangling references
- `clippy::mem_forget` - detects potential memory leaks
- `clippy::unsafe_derive_deserialize` - warns about unsafe deserialization
**For Linux Hello:** Run regularly throughout codebase:
```bash
cargo clippy --all-targets -- -D warnings
```
---
### 7. cargo-auditable — Production Binary Auditing
**What it does:** Embeds dependency tree metadata into compiled binaries.
**Key capabilities:**
- ~4KB overhead even for large dependency trees
- Enables `cargo audit` to work on production binaries
- Integrates with Trivy, Grype, osv-scanner
**For Linux Hello:** Essential for deployed systems:
```bash
cargo auditable build --release
# Later, audit the binary
cargo audit bin target/release/linux-hello-daemon
```
---
## Security Audit Workflow
### Phase 1: Dependency Scanning (Day 1)
```bash
# 1. Audit dependencies for vulnerabilities
cargo audit
# 2. Check against security policies
cargo deny check
# 3. Verify supply chain
cargo vet
```
### Phase 2: Static Analysis (Days 1-3)
```bash
# 1. Full clippy with strict warnings
cargo clippy --all-targets -- -D warnings -W clippy::all
# 2. Miri for undefined behavior (requires nightly)
cargo +nightly miri test
cargo +nightly miri test --lib
# 3. Check for outdated dependencies
cargo outdated
```
### Phase 3: Fuzzing (Days 3-7)
```bash
# Set up fuzz targets in fuzz/fuzz_targets/
cargo fuzz run <target>
# Run with coverage
cargo fuzz coverage <target>
```
### Phase 4: Manual Security Review
Areas requiring manual review for Linux Hello:
1. TPM integration (`tpm.rs`) - FFI safety, error handling
2. Secure memory implementation (`secure_memory.rs`) - zeroization, locking
3. Template encryption (`secure_template_store.rs`) - crypto implementation
4. Anti-spoofing logic (`anti_spoofing.rs`) - detection bypass vectors
5. IPC authorization (`ipc.rs`) - privilege escalation
---
## Alternatives Considered
| Recommended | Alternative | When to Use Alternative |
|-------------|-------------|------------------------|
| cargo-audit | trivy (aquasecurity) | Already using Trivy for container scanning |
| cargo-fuzz | AFL++ | Need cross-platform fuzzing support |
| cargo-vet | cargo-crev | Prefer decentralized trust model |
| Miri | Kani model checker | Need formal verification (higher effort) |
| clippy | rustc built-in | CI environments without clippy |
---
## What NOT to Use
| Avoid | Why | Use Instead |
|-------|-----|-------------|
| cargo-audit (older than 0.10) | Missing vulnerability database updates | cargo-audit 0.10+ |
| Miri without nightly | Miri requires nightly toolchain | Use stable for other tools, nightly only for Miri |
| Fuzzing without corpus | Inefficient, misses edge cases | Build corpus with known inputs |
| Ignoring clippy warnings | Technical debt, potential bugs | Fix or document exceptions |
---
## Version Compatibility
| Tool | MSRV | Notes |
|------|------|-------|
| cargo-audit | Rust 1.74+ | Required for JSON vulnerability output |
| cargo-deny | Rust 1.70+ | Check changelog for latest |
| cargo-vet | Rust 1.70+ | Actively maintained |
| Miri | Nightly only | Updates with Rust compiler |
| cargo-fuzz | Nightly only | Uses LLVM sanitizers |
| clippy | Stable (matches rustc) | Part of Rust toolchain |
| cargo-auditable | Rust 1.66+ | Check for latest version requirements |
---
## Sources
- **RustSec Advisory Database**: https://rustsec.org/ — Official Rust security advisories (HIGH confidence)
- **cargo-audit README**: https://github.com/rustsec/rustsec/tree/main/cargo-audit — Tool documentation (HIGH confidence)
- **cargo-deny Documentation**: https://embarkstudios.github.io/cargo-deny/ — Policy enforcement guide (HIGH confidence)
- **Rust Fuzz Book**: https://rust-fuzz.github.io/book/ — Official fuzzing documentation (HIGH confidence)
- **Miri GitHub**: https://github.com/rust-lang/miri — Undefined behavior detector (HIGH confidence)
- **Clippy Documentation**: https://doc.rust-lang.org/clippy/ — 750+ lints reference (HIGH confidence)
- **cargo-vet Documentation**: https://mozilla.github.io/cargo-vet/ — Supply chain security (HIGH confidence)
- **cargo-auditable**: https://github.com/rust-secure-code/cargo-auditable — Production binary auditing (HIGH confidence)
---
*Stack research for: Rust Security Audit Tools*
*Researched: 2026-02-14*

View File

@@ -1,159 +0,0 @@
# Project Research Summary
**Project:** Linux Hello — Biometric Authentication System Security Audit
**Domain:** Security Audit Framework for Rust Biometric Systems
**Researched:** 2026-02-14
**Confidence:** HIGH
## Executive Summary
This document synthesizes research for conducting a security audit of Linux Hello, a Rust-based biometric authentication system with face detection, TPM integration, secure memory handling, and encrypted template storage. The research identifies five critical audit phases spanning 8-12 weeks, with particular emphasis on biometric-specific vulnerabilities (presentation attack detection, template encryption, secure memory) that are often overlooked in standard security audits.
The recommended approach layers multiple tool categories: dependency vulnerability scanning (cargo-audit, cargo-deny), supply chain verification (cargo-vet), static analysis (clippy + Miri), fuzzing (cargo-fuzz), and manual cryptographic review. Critical audit areas include biometric PAD testing (often inadequately performed), FAR/FRR verification, template storage encryption, timing attack prevention, rate limiting, and IPC authorization. The highest-risk pitfalls are treating PAD as optional, ignoring FAR/FRR operational implications, weak template storage, and missing constant-time operations in template matching.
## Key Findings
### Recommended Stack
The Rust ecosystem provides excellent security tooling maintained by the Rust Secure Code Working Group. The recommended approach layers multiple tools: dependency vulnerability scanning (cargo-audit), dependency management enforcement (cargo-deny), supply chain verification (cargo-vet), static analysis (clippy + Miri), and fuzzing (cargo-fuzz).
**Core security audit tools:**
- **cargo-audit (0.10+)** — Scans Cargo.lock for crates with known security vulnerabilities in the RustSec Advisory Database; essential first line of defense
- **cargo-deny (0.14+)** — Lints dependency graph for security policies, licenses, duplicate versions; enforces organizational security policies at build time
- **cargo-vet (latest)** — Audits third-party dependencies via trusted audit sharing; prevents supply chain attacks
- **Miri (nightly)** — Interprets Rust MIR to detect undefined behavior in unsafe code; catches memory safety bugs, use-after-free, data races
- **cargo-fuzz (latest)** — libFuzzer-based fuzzing for Rust; finds crashes and panics from malformed inputs
- **clippy (stable)** — 750+ lints for common mistakes, performance issues, style; catches code quality issues that could become security problems
- **cargo-auditable (latest)** — Embeds dependency tree into binaries for production auditing; critical for auditing deployed binaries
### Expected Features
**Critical audit areas (must audit):**
- **Biometric Presentation Attack Detection (PAD)** — IR liveness check, depth estimation, texture analysis, blink detection, movement check, deepfake injection; primary attack vector against biometric systems
- **Template Storage Encryption** — TPM binding, software fallback security (PBKDF2-HMAC-SHA256 with 600k iterations), key derivation, IV/nonce management
- **Secure Memory Handling** — Memory zeroization, swap prevention (mlock), timing attack prevention (constant-time comparison via subtle crate), debug information leak prevention
- **IPC Authorization and Rate Limiting** — Peer credential validation (SO_PEERCRED), authorization boundaries, rate limiting (MAX_CONNECTIONS_PER_SECOND = 10), message size limits
- **Face Detection and Matching Security** — FAR/FRR verification per FIDO requirements (<1% Level 1, <0.01% Level 2), template unlinkability, embedding extraction protection
**Optional audit areas (nice-to-audit):**
- TPM hardware security (feature-gated)
- Camera subsystem security
- Session management
- D-Bus interface security
- PAM module integration
### Architecture Approach
The recommended audit architecture follows a phased approach combining OWASP methodologies with Rust-specific security considerations and biometric authentication domain expertise. Structure the audit in five sequential phases: Architecture Review → Code Analysis → Cryptographic Review → Biometric-Specific Audit → Integration Testing. This ordering ensures foundational issues are identified before detailed component-specific analysis.
**Major components to audit:**
1. **IPC Layer** (`ipc.rs`) — Unix socket communication, peer credential validation, rate limiting
2. **Template Storage** (`secure_template_store.rs`, `tpm.rs`) — AES-256-GCM encryption, TPM integration, key derivation
3. **Secure Memory** (`secure_memory.rs`) — Zeroization, memory locking, constant-time operations
4. **Anti-Spoofing** (`anti_spoofing.rs`) — Liveness detection, PAD signals
5. **ONNX Integration** — Model loading, inference, integrity verification
### Critical Pitfalls
1. **Inadequate PAD Testing** — Auditors assume if biometric matching works, the system is secure. Without proper PAD testing (photos, videos, masks, deepfakes), systems can be easily defeated. Verify multiple PAD signals, test with realistic attack instruments, check PAD rate limiting.
2. **Ignoring FAR/FRR Tradeoffs** — Auditors accept stated FAR/FRR numbers without operational security understanding. A 0.01% FAR system is vulnerable to bulk attacks without rate limiting. Verify FAR claims independently, understand attack model, check rate limiting.
3. **Weak Template Storage** — Biometric templates stored without proper protection cannot be revoked like passwords. Verify hardware-bound keys (TPM), non-exportable templates, AES-256-GCM with proper key derivation.
4. **Timing Attack Vulnerabilities** — Template comparison using non-constant-time operations leaks information through timing differences. Verify use of `subtle` crate for constant-time operations.
5. **Missing Rate Limiting** — Biometric authentication lacks rate limiting common in password auth. Attackers can make unlimited attempts. Verify account lockout, re-enrollment requires strong auth, exponential backoff.
6. **IPC Security Gaps** — Unix sockets assumed secure without proper peer credential validation. Verify SO_PEERCRED validation, message signing, authorization checks.
7. **Insecure Camera Input** — Camera input not validated allowing injection of pre-recorded video. Verify frame metadata validation, IR/RGB camera binding, camera enumeration restrictions.
## Implications for Roadmap
Based on research, the suggested phase structure for the security audit:
### Phase 1: Architecture & Threat Modeling (Week 1-2)
**Rationale:** Establish security context and identify attack surface before code review; foundational for all subsequent phases
**Delivers:** System DFD with trust boundaries, STRIDE threat analysis, attack surface enumeration, control mapping document
**Addresses:** All critical audit areas require understanding of system boundaries first
**Avoids:** Pitfall 6 (IPC Security Gaps) — understand IPC boundaries before auditing
### Phase 2: Rust-Specific Code Security Review (Week 2-4)
**Rationale:** Identify Rust-specific vulnerabilities and unsafe code issues before deep-diving into crypto/biometric specifics
**Delivers:** Unsafe code inventory, OWASP vulnerability pattern findings, input validation verification
**Uses:** cargo-audit, cargo-deny, clippy, Miri, cargo-geiger
**Implements:** Code analysis of all modules focusing on unsafe blocks, FFI boundaries, standard vulnerability patterns
### Phase 3: Cryptographic Implementation Audit (Week 4-5)
**Rationale:** Verify cryptographic implementations follow best practices; depends on Phase 2 understanding of key management code
**Delivers:** Algorithm verification, key management review, constant-time operations check
**Addresses:** Template storage encryption, secure memory handling
**Avoids:** Pitfall 3 (Weak Template Storage), Pitfall 4 (Timing Attack Vulnerabilities)
### Phase 4: Biometric-Specific Security Audit (Week 5-6)
**Rationale:** Address unique biometric authentication concerns; requires crypto review completion
**Delivers:** Anti-spoofing verification, template security review, liveness detection assessment
**Addresses:** Biometric PAD, face matching FAR/FRR, template security
**Avoids:** Pitfall 1 (Inadequate PAD Testing), Pitfall 2 (Ignoring FAR/FRR Tradeoffs)
### Phase 5: Integration & Penetration Testing (Week 6-8)
**Rationale:** Validate security in realistic attack scenarios; requires all previous phases complete
**Delivers:** Component interaction testing, penetration testing results, fuzzing campaign findings
**Addresses:** PAM module integration, D-Bus interface, camera capture, rate limiting verification
**Avoids:** Pitfall 5 (Missing Rate Limiting), Pitfall 7 (Insecure Camera Input)
### Phase Ordering Rationale
- **Why this order:** Each phase builds on findings from previous phases — threat model informs code review focus, code review identifies crypto-relevant areas, crypto review enables biometric-specific analysis
- **Why this grouping:** Rust-specific tools (Phase 2) before specialized biometric analysis (Phase 4); integration testing last requires complete understanding
- **How this avoids pitfalls:** By treating PAD as integral to architecture (Phase 1), verifying FAR/FRR independently (Phase 4), checking template encryption early (Phase 3), testing rate limiting end-to-end (Phase 5)
### Research Flags
Phases likely needing deeper research during planning:
- **Phase 4 (Biometric-Specific):** FAR/FRR testing requires large dataset (245 subjects minimum for Level 2 per FIDO); PAD testing requires specific PAI species testing; may need specialized expertise or tools
- **Phase 5 (Integration Testing):** D-Bus fuzzing requires specific tooling research; PAM module interaction testing needs Linux authentication expertise
Phases with standard patterns (skip research-phase):
- **Phase 2 (Rust Code Review):** Well-documented patterns from OWASP, Rust security guidelines established
- **Phase 3 (Cryptographic Audit):** Standard cryptographic review patterns, NIST/FIPS guidelines apply
## Confidence Assessment
| Area | Confidence | Notes |
|------|------------|-------|
| Stack | HIGH | Rust Secure Code Working Group tools, official documentation, well-established |
| Features | HIGH | Based on NIST SP 800-63-4, FIDO Biometrics Requirements v4.1, industry standards |
| Architecture | HIGH | OWASP methodologies combined with Rust-specific considerations, clear phased approach |
| Pitfalls | HIGH | Based on NIST/FIDO standards, real-world biometric audit experience documented |
**Overall confidence:** HIGH — All research based on official standards (NIST, FIDO, OWASP), established Rust tooling, and industry best practices.
### Gaps to Address
- **FAR/FRR Testing Dataset:** Research assumes access to test dataset; actual testing requires 245+ subjects for Level 2 verification — this may require contracting or specialized lab access
- **PAD Testing Expertise:** Deepfake/mask testing requires specialized knowledge and attack instruments — may need external penetration testers
- **TPM Hardware:** Testing actual TPM hardware vs software fallback requires physical access to TPM-enabled machine
## Sources
### Primary (HIGH confidence)
- **NIST SP 800-63B/63-4** — Digital Identity Guidelines for biometric authentication requirements
- **FIDO Biometrics Requirements v4.1** — Industry certification requirements for biometric systems
- **RustSec Advisory Database** — Official Rust security advisories
- **OWASP Secure Code Review Guide** — Standard security review methodology
- **The Rustonomicon** — Rust unsafe code patterns
### Secondary (HIGH confidence)
- **cargo-audit, cargo-deny, cargo-vet documentation** — Tool-specific guidance
- **Miri GitHub** — Undefined behavior detection
- **ISO/IEC 19795-1:2021** — Biometric performance testing
- **ISO/IEC 30107-1:2023** — Biometric presentation attack detection framework
### Tertiary (HIGH confidence)
- **Project Code Analysis** — linux-hello-daemon source code review (used for feature mapping)
---
*Research completed: 2026-02-14*
*Ready for roadmap: yes*

View File

@@ -1,87 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.1.0] - 2026-01-30
### Added
- **Core Authentication**
- Face detection with LBPH algorithm (default) or ONNX models (optional)
- Face embedding extraction and template matching
- Multi-template support per user (e.g., with/without glasses)
- Configurable distance thresholds
- **Security Features**
- TPM2 integration for hardware-bound template encryption
- AES-256-GCM software fallback when TPM unavailable
- Secure memory handling with automatic zeroization
- Constant-time comparison for security-sensitive operations
- Memory locking to prevent swapping sensitive data
- **Anti-Spoofing**
- IR presence validation
- Depth estimation (gradient-based)
- Texture analysis (LBP-based)
- Blink detection
- Micro-movement tracking
- Configurable thresholds per check
- **Camera Support**
- V4L2 camera enumeration
- IR camera detection heuristics
- IR emitter control
- Multiple pixel format support (GREY, YUYV, MJPEG)
- **IPC & Integration**
- Unix socket IPC for PAM module communication
- D-Bus interface for desktop integration
- Peer credential verification
- Rate limiting
- **CLI Tool**
- `capture` - Capture test frames
- `detect` - Test face detection
- `status` - Show system status
- `enroll` - Enroll a face
- `list` - List enrolled templates
- `remove` - Remove templates
- `test` - Test authentication
- `config` - View/modify configuration
- **PAM Module**
- C implementation for maximum compatibility
- Configurable timeout
- Password fallback support
- Debug logging
- **Settings Apps**
- GNOME Settings app (GTK4/libadwaita)
- KDE System Settings module (Qt6/KCM)
- **Documentation**
- Comprehensive README
- API documentation
- Testing guide
- Coding standards
- Security policy
### Security Notes
- Requires IR camera for security - RGB cameras explicitly not supported
- TPM2 recommended for production deployments
- Software fallback encryption is NOT cryptographically bound to hardware
### Known Limitations
- ONNX models require glibc 2.38+ (Ubuntu 24.04+, Fedora 39+)
- IR emitter control may require hardware-specific configuration
- Full TPM hardware integration needs real TPM for testing
[Unreleased]: https://github.com/YOUR_USERNAME/linux-hello/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/YOUR_USERNAME/linux-hello/releases/tag/v0.1.0

View File

@@ -1,164 +0,0 @@
# Safety-Critical Coding Standards
This document outlines the safety-critical coding standards applied to Linux Hello, based on MISRA C and similar standards, adapted for both C and Rust code.
## Principles Applied
### 1. Simple Control Flow
-**C**: No goto, setjmp, longjmp, or recursion
-**Rust**: Avoid recursion where possible; use iterative solutions. Rust's ownership system prevents many control flow issues.
### 2. Fixed Loop Bounds
-**C**: All loops have fixed upper bounds (e.g., `MAX_ARGS = 32`)
-**Rust**: Use bounded iterators, `take()`, or explicit bounds. Example:
```rust
for item in items.iter().take(MAX_ITEMS) { ... }
```
### 3. No Dynamic Memory After Init
- ✅ **C**: No malloc/free after startup (stack allocation only)
- ⚠️ **Rust**: Rust's allocator is safer, but we still prefer:
- Pre-allocated buffers where possible
- `Vec::with_capacity()` to avoid reallocations
- Stack allocation for small data
### 4. Function Length Limit (~60 lines)
- ✅ **C**: All functions under 60 lines
- ✅ **Rust**: Same principle - break complex functions into smaller, testable units
### 5. Runtime Assertions (2+ per function)
- ✅ **C**: Using `assert()` and `assert_condition()` helper
- ✅ **Rust**: Use `debug_assert!()`, `assert!()`, and `unwrap_or_else()` with validation
### 6. Smallest Scope for Data
- ✅ **C**: Declare variables at smallest possible scope
- ✅ **Rust**: Rust enforces this - variables are scoped to blocks
### 7. Check All Return Values
- ✅ **C**: All function returns checked, void casts for intentional ignores
- ✅ **Rust**: Use `Result<T, E>` and `Option<T>` - compiler enforces checking
### 8. Minimal Preprocessor
- ✅ **C**: Only `#include` and simple `#define` constants
- ✅ **Rust**: Use `cfg!()` and `#[cfg(...)]` attributes instead of macros
### 9. Restricted Pointer Use
- ✅ **C**: Single level dereferencing only, no function pointers unless essential
- ✅ **Rust**: Rust's references are safer, but we still:
- Avoid deep nesting (`&&&T`)
- Prefer owned types over references where possible
- Use function pointers only when necessary (e.g., trait objects)
### 10. Strictest Warnings
- ✅ **C**: `-Wall -Wextra -Werror -Wpedantic` + static analysis
- ✅ **Rust**: `#![deny(warnings)]` in critical modules, `clippy` with pedantic lints
## Implementation Status
### C PAM Module (`pam-module/pam_linux_hello.c`)
✅ **Fully compliant**:
- Split `authenticate_face()` into smaller functions
- Fixed loop bounds (`MAX_ARGS = 32`)
- All return values checked
- Runtime assertions added
- Strictest compiler warnings enabled
- Single-level pointer dereferencing
- No dynamic allocation after init
### Rust Codebase
🔄 **In Progress** - Applying equivalent principles:
#### Completed:
- ✅ Return values checked (Rust enforces this)
- ✅ Small scope (Rust enforces this)
- ✅ No goto/setjmp (not applicable in Rust)
- ✅ Minimal preprocessor (Rust uses attributes)
#### To Improve:
- ⏳ Function length limits (some functions > 60 lines)
- ⏳ Fixed loop bounds (some iterators unbounded)
- ⏳ More runtime assertions
- ⏳ Enable strictest Rust lints
## Rust-Specific Safety Measures
### Memory Safety
- Rust's ownership system prevents use-after-free, double-free
- No manual memory management needed
- `unsafe` blocks are minimal and documented
### Type Safety
- Strong typing prevents many classes of bugs
- Pattern matching ensures exhaustive handling
- `Result` and `Option` enforce error handling
### Bounds Checking
- Array/vector bounds checked at runtime (can be disabled with `unsafe`)
- Iterator bounds enforced by type system
## Static Analysis
### C Code
```bash
# Compile with strictest warnings
make CFLAGS="-Wall -Wextra -Werror -Wpedantic ..."
# Run static analysis
cppcheck --enable=all pam-module/pam_linux_hello.c
splint pam-module/pam_linux_hello.c
```
### Rust Code
```bash
# Clippy with pedantic lints
cargo clippy -- -W clippy::pedantic
# Deny warnings in release
RUSTFLAGS="-D warnings" cargo build --release
```
## Code Review Checklist
- [ ] No functions > 60 lines
- [ ] All loops have fixed bounds
- [ ] All return values checked
- [ ] Minimum 2 assertions per function
- [ ] Variables at smallest scope
- [ ] No recursion (unless essential)
- [ ] Single-level pointer/reference dereferencing
- [ ] Compiles with strictest warnings
- [ ] Passes static analysis
## Examples
### Good: Fixed Loop Bound
```rust
const MAX_ITEMS: usize = 100;
for item in items.iter().take(MAX_ITEMS) {
// Process item
}
```
### Good: Assertions
```rust
fn process_data(data: &[u8]) -> Result<()> {
debug_assert!(!data.is_empty(), "Data must not be empty");
debug_assert!(data.len() <= MAX_SIZE, "Data exceeds maximum size");
// ... processing
}
```
### Good: Small Functions
```rust
// Instead of one 100-line function, split:
fn validate_input(input: &str) -> Result<()> { ... } // 20 lines
fn parse_input(input: &str) -> Result<Data> { ... } // 25 lines
fn process_data(data: Data) -> Result<Output> { ... } // 30 lines
```
## References
- MISRA C:2012 Guidelines
- CERT C Coding Standard
- Rust API Guidelines
- Safety-Critical Software Development

View File

@@ -1,422 +0,0 @@
# Testing Linux Hello on Your Linux Computer
This guide will help you test Linux Hello on your system. We'll start with safe CLI testing before any system-level installation.
## Prerequisites
### Install Required Packages
**Debian/Ubuntu:**
```bash
sudo apt update
sudo apt install -y \
build-essential \
libpam0g-dev \
v4l-utils \
pkg-config \
libssl-dev
```
**Fedora/RHEL:**
```bash
sudo dnf install -y \
gcc \
make \
pam-devel \
v4l-utils \
pkgconfig \
openssl-devel
```
**Arch Linux:**
```bash
sudo pacman -S \
base-devel \
pam \
v4l-utils \
pkgconf \
openssl
```
### Install Rust
If you don't have Rust installed:
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
```
---
## Step 1: Build the Project
```bash
# Clone or navigate to the project directory
cd Linux-Hello
# Build in release mode (works on any Linux)
cargo build --release
# Or with ONNX ML support (requires glibc 2.38+ / Ubuntu 24.04+)
cargo build --release --features onnx
```
This will create:
- `target/release/linux-hello` (CLI tool)
- `target/release/linux-hello-daemon` (daemon)
### Build Options
| Build | Command | Requirements |
|-------|---------|--------------|
| Default | `cargo build --release` | Any Linux |
| With ONNX | `cargo build --release --features onnx` | glibc 2.38+ |
| With TPM | `cargo build --release --features tpm` | TPM2 libraries |
---
## Step 2: Test Without Installation (Safest)
You can test most features without installing anything system-wide.
### 2.1 Check Camera Detection
```bash
# Run the CLI tool directly
./target/release/linux-hello status --camera
```
**Expected output:**
- Lists available cameras
- Shows IR camera detection
- May show "No cameras found" if no camera is connected
**Note:** Works even without a camera (will show empty list or use mock).
### 2.2 Test Configuration
```bash
# View default configuration
./target/release/linux-hello config
# View as JSON
./target/release/linux-hello config --json
```
### 2.3 Capture Test Frames (if camera available)
```bash
# Create a test directory
mkdir -p ~/test-frames
# Capture 5 frames
./target/release/linux-hello capture --output ~/test-frames --count 5
```
**Expected:** Creates PNG files in `~/test-frames/` (if camera available).
### 2.4 Test Face Detection (with image file)
```bash
# Test detection on a photo
./target/release/linux-hello detect --image ~/test-frames/frame_000.png --output ~/detected.png
```
**Expected:**
- With ONNX models: Accurate face detection with bounding boxes
- Without ONNX: Basic placeholder detection (unreliable)
---
## Step 3: Test with Daemon (Manual Start)
Before installing system-wide, test the daemon manually:
### 3.1 Start Daemon Manually
```bash
# Create runtime directory
sudo mkdir -p /run/linux-hello
sudo chmod 777 /run/linux-hello # For testing only!
# Start daemon in foreground (to see logs)
sudo ./target/release/linux-hello-daemon
```
**Keep this terminal open** - you'll see daemon logs.
### 3.2 Test Enrollment (in another terminal)
```bash
# In a new terminal, test enrollment
./target/release/linux-hello enroll --label test
```
**Expected:**
- Captures frames from camera
- Runs anti-spoofing checks
- Creates face template
- Stores encrypted in `/var/lib/linux-hello/templates/`
### 3.3 Test Authentication
```bash
# Test authentication
./target/release/linux-hello test
```
**Expected:**
- Captures frame from camera
- Runs face detection
- Compares with enrolled template
- Reports success/failure with confidence score
### 3.4 List Enrolled Templates
```bash
./target/release/linux-hello list
```
---
## Step 4: Full Installation (Optional)
**Warning:** This modifies system PAM configuration. Test in a VM or have a recovery plan.
### 4.1 Build PAM Module
```bash
cd pam-module
make
```
### 4.2 Install Components
```bash
# Install PAM module
sudo make install
# Install daemon and CLI
sudo cp ../target/release/linux-hello-daemon /usr/libexec/
sudo cp ../target/release/linux-hello /usr/bin/
sudo chmod +x /usr/libexec/linux-hello-daemon /usr/bin/linux-hello
# Install systemd service
sudo cp ../dist/linux-hello.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable linux-hello.service
sudo systemctl start linux-hello.service
# Install D-Bus configuration
sudo cp ../dist/org.linuxhello.Daemon.conf /etc/dbus-1/system.d/
sudo cp ../dist/org.linuxhello.Daemon.service /usr/share/dbus-1/system-services/
# Install configuration
sudo mkdir -p /etc/linux-hello
sudo cp ../dist/config.toml /etc/linux-hello/
```
### 4.3 Configure PAM (CAREFUL!)
**Backup first:**
```bash
sudo cp /etc/pam.d/common-auth /etc/pam.d/common-auth.backup
```
**Edit PAM config:**
```bash
sudo nano /etc/pam.d/common-auth
```
Add at the top:
```
auth sufficient pam_linux_hello.so debug fallback=password
auth required pam_unix.so use_first_pass
```
**Test login:**
- Try logging out and back in
- Face authentication will be attempted first
- Falls back to password if it fails
---
## Step 5: ONNX Model Setup (For Real Face Recognition)
For accurate face recognition, you need ONNX models:
### 5.1 Check System Requirements
ONNX support requires **glibc 2.38+**:
- Ubuntu 24.04 or later
- Fedora 39 or later
- Arch Linux (rolling release)
```bash
# Check your glibc version
ldd --version
```
### 5.2 Download Models
See [models/README.md](models/README.md) for model download instructions.
### 5.3 Build with ONNX
```bash
cargo build --release --features onnx
```
---
## Step 6: Troubleshooting
### Daemon Won't Start
```bash
# Check if socket directory exists
ls -la /run/linux-hello/
# Check daemon logs
sudo journalctl -u linux-hello.service -f
```
### Camera Not Detected
```bash
# List V4L2 devices
v4l2-ctl --list-devices
# Check permissions
ls -la /dev/video*
# May need to add user to video group
sudo usermod -aG video $USER
# Log out and back in
```
### Permission Errors
```bash
# Template storage directory
sudo mkdir -p /var/lib/linux-hello/templates
sudo chmod 755 /var/lib/linux-hello/templates
# Runtime directory
sudo mkdir -p /run/linux-hello
sudo chmod 755 /run/linux-hello
```
### PAM Module Issues
```bash
# Check if module is installed
ls -la /lib/x86_64-linux-gnu/security/pam_linux_hello.so
# Check PAM logs
sudo tail -f /var/log/auth.log
# or
sudo journalctl -f | grep pam
```
### ONNX Linking Errors
If you see errors about `__isoc23_strtoll`:
- Your system has glibc < 2.38
- Use the default build (without `--features onnx`)
- Or upgrade to Ubuntu 24.04+ / Fedora 39+
---
## Step 7: Running Tests
```bash
# Run all tests
cargo test
# Run specific test suites
cargo test --test phase3_security_test
cargo test --test phase2_auth_test
# Run with output
cargo test -- --nocapture
# Run benchmarks
cargo bench -p linux-hello-daemon
```
---
## Step 8: Cleanup (If Needed)
### Remove Installation
```bash
# Stop and disable service
sudo systemctl stop linux-hello.service
sudo systemctl disable linux-hello.service
# Remove PAM module
cd pam-module
sudo make uninstall
# Remove binaries
sudo rm /usr/libexec/linux-hello-daemon
sudo rm /usr/bin/linux-hello
# Remove service file
sudo rm /etc/systemd/system/linux-hello.service
sudo systemctl daemon-reload
# Remove D-Bus files
sudo rm /etc/dbus-1/system.d/org.linuxhello.Daemon.conf
sudo rm /usr/share/dbus-1/system-services/org.linuxhello.Daemon.service
# Restore PAM config
sudo cp /etc/pam.d/common-auth.backup /etc/pam.d/common-auth
```
---
## Safety Recommendations
1. **Test in a VM first** - Don't test on your main system
2. **Keep password fallback** - Always have `fallback=password` in PAM config
3. **Backup PAM configs** - Before modifying `/etc/pam.d/`
4. **Test logout/login** - In a separate session (don't lock yourself out)
5. **Use TPM for production** - Software fallback is for development only
---
## Quick Test Checklist
- [ ] Project builds successfully
- [ ] CLI tool runs (`./target/release/linux-hello status`)
- [ ] Camera enumeration works (or shows empty list)
- [ ] Configuration displays correctly
- [ ] Daemon starts manually
- [ ] Enrollment works (creates template)
- [ ] Authentication test runs
- [ ] Tests pass (`cargo test`)
---
## What Works With/Without ONNX
### Default Build (No ONNX)
- All infrastructure and security features
- Camera capture and IR control
- Anti-spoofing framework
- Template encryption (AES-256-GCM)
- IPC and D-Bus communication
- **Placeholder** face detection/embedding (not accurate)
### With ONNX Models
- Accurate face detection (RetinaFace)
- Accurate face embedding (MobileFaceNet)
- Production-ready face recognition
- Proper anti-spoofing based on real face data
---
**The system is feature-complete.** For production use, build with `--features onnx` on a compatible system and download the ONNX models.

View File

@@ -1,562 +0,0 @@
# Linux Hello API Documentation
This document provides a high-level overview of the Linux Hello API for developers
who want to integrate with, extend, or understand the facial authentication system.
## Table of Contents
- [Architecture Overview](#architecture-overview)
- [Security Model](#security-model)
- [Authentication Flow](#authentication-flow)
- [Crate Structure](#crate-structure)
- [Key APIs](#key-apis)
- [Extension Points](#extension-points)
- [Configuration](#configuration)
- [IPC Protocol](#ipc-protocol)
- [D-Bus API](#d-bus-api)
- [Error Handling](#error-handling)
## Architecture Overview
Linux Hello uses a pipeline architecture for facial authentication:
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Authentication Pipeline │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌───────────┐ ┌─────────────┐ ┌───────────┐ ┌──────────┐ │
│ │ Camera │──▶│ Face │──▶│ Anti- │──▶│ Embedding │──▶│ Template │ │
│ │ Capture │ │ Detection │ │ Spoofing │ │Extraction │ │ Matching │ │
│ └──────────┘ └───────────┘ └─────────────┘ └───────────┘ └──────────┘ │
│ │ │ │ │ │ │
│ ▼ ▼ ▼ ▼ ▼ │
│ camera/ detection/ anti_spoofing/ embedding/ matching/ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
### Components
| Component | Purpose | Module |
|-----------|---------|--------|
| Camera Capture | Acquire IR frames from webcam | `camera` |
| Face Detection | Locate faces in frames | `detection` |
| Anti-Spoofing | Verify liveness (prevent photos/videos) | `anti_spoofing` |
| Embedding Extraction | Generate face feature vector | `embedding` |
| Template Matching | Compare against enrolled templates | `matching` |
## Security Model
Linux Hello implements defense-in-depth security:
### Layer 1: Hardware Security
- **IR Camera Requirement**: Only infrared cameras are accepted
- **TPM Integration**: Templates encrypted with hardware-bound keys
- **PCR Binding**: Optional boot configuration verification
### Layer 2: Biometric Security
- **Anti-Spoofing**: Multiple liveness detection methods
- IR reflection analysis
- Depth estimation
- Texture analysis (LBP)
- Blink detection
- Micro-movement tracking
### Layer 3: Data Security
- **Encrypted Storage**: AES-256-GCM for templates at rest
- **Secure Memory**: Sensitive data zeroized on drop
- **Memory Locking**: Prevents swapping to disk
### Layer 4: Access Control
- **IPC Authorization**: Peer credential verification
- **Rate Limiting**: Prevents brute-force attacks
- **Permission Checks**: Users can only manage their own templates
## Authentication Flow
```
┌──────────────────────────────────────────────────────────────────────────────┐
│ Authentication Sequence │
└──────────────────────────────────────────────────────────────────────────────┘
PAM Module Daemon Storage
│ │ │
│ 1. Authenticate(user) │ │
│───────────────────────▶│ │
│ │ │
│ │ 2. Load templates │
│ │─────────────────────────▶│
│ │ │
│ │ 3. Capture frame │
│ │ ◄──── IR Camera │
│ │ │
│ │ 4. Detect face │
│ │ 5. Anti-spoofing check │
│ │ 6. Extract embedding │
│ │ 7. Match templates │
│ │ │
│ 8. Auth result │ │
│◄───────────────────────│ │
│ │ │
```
## Crate Structure
### linux-hello-common
Shared types and utilities used by all components.
```rust
// Key exports
use linux_hello_common::{
Config, // System configuration
Error, Result, // Error handling
FaceTemplate, // Template data structure
TemplateStore, // File-based storage
};
```
### linux-hello-daemon
Core authentication functionality and services.
```rust
// Camera access
use linux_hello_daemon::{
enumerate_cameras, // List available cameras
Camera, // Camera control
CameraInfo, // Camera metadata
Frame, PixelFormat, // Frame data
};
// Face processing
use linux_hello_daemon::{
FaceDetection, FaceDetect, // Detection types
EmbeddingExtractor, // Embedding trait
cosine_similarity, // Distance metrics
match_template, MatchResult, // Matching
};
// Security
use linux_hello_daemon::{
AntiSpoofingDetector, LivenessResult, // Anti-spoofing
SecureEmbedding, SecureBytes, // Secure memory
TpmStorage, SoftwareTpmFallback, // Encryption
};
// IPC
use linux_hello_daemon::{
IpcServer, IpcClient, // Server/client
IpcRequest, IpcResponse, // Messages
};
```
## Key APIs
### Camera API
```rust
use linux_hello_daemon::{enumerate_cameras, Camera, Frame};
// Find IR camera
let cameras = enumerate_cameras()?;
let ir_camera = cameras.iter()
.find(|c| c.is_ir)
.ok_or("No IR camera found")?;
// Capture frames
let mut camera = Camera::open(&ir_camera.device_path)?;
camera.start()?;
let frame: Frame = camera.capture_frame()?;
```
### Face Detection API
```rust
use linux_hello_daemon::{FaceDetect, SimpleFaceDetector, FaceDetection};
// Create detector
let detector = SimpleFaceDetector::new(0.5); // confidence threshold
// Detect faces
let detections: Vec<FaceDetection> = detector.detect(
&frame.data,
frame.width,
frame.height
)?;
// Convert to pixel coordinates
if let Some(face) = detections.first() {
let (x, y, w, h) = face.to_pixels(frame.width, frame.height);
}
```
### Embedding API
```rust
use linux_hello_daemon::{
EmbeddingExtractor, PlaceholderEmbeddingExtractor,
cosine_similarity, euclidean_distance, similarity_to_distance,
};
use image::GrayImage;
// Extract embedding
let extractor = PlaceholderEmbeddingExtractor::new(128);
let face_image = GrayImage::new(112, 112); // cropped face
let embedding: Vec<f32> = extractor.extract(&face_image)?;
// Compare embeddings
let similarity = cosine_similarity(&embedding1, &embedding2);
let distance = similarity_to_distance(similarity);
```
### Template Matching API
```rust
use linux_hello_daemon::{match_template, MatchResult, average_embeddings};
use linux_hello_common::FaceTemplate;
// Match against stored templates
let result: MatchResult = match_template(
&probe_embedding,
&stored_templates,
0.6 // distance threshold
);
if result.matched {
println!("Match found: {:?}", result.matched_label);
}
// Create averaged template for enrollment
let avg_embedding = average_embeddings(&multiple_embeddings)?;
```
### Anti-Spoofing API
```rust
use linux_hello_daemon::anti_spoofing::{
AntiSpoofingDetector, AntiSpoofingConfig, AntiSpoofingFrame, LivenessResult
};
let config = AntiSpoofingConfig::default();
let mut detector = AntiSpoofingDetector::new(config);
let frame = AntiSpoofingFrame {
pixels: frame_data,
width: 640,
height: 480,
is_ir: true,
face_bbox: Some((x, y, w, h)),
timestamp_ms: 0,
};
let result: LivenessResult = detector.check_frame(&frame)?;
if result.is_live {
// Proceed with authentication
}
```
### Secure Memory API
```rust
use linux_hello_daemon::{SecureEmbedding, SecureBytes};
// Automatically zeroized on drop
let secure_emb = SecureEmbedding::new(embedding);
// Constant-time comparison
let bytes1 = SecureBytes::new(data1);
let bytes2 = SecureBytes::new(data2);
let equal = bytes1.constant_time_eq(&bytes2);
```
### IPC API
```rust
use linux_hello_daemon::ipc::{IpcClient, IpcServer, IpcRequest, IpcResponse};
// Client usage
let client = IpcClient::default();
let response = client.authenticate("username").await?;
if response.success {
println!("Authenticated!");
}
// Server setup
let mut server = IpcServer::new("/run/linux-hello/auth.sock");
server.set_auth_handler(|user| async move {
// Perform authentication
Ok(true)
});
server.start().await?;
```
## Extension Points
### Custom Face Detector
Implement the `FaceDetect` trait:
```rust
use linux_hello_daemon::{FaceDetect, FaceDetection};
use linux_hello_common::Result;
struct MyDetector { /* ... */ }
impl FaceDetect for MyDetector {
fn detect(&self, image_data: &[u8], width: u32, height: u32)
-> Result<Vec<FaceDetection>>
{
// Custom detection logic
Ok(vec![])
}
}
```
### Custom Embedding Extractor
Implement the `EmbeddingExtractor` trait:
```rust
use linux_hello_daemon::EmbeddingExtractor;
use linux_hello_common::Result;
use image::GrayImage;
struct MyExtractor { /* ... */ }
impl EmbeddingExtractor for MyExtractor {
fn extract(&self, face_image: &GrayImage) -> Result<Vec<f32>> {
// Custom embedding extraction
Ok(vec![])
}
}
```
### Custom TPM Storage
Implement the `TpmStorage` trait:
```rust
use linux_hello_daemon::tpm::{TpmStorage, EncryptedTemplate};
use linux_hello_common::Result;
struct MyStorage { /* ... */ }
impl TpmStorage for MyStorage {
fn is_available(&self) -> bool { true }
fn initialize(&mut self) -> Result<()> { Ok(()) }
fn encrypt(&self, user: &str, plaintext: &[u8]) -> Result<EncryptedTemplate> { /* ... */ }
fn decrypt(&self, user: &str, encrypted: &EncryptedTemplate) -> Result<Vec<u8>> { /* ... */ }
fn create_user_key(&mut self, user: &str) -> Result<()> { Ok(()) }
fn remove_user_key(&mut self, user: &str) -> Result<()> { Ok(()) }
}
```
## Configuration
Configuration is stored in `/etc/linux-hello/config.toml`:
```toml
[general]
log_level = "info"
timeout_seconds = 5
[camera]
device = "auto" # or "/dev/video0"
ir_emitter = "auto"
resolution = [640, 480]
fps = 30
[detection]
model = "blazeface"
min_face_size = 80
confidence_threshold = 0.9
[embedding]
model = "mobilefacenet"
distance_threshold = 0.6
[anti_spoofing]
enabled = true
depth_check = true
liveness_model = true
temporal_check = true
min_score = 0.7
[tpm]
enabled = true
pcr_binding = false
```
## IPC Protocol
The daemon communicates via Unix socket using JSON messages.
### Socket Location
`/run/linux-hello/auth.sock`
### Request Format
```json
{"action": "authenticate", "user": "username"}
{"action": "enroll", "user": "username", "label": "default", "frame_count": 5}
{"action": "list", "user": "username"}
{"action": "remove", "user": "username", "label": "default"}
{"action": "ping"}
```
### Response Format
```json
{
"success": true,
"message": "Authentication successful",
"confidence": 0.95,
"templates": ["default", "backup"]
}
```
## D-Bus API
The daemon exposes a D-Bus interface for desktop integration.
### Service Information
| Property | Value |
|----------|-------|
| Bus | System bus |
| Service Name | `org.linuxhello.Daemon` |
| Object Path | `/org/linuxhello/Manager` |
| Interface | `org.linuxhello.Manager` |
### Methods
```xml
<!-- Authenticate a user -->
<method name="Authenticate">
<arg name="user" type="s" direction="in"/>
<arg name="success" type="b" direction="out"/>
<arg name="confidence" type="d" direction="out"/>
<arg name="message" type="s" direction="out"/>
</method>
<!-- Start enrollment -->
<method name="EnrollStart">
<arg name="user" type="s" direction="in"/>
<arg name="label" type="s" direction="in"/>
<arg name="frame_count" type="u" direction="in"/>
<arg name="success" type="b" direction="out"/>
</method>
<!-- Cancel enrollment -->
<method name="EnrollCancel">
<arg name="success" type="b" direction="out"/>
</method>
<!-- List templates for user -->
<method name="ListTemplates">
<arg name="user" type="s" direction="in"/>
<arg name="templates" type="as" direction="out"/>
</method>
<!-- Remove a template -->
<method name="RemoveTemplate">
<arg name="user" type="s" direction="in"/>
<arg name="label" type="s" direction="in"/>
<arg name="success" type="b" direction="out"/>
</method>
<!-- Get system status -->
<method name="GetSystemStatus">
<arg name="camera_available" type="b" direction="out"/>
<arg name="tpm_available" type="b" direction="out"/>
<arg name="anti_spoofing_enabled" type="b" direction="out"/>
<arg name="enrolled_count" type="u" direction="out"/>
</method>
```
### Properties
```xml
<property name="Version" type="s" access="read"/>
<property name="CameraAvailable" type="b" access="read"/>
<property name="TpmAvailable" type="b" access="read"/>
<property name="AntiSpoofingEnabled" type="b" access="read"/>
```
### Signals
```xml
<!-- Enrollment progress -->
<signal name="EnrollmentProgress">
<arg name="frames_captured" type="u"/>
<arg name="frames_total" type="u"/>
<arg name="status" type="s"/>
</signal>
<!-- Enrollment complete -->
<signal name="EnrollmentComplete">
<arg name="success" type="b"/>
<arg name="message" type="s"/>
</signal>
```
### D-Bus Client Example (Rust with zbus)
```rust
use zbus::{Connection, proxy};
#[proxy(
interface = "org.linuxhello.Manager",
default_service = "org.linuxhello.Daemon",
default_path = "/org/linuxhello/Manager"
)]
trait LinuxHelloManager {
async fn authenticate(&self, user: &str) -> zbus::Result<(bool, f64, String)>;
async fn list_templates(&self, user: &str) -> zbus::Result<Vec<String>>;
}
async fn authenticate_user() -> zbus::Result<()> {
let connection = Connection::system().await?;
let proxy = LinuxHelloManagerProxy::new(&connection).await?;
let (success, confidence, message) = proxy.authenticate("alice").await?;
println!("Auth: {} ({}): {}", success, confidence, message);
Ok(())
}
```
## Error Handling
All operations return `Result<T, Error>` where `Error` is defined in `linux_hello_common::Error`:
```rust
use linux_hello_common::{Error, Result};
match operation() {
Ok(result) => { /* success */ }
Err(Error::NoCameraFound) => { /* no IR camera */ }
Err(Error::NoFaceDetected) => { /* face not visible */ }
Err(Error::AuthenticationFailed) => { /* no match */ }
Err(Error::UserNotEnrolled(user)) => { /* not enrolled */ }
Err(e) => { /* other error */ }
}
```
## Building Documentation
Generate HTML documentation:
```bash
cargo doc --workspace --no-deps --open
```
Documentation is generated at `target/doc/linux_hello_daemon/index.html`.
## See Also
- [README.md](../README.md) - Project overview and quick start
- [BENCHMARKS.md](BENCHMARKS.md) - Performance benchmarks
- Source code documentation: `cargo doc --open`

View File

@@ -1,289 +0,0 @@
# Linux Hello Performance Benchmarks
This document describes the performance benchmarks for the Linux Hello face authentication system. These benchmarks are used for optimization and regression testing.
## Overview
The benchmark suite measures performance of critical authentication pipeline components:
| Component | Description | Target Metric |
|-----------|-------------|---------------|
| Face Detection | Locate faces in camera frames | Frames per second |
| Embedding Extraction | Extract facial features | Embeddings per second |
| Template Matching | Compare embeddings (cosine similarity) | Comparisons per second |
| Anti-Spoofing | Liveness detection pipeline | Latency (ms) |
| Encryption/Decryption | AES-256-GCM operations | Throughput (MB/s) |
| Secure Memory | Allocation, zeroization, constant-time ops | Overhead (ns) |
## Performance Goals
For a responsive authentication experience, the total authentication time should be under 100ms. This breaks down as follows:
| Stage | Target | Notes |
|-------|--------|-------|
| Frame Capture | <33ms | 30 FPS minimum |
| Face Detection | <20ms | Per frame |
| Embedding Extraction | <30ms | Per detected face |
| Anti-Spoofing (per frame) | <15ms | Single frame analysis |
| Template Matching | <5ms | Against up to 100 templates |
| Encryption Round-trip | <10ms | For template storage/retrieval |
| **Total Pipeline** | **<100ms** | Single-frame authentication |
### Additional Targets
- **Multi-frame anti-spoofing**: <150ms for 10-frame temporal analysis
- **Secure memory operations**: <1% overhead vs non-secure operations
- **Constant-time comparisons**: Timing variance <1% between match/no-match
## Running Benchmarks
### Prerequisites
Ensure you have Rust 1.75+ installed and the project dependencies:
```bash
cd linux-hello
cargo build --release -p linux-hello-daemon
```
### Run All Benchmarks
```bash
cargo bench -p linux-hello-daemon
```
### Run Specific Benchmark Groups
```bash
# Face detection only
cargo bench -p linux-hello-daemon -- face_detection
# Template matching
cargo bench -p linux-hello-daemon -- template_matching
# Encryption
cargo bench -p linux-hello-daemon -- encryption
# Secure memory operations
cargo bench -p linux-hello-daemon -- secure_memory
# Full authentication pipeline
cargo bench -p linux-hello-daemon -- full_pipeline
```
### Generate HTML Reports
Criterion automatically generates HTML reports in `target/criterion/`. Open `target/criterion/report/index.html` in a browser to view detailed results with graphs.
```bash
# After running benchmarks
firefox target/criterion/report/index.html
```
### Compare Against Baseline
To track regressions, save a baseline and compare:
```bash
# Save current results as baseline
cargo bench -p linux-hello-daemon -- --save-baseline main
# After changes, compare against baseline
cargo bench -p linux-hello-daemon -- --baseline main
```
## Benchmark Descriptions
### Face Detection (`face_detection`)
Tests the face detection algorithms at common camera resolutions:
- QVGA (320x240)
- VGA (640x480)
- 720p (1280x720)
- 1080p (1920x1080)
**What it measures**:
- `simple_detection`: Basic placeholder algorithm
- `detector_trait`: Full FaceDetect trait implementation
### Embedding Extraction (`embedding_extraction`)
Tests embedding generation at various input sizes and output dimensions:
- Face sizes: 64x64, 112x112, 160x160, 224x224
- Embedding dimensions: 64, 128, 256, 512
**What it measures**:
- Time to extract a normalized embedding vector from a face region
### Template Matching (`template_matching`)
Tests comparison operations:
- Cosine similarity at different dimensions
- Euclidean distance calculations
- Matching against databases of 1-100 templates
**What it measures**:
- Single comparison latency
- Throughput when matching against template databases
### Anti-Spoofing (`anti_spoofing`)
Tests liveness detection components:
- Single frame IR/depth/texture analysis
- Full temporal pipeline (10 frames with movement/blink detection)
**What it measures**:
- Per-frame analysis latency
- Full pipeline latency for multi-frame analysis
### Encryption (`encryption`)
Tests AES-256-GCM encryption used for template storage:
- Encrypt/decrypt at various data sizes
- Round-trip (encrypt then decrypt)
- PBKDF2 key derivation overhead
**What it measures**:
- Throughput (bytes/second)
- Latency for template-sized data
### Secure Memory (`secure_memory`)
Tests security-critical memory operations:
- SecureEmbedding creation (with memory locking)
- Constant-time cosine similarity
- Secure byte comparison (SecureBytes)
- Memory zeroization
**What it measures**:
- Overhead vs non-secure operations
- Timing consistency (for constant-time operations)
### Full Pipeline (`full_pipeline`)
Tests complete authentication flows:
- `auth_pipeline_no_crypto`: Detection + extraction + matching
- `auth_pipeline_with_antispoofing`: Full pipeline with liveness checks
**What it measures**:
- End-to-end authentication latency
## Reference Results
Expected results on reference hardware (AMD Ryzen 7 5800X, 32GB RAM):
| Benchmark | Expected Time | Notes |
|-----------|---------------|-------|
| Face detection (VGA) | ~50 us | Placeholder algorithm |
| Embedding extraction (112x112) | ~100 us | Placeholder algorithm |
| Cosine similarity (128-dim) | ~500 ns | SIMD-optimized |
| Template matching (5 templates) | ~3 us | Linear scan |
| Anti-spoofing (single frame) | ~2 ms | VGA resolution |
| AES-GCM encrypt (512 bytes) | ~20 us | With PBKDF2 |
| Secure memory zero (1KB) | ~500 ns | Volatile writes |
| Constant-time eq (256 bytes) | ~300 ns | Using subtle crate |
| Full pipeline (no crypto) | ~200 us | Detection + match |
| Full pipeline (with anti-spoof) | ~2.5 ms | Complete auth |
**Note**: Production performance with ONNX models will differ significantly. These benchmarks use placeholder algorithms for testing infrastructure.
## Interpreting Results
### Understanding Criterion Output
```
template_matching/cosine_similarity/128
time: [487.23 ns 489.12 ns 491.34 ns]
thrpt: [2.0353 Melem/s 2.0444 Melem/s 2.0523 Melem/s]
change: [-1.2% +0.3% +1.8%] (p = 0.72 > 0.05)
No change in performance detected.
```
- **time**: [lower bound, estimate, upper bound] with 95% confidence
- **thrpt**: Throughput (operations per second)
- **change**: Comparison vs previous run (if available)
### Performance Regressions
Criterion will flag significant regressions:
- Performance degraded: >5% slower with high confidence
- Performance improved: >5% faster with high confidence
Investigate regressions before merging code changes.
## Adding New Benchmarks
When adding new functionality, include appropriate benchmarks:
```rust
fn bench_new_feature(c: &mut Criterion) {
let mut group = c.benchmark_group("new_feature");
// Set throughput for rate-based benchmarks
group.throughput(Throughput::Elements(1));
group.bench_function("operation_name", |b| {
// Setup (not measured)
let input = prepare_input();
b.iter(|| {
// This code is measured
black_box(your_function(black_box(&input)))
});
});
group.finish();
}
// Add to criterion_group!
criterion_group!(benches, ..., bench_new_feature);
```
## Continuous Integration
Benchmarks should be run in CI on performance-critical PRs:
```yaml
# Example GitHub Actions workflow
benchmark:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run benchmarks
run: cargo bench -p linux-hello-daemon -- --noplot
- name: Store results
uses: actions/upload-artifact@v4
with:
name: benchmark-results
path: target/criterion/
```
## Troubleshooting
### High Variance in Results
If benchmarks show high variance (wide confidence intervals):
1. Close other applications
2. Disable CPU frequency scaling: `sudo cpupower frequency-set -g performance`
3. Increase sample size: `group.sample_size(200);`
4. Run on an idle system
### Benchmarks Too Slow
For slow benchmarks, reduce sample size:
```rust
group.sample_size(10); // Default is 100
group.measurement_time(std::time::Duration::from_secs(5));
```
### Memory Issues
If benchmarks fail with OOM or memory errors:
1. Reduce iteration count
2. Clean up large allocations in benchmark functions
3. Check for memory leaks with valgrind
## License
These benchmarks are part of the Linux Hello project and are released under the GPL-3.0 license.

View File

@@ -1,207 +0,0 @@
#!/bin/bash
#
# Linux Hello System Installation
#
# Installs the daemon, PAM module, and GDM integration.
# Run with: sudo ./scripts/install-system.sh
#
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
# Check root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Run with sudo: sudo $0${NC}"
exit 1
fi
# Check binaries exist
if [ ! -f "$PROJECT_DIR/target/release/linux-hello-daemon" ]; then
echo -e "${RED}Build first: cargo build --release --features onnx${NC}"
exit 1
fi
if [ ! -f "$PROJECT_DIR/pam-module/pam_linux_hello.so" ]; then
echo -e "${RED}Build PAM module first: cd pam-module && make${NC}"
exit 1
fi
echo -e "${GREEN}=== Linux Hello System Installation ===${NC}"
echo
# 1. Install daemon binary
echo -e "${YELLOW}[1/7] Installing daemon binary...${NC}"
install -m 755 "$PROJECT_DIR/target/release/linux-hello-daemon" /usr/libexec/linux-hello-daemon
# 2. Install CLI binary
echo -e "${YELLOW}[2/7] Installing CLI binary...${NC}"
install -m 755 "$PROJECT_DIR/target/release/linux-hello" /usr/local/bin/linux-hello
# 3. Install ONNX models
echo -e "${YELLOW}[3/7] Installing ONNX models...${NC}"
install -d /usr/share/linux-hello/models
for model in "$PROJECT_DIR"/models/*.onnx; do
[ -f "$model" ] && install -m 644 "$model" /usr/share/linux-hello/models/
done
# 4. Install config
echo -e "${YELLOW}[4/7] Installing config...${NC}"
install -d /etc/linux-hello
if [ ! -f /etc/linux-hello/config.toml ]; then
# Use the user's tested config if available, otherwise use dist default
REAL_USER="${SUDO_USER:-$USER}"
USER_CONFIG="/home/$REAL_USER/.config/linux-hello/config.toml"
if [ -f "$USER_CONFIG" ]; then
install -m 644 "$USER_CONFIG" /etc/linux-hello/config.toml
echo " Using tested config from $USER_CONFIG"
else
install -m 644 "$PROJECT_DIR/dist/config.toml" /etc/linux-hello/config.toml
fi
else
echo " Config already exists, skipping"
fi
# 5. Install systemd service (with IR emitter integration)
echo -e "${YELLOW}[5/7] Installing systemd service...${NC}"
# Install linux-enable-ir-emitter if built
IR_EMITTER="/tmp/linux-enable-ir-emitter/target/release/linux-enable-ir-emitter"
if [ -f "$IR_EMITTER" ]; then
install -m 755 "$IR_EMITTER" /usr/local/bin/linux-enable-ir-emitter
# Copy config from the user who ran configure
REAL_USER="${SUDO_USER:-$USER}"
IR_CONFIG="/home/$REAL_USER/.config/linux-enable-ir-emitter.toml"
IR_CONFIG_ROOT="/root/.config/linux-enable-ir-emitter.toml"
if [ -f "$IR_CONFIG" ]; then
install -d /etc/linux-hello
cp "$IR_CONFIG" /etc/linux-hello/ir-emitter.toml
elif [ -f "$IR_CONFIG_ROOT" ]; then
install -d /etc/linux-hello
cp "$IR_CONFIG_ROOT" /etc/linux-hello/ir-emitter.toml
fi
fi
# Install ONNX runtime env
REAL_USER="${SUDO_USER:-$USER}"
ORT_LIB="/home/$REAL_USER/.local/lib/linux-hello/libonnxruntime.so"
if [ -f "$ORT_LIB" ]; then
install -d /usr/local/lib/linux-hello
install -m 755 "$ORT_LIB" /usr/local/lib/linux-hello/libonnxruntime.so
fi
# Create systemd service with IR emitter pre-start
cat > /etc/systemd/system/linux-hello.service << 'EOF'
[Unit]
Description=Linux Hello Face Authentication Daemon
Documentation=https://github.com/linux-hello/linux-hello
After=multi-user.target
[Service]
Type=simple
Environment=ORT_DYLIB_PATH=/usr/local/lib/linux-hello/libonnxruntime.so
ExecStartPre=-/usr/local/bin/linux-enable-ir-emitter run
ExecStart=/usr/libexec/linux-hello-daemon
Restart=on-failure
RestartSec=5
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
MemoryDenyWriteExecute=false
LockPersonality=true
# Allow access to required devices
DeviceAllow=/dev/video* rw
DeviceAllow=/dev/tpm* rw
DeviceAllow=/dev/tpmrm* rw
# Allow network for D-Bus and Unix socket
RestrictAddressFamilies=AF_UNIX
# State directory
StateDirectory=linux-hello
RuntimeDirectory=linux-hello
ConfigurationDirectory=linux-hello
# Read access to models
ReadOnlyPaths=/usr/share/linux-hello
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
# 6. Install PAM module
echo -e "${YELLOW}[6/7] Installing PAM module...${NC}"
PAM_DIR="/lib/x86_64-linux-gnu/security"
[ ! -d "$PAM_DIR" ] && PAM_DIR="/lib/security"
install -m 755 "$PROJECT_DIR/pam-module/pam_linux_hello.so" "$PAM_DIR/"
echo " Installed to $PAM_DIR/pam_linux_hello.so"
# 7. Create GDM PAM config (same pattern as gdm-fingerprint)
echo -e "${YELLOW}[7/7] Creating GDM PAM config...${NC}"
if [ ! -f /etc/pam.d/gdm-linux-hello ]; then
cat > /etc/pam.d/gdm-linux-hello << 'EOF'
#%PAM-1.0
# Linux Hello Face Authentication for GDM
# This provides face auth as an alternative to password on the login screen.
auth requisite pam_nologin.so
auth required pam_succeed_if.so user != root quiet_success
auth required pam_linux_hello.so
auth optional pam_gnome_keyring.so
@include common-account
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close
session required pam_loginuid.so
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so open
session optional pam_keyinit.so force revoke
session required pam_limits.so
session required pam_env.so readenv=1
session required pam_env.so readenv=1 user_readenv=1 envfile=/etc/default/locale
@include common-session
session optional pam_gnome_keyring.so auto_start
EOF
echo " Created /etc/pam.d/gdm-linux-hello"
else
echo " /etc/pam.d/gdm-linux-hello already exists, skipping"
fi
# Migrate templates to system path
echo
REAL_USER="${SUDO_USER:-$USER}"
TEMP_TEMPLATES="/tmp/linux-hello-templates"
SYSTEM_TEMPLATES="/var/lib/linux-hello/templates"
if [ -d "$TEMP_TEMPLATES" ] && [ "$(ls -A "$TEMP_TEMPLATES" 2>/dev/null)" ]; then
echo -e "${YELLOW}Migrating enrolled templates...${NC}"
install -d "$SYSTEM_TEMPLATES"
cp -r "$TEMP_TEMPLATES"/* "$SYSTEM_TEMPLATES/" 2>/dev/null || true
echo " Copied templates to $SYSTEM_TEMPLATES"
fi
echo
echo -e "${GREEN}=== Installation complete ===${NC}"
echo
echo "Next steps:"
echo " 1. Enable and start the daemon:"
echo " sudo systemctl enable --now linux-hello.service"
echo
echo " 2. Verify it's running:"
echo " systemctl status linux-hello.service"
echo
echo " 3. Log out and back in — GDM should show 'Linux Hello' as an auth option"
echo
echo " Your password always works as an alternative."
echo

View File

@@ -1,586 +0,0 @@
#!/bin/bash
#
# Linux Hello - Complete Setup Script
#
# This script sets up everything needed to use Linux Hello:
# 1. Downloads ONNX face recognition models
# 2. Installs ONNX Runtime (for older glibc systems)
# 3. Builds the project
# 4. Installs the PAM module
# 5. Guides through face enrollment
#
# Usage:
# ./scripts/setup.sh
#
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
MODELS_DIR="${PROJECT_DIR}/models"
print_banner() {
echo -e "${CYAN}"
echo " _ _ _ _ _ _ "
echo " | | (_)_ __ _ ___ _| | | | ___| | | ___ "
echo " | | | | '_ \| | | \ \/ / |_| |/ _ \ | |/ _ \ "
echo " | |___| | | | | |_| |> <| _ | __/ | | (_) |"
echo " |_____|_|_| |_|\__,_/_/\_\_| |_|\___|_|_|\___/ "
echo -e "${NC}"
echo -e "${BOLD}Windows Hello-style facial authentication for Linux${NC}"
echo
}
print_step() {
echo -e "\n${BLUE}==>${NC} ${BOLD}$1${NC}"
}
print_substep() {
echo -e " ${CYAN}->${NC} $1"
}
print_success() {
echo -e " ${GREEN}[OK]${NC} $1"
}
print_warning() {
echo -e " ${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e " ${RED}[ERROR]${NC} $1"
}
check_dependencies() {
print_step "Checking dependencies"
local missing=()
# Check for required tools
for cmd in cargo wget python3 make gcc; do
if command -v $cmd &> /dev/null; then
print_success "$cmd found"
else
print_error "$cmd not found"
missing+=($cmd)
fi
done
# Check for pip/python packages for model conversion
if python3 -c "import onnx" 2>/dev/null; then
print_success "python3 onnx module found"
else
print_warning "python3 onnx module not found (needed for model verification)"
echo -e " Install with: ${CYAN}pip3 install onnx${NC}"
fi
# Check for video devices
if ls /dev/video* &>/dev/null; then
local cam_count=$(ls /dev/video* 2>/dev/null | wc -l)
print_success "Found $cam_count video device(s)"
else
print_warning "No video devices found - camera required for enrollment"
fi
if [[ ${#missing[@]} -gt 0 ]]; then
print_error "Missing required dependencies: ${missing[*]}"
echo -e "\nInstall on Ubuntu/Debian:"
echo -e " ${CYAN}sudo apt install build-essential cargo wget python3${NC}"
exit 1
fi
}
get_glibc_version() {
ldd --version 2>&1 | head -1 | grep -oP '\d+\.\d+' | head -1
}
version_gte() {
local lowest
lowest=$(printf '%s\n%s' "$1" "$2" | sort -V | head -1)
[[ "$lowest" == "$2" ]]
}
setup_onnx_runtime() {
print_step "Setting up ONNX Runtime"
local glibc_version
glibc_version=$(get_glibc_version)
print_substep "Detected glibc version: $glibc_version"
if version_gte "$glibc_version" "2.38"; then
print_success "glibc >= 2.38 - bundled ONNX Runtime will work"
export ORT_STRATEGY="bundled"
elif version_gte "$glibc_version" "2.28"; then
print_warning "glibc < 2.38 - need standalone ONNX Runtime"
print_substep "Running ONNX Runtime installer..."
if [[ -f "${SCRIPT_DIR}/install-onnx-runtime.sh" ]]; then
bash "${SCRIPT_DIR}/install-onnx-runtime.sh" --user
export ORT_STRATEGY="standalone"
# Source the environment
if [[ -f "$HOME/.local/etc/linux-hello/onnx-env.sh" ]]; then
source "$HOME/.local/etc/linux-hello/onnx-env.sh"
print_success "ONNX Runtime environment configured"
fi
else
print_error "install-onnx-runtime.sh not found"
exit 1
fi
else
print_error "glibc $glibc_version is too old (minimum: 2.28)"
print_error "Please upgrade to Ubuntu 20.04 or later"
exit 1
fi
}
download_models() {
print_step "Downloading face recognition models"
mkdir -p "$MODELS_DIR"
cd "$MODELS_DIR"
# Download RetinaFace for face detection
print_substep "Downloading RetinaFace (face detection)..."
if [[ -f "retinaface.onnx" ]]; then
print_success "retinaface.onnx already exists"
else
# Try multiple sources
local retinaface_urls=(
"https://github.com/onnx/models/raw/main/validated/vision/body_analysis/ultraface/models/version-RFB-640.onnx"
"https://huggingface.co/onnx-community/retinaface/resolve/main/retinaface_mnet025_v2.onnx"
)
local downloaded=false
for url in "${retinaface_urls[@]}"; do
print_substep "Trying: $url"
if wget -q --show-progress -O retinaface.onnx "$url" 2>/dev/null; then
downloaded=true
break
fi
done
if [[ "$downloaded" == "true" ]]; then
print_success "Downloaded retinaface.onnx"
else
print_warning "Could not download RetinaFace - will try alternative"
download_ultraface
fi
fi
# Download MobileFaceNet for embeddings
print_substep "Downloading MobileFaceNet (face embeddings)..."
if [[ -f "mobilefacenet.onnx" ]]; then
print_success "mobilefacenet.onnx already exists"
else
download_mobilefacenet
fi
cd "$PROJECT_DIR"
}
download_ultraface() {
# UltraFace is a lightweight alternative that's easier to get
print_substep "Downloading UltraFace as alternative..."
local url="https://github.com/onnx/models/raw/main/validated/vision/body_analysis/ultraface/models/version-RFB-320.onnx"
if wget -q --show-progress -O retinaface.onnx "$url"; then
print_success "Downloaded UltraFace (compatible with RetinaFace interface)"
else
print_error "Failed to download face detection model"
print_error "Please manually download a RetinaFace ONNX model to models/retinaface.onnx"
exit 1
fi
}
download_mobilefacenet() {
# Try to get MobileFaceNet from various sources
local urls=(
"https://huggingface.co/onnx-community/mobilefacenet/resolve/main/mobilefacenet.onnx"
"https://github.com/onnx/models/raw/main/validated/vision/body_analysis/arcface/model/arcfaceresnet100-8.onnx"
)
for url in "${urls[@]}"; do
print_substep "Trying: $url"
if wget -q --show-progress -O mobilefacenet.onnx "$url" 2>/dev/null; then
print_success "Downloaded mobilefacenet.onnx"
return 0
fi
done
# If direct download fails, try to create from InsightFace
print_warning "Direct download failed, trying InsightFace conversion..."
create_mobilefacenet_from_insightface
}
create_mobilefacenet_from_insightface() {
print_substep "Attempting to get model from InsightFace..."
# Check if we have the required Python packages
if ! python3 -c "import numpy" 2>/dev/null; then
print_substep "Installing numpy..."
pip3 install --user numpy
fi
# Create a minimal embedding model as fallback
# This creates a simple model that extracts basic features
print_substep "Creating compatible embedding model..."
python3 << 'PYTHON_SCRIPT'
import os
import sys
try:
import numpy as np
except ImportError:
print("numpy not available, skipping model creation")
sys.exit(1)
# Try to download from alternative source
import urllib.request
urls = [
("https://drive.google.com/uc?export=download&id=1H37LER8mRRI4q_nxpS3uQz3DcGHkTrNU", "insightface model"),
]
# If we can't get a real model, we'll note it
print("Note: Could not automatically download MobileFaceNet.")
print("The system will use LBPH (Local Binary Pattern Histogram) as fallback.")
print("For best accuracy, manually download MobileFaceNet from InsightFace.")
sys.exit(0)
PYTHON_SCRIPT
if [[ ! -f "mobilefacenet.onnx" ]]; then
print_warning "MobileFaceNet not available - system will use LBPH fallback"
print_warning "LBPH provides ~85-90% accuracy vs ~99% with neural network"
print_warning ""
print_warning "For best results, manually download from:"
print_warning " https://github.com/deepinsight/insightface/tree/master/model_zoo"
# Create a marker file so the system knows to use fallback
touch "mobilefacenet.onnx.missing"
fi
}
verify_models() {
print_step "Verifying models"
cd "$MODELS_DIR"
if [[ -f "retinaface.onnx" ]]; then
local size=$(stat -f%z "retinaface.onnx" 2>/dev/null || stat -c%s "retinaface.onnx" 2>/dev/null)
if [[ $size -gt 100000 ]]; then
print_success "retinaface.onnx ($(numfmt --to=iec $size 2>/dev/null || echo "${size} bytes"))"
else
print_error "retinaface.onnx seems too small (corrupted?)"
fi
else
print_error "retinaface.onnx not found"
fi
if [[ -f "mobilefacenet.onnx" ]]; then
local size=$(stat -f%z "mobilefacenet.onnx" 2>/dev/null || stat -c%s "mobilefacenet.onnx" 2>/dev/null)
if [[ $size -gt 100000 ]]; then
print_success "mobilefacenet.onnx ($(numfmt --to=iec $size 2>/dev/null || echo "${size} bytes"))"
else
print_warning "mobilefacenet.onnx seems small - may be placeholder"
fi
elif [[ -f "mobilefacenet.onnx.missing" ]]; then
print_warning "mobilefacenet.onnx not available - will use LBPH fallback"
else
print_warning "mobilefacenet.onnx not found - will use LBPH fallback"
fi
cd "$PROJECT_DIR"
}
build_project() {
print_step "Building Linux Hello"
cd "$PROJECT_DIR"
# Determine features based on what's available
local features="tpm"
if [[ -f "${MODELS_DIR}/retinaface.onnx" ]]; then
features="onnx,tpm"
print_substep "Building with ONNX support"
else
print_substep "Building without ONNX (no models found)"
fi
print_substep "Running: cargo build --release --features \"$features\""
if cargo build --release --features "$features"; then
print_success "Build successful"
else
print_error "Build failed"
exit 1
fi
# Build PAM module
print_substep "Building PAM module..."
if [[ -d "${PROJECT_DIR}/pam-module" ]]; then
cd "${PROJECT_DIR}/pam-module"
if make clean && make; then
print_success "PAM module built"
else
print_warning "PAM module build failed (optional)"
fi
cd "$PROJECT_DIR"
fi
}
detect_camera() {
print_step "Detecting cameras"
# Try to find IR camera
local ir_camera=""
local any_camera=""
for dev in /dev/video*; do
[[ -e "$dev" ]] || continue
local name=""
if command -v v4l2-ctl &>/dev/null; then
name=$(v4l2-ctl -d "$dev" --info 2>/dev/null | grep "Card type" | cut -d: -f2 | xargs)
fi
if [[ -z "$name" ]]; then
name=$(cat /sys/class/video4linux/$(basename $dev)/name 2>/dev/null || echo "Unknown")
fi
# Check if it looks like an IR camera
if [[ "$name" =~ [Ii][Rr] ]] || [[ "$name" =~ [Ii]nfra ]] || [[ "$name" =~ [Hh]ello ]]; then
ir_camera="$dev"
print_success "Found IR camera: $dev ($name)"
else
any_camera="$dev"
print_substep "Found camera: $dev ($name)"
fi
done
if [[ -n "$ir_camera" ]]; then
export LINUX_HELLO_CAMERA="$ir_camera"
print_success "Using IR camera: $ir_camera"
elif [[ -n "$any_camera" ]]; then
export LINUX_HELLO_CAMERA="$any_camera"
print_warning "No IR camera found - using: $any_camera"
print_warning "Note: RGB camera provides less security than IR camera"
else
print_error "No camera found"
print_error "Please connect a camera and try again"
exit 1
fi
}
test_installation() {
print_step "Testing installation"
cd "$PROJECT_DIR"
# Source ONNX environment if needed
if [[ -f "$HOME/.local/etc/linux-hello/onnx-env.sh" ]]; then
source "$HOME/.local/etc/linux-hello/onnx-env.sh"
fi
print_substep "Running: linux-hello status"
if ./target/release/linux-hello status; then
print_success "CLI works"
else
print_warning "CLI returned non-zero (may be normal if daemon not running)"
fi
}
setup_environment() {
print_step "Setting up environment"
# Create shell profile addition
local profile_script="$HOME/.linux-hello-env"
cat > "$profile_script" << 'EOF'
# Linux Hello environment
if [[ -f "$HOME/.local/etc/linux-hello/onnx-env.sh" ]]; then
source "$HOME/.local/etc/linux-hello/onnx-env.sh"
fi
# Add to PATH if needed
if [[ -d "$HOME/.local/bin" ]] && [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
export PATH="$HOME/.local/bin:$PATH"
fi
EOF
print_success "Created $profile_script"
# Add to shell profile if not already there
local shell_profile=""
if [[ -f "$HOME/.bashrc" ]]; then
shell_profile="$HOME/.bashrc"
elif [[ -f "$HOME/.zshrc" ]]; then
shell_profile="$HOME/.zshrc"
fi
if [[ -n "$shell_profile" ]]; then
if ! grep -q "linux-hello-env" "$shell_profile" 2>/dev/null; then
echo "" >> "$shell_profile"
echo "# Linux Hello" >> "$shell_profile"
echo "source \"$profile_script\"" >> "$shell_profile"
print_success "Added to $shell_profile"
else
print_success "Already in $shell_profile"
fi
fi
}
prompt_enrollment() {
print_step "Face enrollment"
echo
echo -e "${BOLD}Linux Hello is ready for face enrollment!${NC}"
echo
echo "To enroll your face, run:"
echo -e " ${CYAN}./target/release/linux-hello enroll --user $USER${NC}"
echo
echo "Or with the installed version:"
echo -e " ${CYAN}linux-hello enroll --user $USER${NC}"
echo
read -p "Would you like to enroll your face now? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
enroll_face
else
echo
echo "You can enroll later with:"
echo -e " ${CYAN}./target/release/linux-hello enroll --user $USER${NC}"
fi
}
enroll_face() {
print_step "Enrolling face for user: $USER"
cd "$PROJECT_DIR"
# Source environment
if [[ -f "$HOME/.local/etc/linux-hello/onnx-env.sh" ]]; then
source "$HOME/.local/etc/linux-hello/onnx-env.sh"
fi
echo
echo -e "${YELLOW}Please look at the camera...${NC}"
echo "The system will capture multiple frames of your face."
echo
if ./target/release/linux-hello enroll --user "$USER" --frames 5; then
print_success "Face enrolled successfully!"
echo
echo -e "${GREEN}You can now use facial authentication!${NC}"
else
print_error "Enrollment failed"
echo
echo "Troubleshooting:"
echo " 1. Make sure your face is well-lit"
echo " 2. Look directly at the camera"
echo " 3. Try running with --verbose for more info"
fi
}
install_pam() {
print_step "Installing PAM module (requires sudo)"
if [[ $EUID -ne 0 ]]; then
echo
echo "To enable facial authentication for system login,"
echo "the PAM module needs to be installed with sudo."
echo
read -p "Install PAM module now? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
cd "${PROJECT_DIR}/pam-module"
if sudo make install; then
print_success "PAM module installed"
show_pam_config
else
print_error "PAM module installation failed"
fi
cd "$PROJECT_DIR"
fi
fi
}
show_pam_config() {
echo
echo -e "${BOLD}PAM Configuration${NC}"
echo
echo "To enable Linux Hello for login, add to /etc/pam.d/common-auth:"
echo
echo -e "${CYAN}# Linux Hello facial authentication"
echo -e "auth sufficient pam_linux_hello.so timeout=10"
echo -e "auth required pam_unix.so nullok_secure # fallback${NC}"
echo
echo -e "${YELLOW}WARNING: Incorrect PAM configuration can lock you out!${NC}"
echo "Always keep a root terminal open when testing PAM changes."
}
print_summary() {
echo
echo -e "${GREEN}============================================${NC}"
echo -e "${GREEN} Setup Complete!${NC}"
echo -e "${GREEN}============================================${NC}"
echo
echo -e "${BOLD}What's installed:${NC}"
echo " - Linux Hello CLI and daemon"
echo " - Face detection models"
if [[ -f "${MODELS_DIR}/mobilefacenet.onnx" ]]; then
echo " - Face embedding models (neural network)"
else
echo " - Face embedding (LBPH fallback)"
fi
if [[ "$ORT_STRATEGY" == "standalone" ]]; then
echo " - ONNX Runtime (standalone for your glibc)"
fi
echo
echo -e "${BOLD}Quick commands:${NC}"
echo " Enroll face: ./target/release/linux-hello enroll --user \$USER"
echo " Test auth: ./target/release/linux-hello test --user \$USER"
echo " List users: ./target/release/linux-hello list"
echo " Show status: ./target/release/linux-hello status"
echo
if [[ -f "$HOME/.local/etc/linux-hello/onnx-env.sh" ]]; then
echo -e "${BOLD}Note:${NC} Run this in new terminals or restart your shell:"
echo " source ~/.linux-hello-env"
echo
fi
}
main() {
print_banner
cd "$PROJECT_DIR"
check_dependencies
setup_onnx_runtime
download_models
verify_models
build_project
detect_camera
test_installation
setup_environment
print_summary
prompt_enrollment
install_pam
echo
echo -e "${GREEN}Linux Hello is ready to use!${NC}"
echo
}
main "$@"

View File

@@ -1,165 +0,0 @@
# Phase 1 Test Summary
## Overview
This document summarizes the comprehensive test suite created for Phase 1 of the Linux Hello project.
## Test Coverage
### Unit Tests
#### Camera Module (`linux-hello-daemon/src/camera/`)
-`test_camera_info_display` - Tests CameraInfo Display implementation
-`test_pixel_format_equality` - Tests PixelFormat equality
-`test_frame_structure` - Tests Frame structure creation
-`test_mock_camera_enumeration` - Tests mock camera enumeration (non-Linux)
-`test_mock_camera_capture` - Tests mock camera frame capture
#### IR Emitter Module (`linux-hello-daemon/src/camera/ir_emitter.rs`)
-`test_ir_emitter_creation` - Tests IrEmitterControl creation
-`test_ir_emitter_enable_disable` - Tests enable/disable functionality
-`test_scan_emitter_controls` - Tests control scanning
#### Detection Module (`linux-hello-daemon/src/detection/`)
-`test_face_detection_pixels` - Tests pixel coordinate conversion
-`test_simple_detection` - Tests simple face detection algorithm
-`test_simple_detector_trait` - Tests FaceDetect trait implementation
#### Common Module (`linux-hello-common/`)
-`test_default_config` - Tests default configuration
-`test_config_serialization` - Tests config serialization/deserialization
-`test_error_display` - Tests error message formatting
**Total Unit Tests: 12 tests, all passing**
### Integration Tests
#### Camera Integration Tests (`tests/camera_test.rs`)
-`test_camera_enumeration` - Tests V4L2 camera enumeration
-`test_camera_open_and_capture` - Tests camera opening and frame capture
-`test_ir_emitter_control` - Tests IR emitter enable/disable
-`test_camera_info_properties` - Tests camera info validation
**Note**: These tests may be skipped if no camera hardware is available.
#### Face Detection Integration Tests (`tests/detection_test.rs`)
-`test_simple_face_detection` - Tests face detection with gradient image
-`test_face_detection_empty_image` - Tests edge case (empty image)
-`test_face_detection_low_contrast` - Tests low contrast image
-`test_face_detection_high_contrast` - Tests high contrast image
-`test_simple_face_detector_trait` - Tests detector trait with different thresholds
-`test_face_detection_pixel_conversion` - Tests pixel coordinate conversion
**Total Integration Tests: 10 tests, all passing**
#### CLI Integration Tests (`tests/cli_test.rs`)
-`test_cli_status_command` - Tests `linux-hello status` command
-`test_cli_config_command` - Tests `linux-hello config` command
-`test_cli_config_json_command` - Tests `linux-hello config --json` command
-`test_cli_capture_command` - Tests `linux-hello capture` command
-`test_cli_detect_command` - Tests `linux-hello detect` command
**Total CLI Tests: 5 tests**
## Test Infrastructure
### Test Package
- Created `linux-hello-tests` package in workspace for integration tests
- Tests are organized in `tests/` directory at project root
- All tests can be run with: `cargo test --package linux-hello-tests`
### Test Runner Script
- Created `tests/phase1_test.sh` - Comprehensive test runner
- Checks all Phase 1 deliverables
- Provides colored output and summary
- Handles missing hardware gracefully
## Phase 1 Deliverables Status
### ✅ Project Scaffolding
- [x] Rust workspace structure
- [x] C PAM module skeleton
- [x] All Cargo.toml files configured
- [x] Build system working
### ✅ V4L2 Camera Enumeration and Capture
- [x] Camera enumeration via V4L2
- [x] Frame capture implementation
- [x] Multiple pixel format support (GREY, YUYV, MJPEG)
- [x] Resolution detection
- [x] IR camera detection heuristics
- [x] Tests for all camera functionality
### ✅ IR Emitter Control
- [x] IR emitter control structure
- [x] v4l2-ctl integration
- [x] Enable/disable functionality
- [x] Control scanning
- [x] Tests for IR emitter
### ✅ Basic Face Detection
- [x] Simple face detection algorithm (placeholder)
- [x] FaceDetect trait for extensibility
- [x] FaceDetection structure with pixel conversion
- [x] Tests for detection pipeline
### ✅ Frame Capture CLI Tool
- [x] `linux-hello capture` command
- [x] Frame saving to files
- [x] Multiple frame capture support
- [x] Camera auto-detection
- [x] Tests for CLI commands
## Running Tests
### All Tests
```bash
cargo test
```
### Unit Tests Only
```bash
cargo test --lib
```
### Integration Tests
```bash
cargo test --package linux-hello-tests
```
### Specific Test Suite
```bash
cargo test --package linux-hello-tests --test camera_test
cargo test --package linux-hello-tests --test detection_test
cargo test --package linux-hello-tests --test cli_test
```
### Phase 1 Test Script
```bash
bash tests/phase1_test.sh
```
## Known Limitations
1. **ONNX Models**: ML models are not yet integrated (waiting for ort 2.0 stable)
2. **Hardware Requirements**: Some tests require actual camera hardware
3. **IR Emitter**: IR emitter control is hardware-specific and may not work on all devices
4. **Face Detection**: Currently using simple placeholder algorithm, not ML-based
## Next Steps (Phase 2)
1. Integrate ONNX Runtime for face detection models
2. Implement face embedding extraction
3. Add template matching and storage
4. Implement PAM-daemon communication
5. Add enrollment flow
6. Add authentication flow
## Test Results Summary
- **Unit Tests**: 12/12 passing ✅
- **Integration Tests**: 10/10 passing ✅
- **CLI Tests**: 5/5 passing ✅
- **Total**: 27 tests, all passing ✅
**Phase 1 Milestone**: ✅ **COMPLETE** - Capture IR frames and detect faces in them

View File

@@ -1,160 +0,0 @@
# Phase 2 Test Summary
## Overview
This document summarizes the test suite for Phase 2 (Core Authentication) of the Linux Hello project.
## Test Coverage
### Unit Tests (Daemon - 9 tests)
#### Embedding Module (`linux-hello-daemon/src/embedding.rs`)
-`test_placeholder_extractor` - Tests embedding extraction with placeholder algorithm
-`test_cosine_similarity` - Tests cosine similarity calculation
-`test_euclidean_distance` - Tests Euclidean distance calculation
#### Matching Module (`linux-hello-daemon/src/matching.rs`)
-`test_match_template` - Tests template matching with threshold
-`test_average_embeddings` - Tests embedding averaging for enrollment
#### IR Emitter Module (`linux-hello-daemon/src/camera/ir_emitter.rs`)
-`test_ir_emitter_creation` - Tests IrEmitterControl creation
-`test_ir_emitter_enable_disable` - Tests enable/disable functionality
-`test_scan_emitter_controls` - Tests control scanning
### Unit Tests (Common - 4 tests)
#### Config Module (`linux-hello-common/src/config.rs`)
-`test_default_config` - Tests default configuration values
-`test_config_serialization` - Tests TOML serialization/deserialization
#### Template Module (`linux-hello-common/src/template.rs`)
-`test_template_store` - Tests template storage operations
#### Error Module (`linux-hello-common/src/error.rs`)
-`test_error_display` - Tests error message formatting
### Integration Tests
#### Phase 2 Auth Tests (`tests/integration/phase2_auth_test.rs`) - 12 tests
-`test_template_store_operations` - Template storage CRUD operations
-`test_multiple_templates_per_user` - Multiple template enrollment
-`test_embedding_extraction` - Embedding extractor with test images
-`test_embedding_consistency` - Same image produces same embedding
-`test_cosine_similarity` - Cosine similarity calculations
-`test_template_matching` - Template matching against stored templates
-`test_embedding_averaging` - Multi-frame embedding averaging
-`test_empty_embeddings_error` - Error handling for empty embeddings
-`test_auth_service_init` - Authentication service initialization
-`test_match_result_structure` - MatchResult structure validation
-`test_embedding_diversity` - Different images produce different embeddings
-`test_template_serialization` - JSON serialization roundtrip
#### IPC Tests (`tests/integration/ipc_test.rs`) - 9 tests
-`test_authenticate_request_serialization` - Auth request JSON format
-`test_enroll_request_serialization` - Enroll request JSON format
-`test_list_request_serialization` - List request JSON format
-`test_remove_request_serialization` - Remove request JSON format
-`test_ping_request_serialization` - Ping request JSON format
-`test_response_serialization` - Response JSON format with all fields
-`test_error_response_serialization` - Error response handling
-`test_default_socket_path` - Socket path constant
-`test_pam_protocol_compatibility` - PAM module JSON compatibility
#### Camera Tests (`tests/camera_test.rs`) - 4 tests
-`test_camera_enumeration` - V4L2 camera enumeration
-`test_camera_open_and_capture` - Camera frame capture
-`test_ir_emitter_control` - IR emitter control
-`test_camera_info_properties` - Camera info validation
#### Detection Tests (`tests/detection_test.rs`) - 6 tests
-`test_simple_face_detection` - Face detection with gradient image
-`test_face_detection_empty_image` - Edge case (empty image)
-`test_face_detection_low_contrast` - Low contrast image
-`test_face_detection_high_contrast` - High contrast image
-`test_simple_face_detector_trait` - Detector trait with thresholds
-`test_face_detection_pixel_conversion` - Pixel coordinate conversion
#### CLI Tests (`tests/cli_test.rs`) - 5 tests
-`test_cli_status_command` - Status command execution
-`test_cli_config_command` - Config TOML output
-`test_cli_config_json_command` - Config JSON output
-`test_cli_capture_command` - Capture command (requires camera)
-`test_cli_detect_command` - Detect command with test image
## Test Summary
| Category | Tests | Status |
|----------|-------|--------|
| Unit Tests (Daemon) | 9 | ✅ All Pass |
| Unit Tests (Common) | 4 | ✅ All Pass |
| Phase 2 Auth Tests | 12 | ✅ All Pass |
| IPC Tests | 9 | ✅ All Pass |
| Camera Tests | 4 | ✅ All Pass |
| Detection Tests | 6 | ✅ All Pass |
| CLI Tests | 5 | ✅ All Pass |
| **Total** | **49** | ✅ **All Pass** |
## Phase 2 Features Tested
### ✅ Face Embedding
- Placeholder embedding extractor (128-dimensional vectors)
- Image statistics-based feature extraction
- Embedding normalization
- Consistent embeddings for identical images
- Different patterns produce distinguishable embeddings
### ✅ Template Matching
- Cosine similarity calculation
- Euclidean distance calculation
- Threshold-based matching
- Best match selection from multiple templates
- Distance-to-similarity conversion
### ✅ Template Storage
- JSON-based template storage
- Per-user directory structure
- Create, read, update, delete operations
- Multiple templates per user
- User enrollment status checking
- Template listing and enumeration
### ✅ IPC Protocol
- JSON message serialization/deserialization
- Authentication requests
- Enrollment requests
- List and remove operations
- PAM module compatibility
- Response format with confidence scores
### ✅ Authentication Service
- Service initialization
- Template store integration
- Camera capture (when available)
- Face detection and extraction
- Embedding extraction and matching
## Running Tests
```bash
# Run all tests
cargo test --workspace
# Run only Phase 2 tests
cargo test --package linux-hello-tests --test phase2_auth_test
cargo test --package linux-hello-tests --test ipc_test
# Run with verbose output
cargo test --workspace -- --nocapture
```
## Notes
1. **Hardware Requirements**: Camera tests may be skipped if no camera is available
2. **Placeholder Implementation**: Face detection and embedding use placeholder algorithms; ONNX integration planned for Phase 3
3. **Permissions**: Auth service init test may report errors on systems where /var/lib is not writable
4. **PAM Integration**: IPC protocol tests verify compatibility with the C PAM module
---
*Last Updated: January 2026*