Skip to content

[PM-26340] Add linux biometrics v2 - #16660

Merged
quexten merged 32 commits into
mainfrom
km/linux-biometrics-v2
Oct 29, 2025
Merged

quexten merged 32 commits into
mainfrom
km/linux-biometrics-v2

Conversation

@quexten

@quexten quexten commented Sep 30, 2025 •

Copy link
Copy Markdown
Contributor

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-26340

📔 Objective

This PR implements biometrics v2 for Linux:

this PR does not yet make use of the implemented module. That is added in a follow-up PR.

The user key is now held in the encrypted memory store (introduced in #16659) after first unlock. The key of the memory store is protected from memory dumping via either of:

  • memfd_secret
  • keyctl
  • PR_SET_DUMPABLE=0 (all systems except snap)
  • System settings: kernel.yama.ptrace_scope (default on at least ubuntu, soon expanding)

only if all of the above methods are unavailable is the memory store key dumpable by other userspace processes (which in turn would make the userkey decryptable).

📸 Screenshots

⏰ Reminders before review

  • Contributor guidelines followed
  • All formatters and local linters executed and passed
  • Written new unit and / or integration tests where applicable
  • Protected functional changes with optionality (feature flags)
  • Used internationalization (i18n) for all UI strings
  • CI builds passed
  • Communicated to DevOps any deployment requirements
  • Updated any necessary documentation (Confluence, contributing docs) or informed the documentation team

🦮 Reviewer guidelines

  • 👍 (:+1:) or similar for great changes
  • 📝 (:memo:) or ℹ️ (:information_source:) for notes or general info
  • ❓ (:question:) for questions
  • 🤔 (:thinking:) or 💭 (:thought_balloon:) for more open inquiry that's not quite a confirmed issue and could potentially benefit from discussion
  • 🎨 (:art:) for suggestions / improvements
  • ❌ (:x:) or ⚠️ (:warning:) for more significant problems or concerns needing attention
  • 🌱 (:seedling:) or ♻️ (:recycle:) for future improvements or indications of technical debt
  • ⛏ (:pick:) for minor or nitpick changes

@sonarqubecloud

Copy link
Copy Markdown

@codecov

codecov Bot commented Sep 30, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 40.17%. Comparing base (2ff9c23) to head (ae0f881).
⚠️ Report is 24 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16660   +/-   ##
=======================================
  Coverage   40.17%   40.17%           
=======================================
  Files        3486     3486           
  Lines       99633    99634    +1     
  Branches    14911    14911           
=======================================
+ Hits        40031    40032    +1     
- Misses      57909    57910    +1     
+ Partials     1693     1692    -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@quexten quexten changed the title Add linux biometrics v2 [PM-26340] Add linux biometrics v2 Sep 30, 2025
@github-actions

github-actions Bot commented Sep 30, 2025 •

Copy link
Copy Markdown
Contributor

Logo
Checkmarx One – Scan Summary & Details – af3440f8-7897-4242-a95d-4f850f556531

Great job! No new security vulnerabilities introduced in this pull request

Base automatically changed from km/encrypted_memory_store to main October 23, 2025 12:04
@quexten
quexten marked this pull request as ready for review October 27, 2025 17:52
@quexten
quexten requested a review from a team as a code owner October 27, 2025 17:52
@quexten
quexten requested a review from mzieniukbw October 27, 2025 17:52
@claude

claude Bot commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

Claude finished @quexten's task —— View job


PR Review: Linux Biometrics V2

Reviewing the implementation of Linux biometrics v2 with memory protection mechanisms.

Todo List

  • Read and analyze changed files
  • Review memory protection implementation
  • Check security implications
  • Verify error handling and resource management
  • Post comprehensive review

Summary of Changes

This PR adds the Linux implementation for biometrics v2, replacing the previous unimplemented.rs stub with a full Polkit-based authentication system. The implementation:

  1. New file: linux.rs (141 lines) - Implements BiometricTrait using Polkit for authentication
  2. Modified: biometric_v2/mod.rs - Changes path from unimplemented.rs to linux.rs for Linux
  3. Modified: secure_memory/mod.rs - Changes encrypted_memory_store from private to pub(crate)

The system stores user keys in an EncryptedMemoryStore protected by memfd_secret/keyctl/mlock, and requires Polkit authentication to retrieve them.


Critical Issues

1. Race Condition in unlock() - Line 65-74

Severity: High

The unlock() method performs authentication and then retrieves the key in two separate lock acquisitions:

async fn unlock(&self, user_id: &str, _hwnd: Vec<u8>) -> Result<Vec<u8>> {
    if !polkit_authenticate_bitwarden_policy().await? {
        return Err(anyhow!("Authentication failed"));
    }

    self.secure_memory
        .lock()
        .await
        .get(user_id)
        .ok_or(anyhow!("No key found"))
}

Problem: Between authentication and key retrieval, another thread could call unenroll() and remove the key. This creates a TOCTOU (Time-of-Check-Time-of-Use) vulnerability.

Recommendation: Hold the lock across both operations:

async fn unlock(&self, user_id: &str, _hwnd: Vec<u8>) -> Result<Vec<u8>> {
    if !polkit_authenticate_bitwarden_policy().await? {
        return Err(anyhow!("Authentication failed"));
    }
    
    let mut store = self.secure_memory.lock().await;
    store.get(user_id).ok_or(anyhow!("No key found"))
}

2. Sensitive Data Exposure in Error Messages - Line 113

Severity: Medium

warn!("[Polkit] Error performing authentication: {:?}", e);

Problem: The debug format of the error could potentially leak sensitive information about the system state, authentication mechanisms, or user context.

Recommendation: Log only sanitized error information:

warn!("[Polkit] Error performing authentication: {}", e);

Or better, log just the error type without details in production builds.

3. Inconsistent Error Handling in Polkit Functions

Severity: Medium

  • polkit_authenticate_bitwarden_policy() returns Ok(false) on error (line 114)
  • polkit_is_bitwarden_policy_available() propagates errors via ?

Problem: Inconsistent error handling makes it harder to distinguish between "user denied" and "system error" scenarios. When Polkit fails with an error in authenticate(), the caller sees Ok(false) as if the user simply denied authentication.

Recommendation: Either propagate errors consistently or document why authentication errors should be treated as denial. Consider:

match authorization_result {
    Ok(result) => Ok(result.is_authorized),
    Err(e) => {
        warn!("[Polkit] Error performing authentication: {}", e);
        Err(e.into())  // or return a specific error type
    }
}

Security Analysis

Memory Protection Architecture

The implementation correctly leverages the existing EncryptedMemoryStore infrastructure which provides layered protection:

  • Level 1: memfd_secret (Linux 6.5+) - kernel-enforced inaccessibility
  • Level 2: keyctl (Linux 2.6+) - kernel keyring storage
  • Level 3: mlock with PR_SET_DUMPABLE - prevents swapping/dumping
  • Level 4: Encryption - All stored keys are encrypted with ChaCha20Poly1305

Authentication Flow

Polkit integration is appropriate for Linux desktop environments:

  • Uses process-based subject identification
  • Allows user interaction for authentication
  • Checks against com.bitwarden.Bitwarden.unlock policy

Potential Security Concerns

  1. No Replay Protection: The authentication is purely synchronous - there's no mechanism to prevent rapid repeated unlock attempts after a single successful authentication.

  2. Key Lifecycle: Keys are held in memory even when the vault is locked. This is by design (per PR description) but means:

    • An attacker who gains code execution in the process can potentially extract keys
    • The protection relies entirely on the platform-specific memory protection mechanisms
    • As documented, only if ALL protection mechanisms fail is the key dumpable
  3. No Rate Limiting: The code doesn't implement rate limiting for failed authentication attempts. This should ideally be handled by Polkit itself, but verification would be prudent.


Suggested Improvements

1. Make BiometricLockSystem Non-Clonable

Since it holds sensitive state, ensure it can't be accidentally cloned:

pub struct BiometricLockSystem {
    secure_memory: Arc<Mutex<crate::secure_memory::encrypted_memory_store::EncryptedMemoryStore>>,
}
// Add this to prevent accidental cloning
#[cfg(not(test))]
impl !Clone for BiometricLockSystem {}

2. Add Timeout to Polkit Operations

Network/system bus operations can hang. Consider adding timeouts:

use tokio::time::{timeout, Duration};

async fn polkit_authenticate_bitwarden_policy() -> Result<bool> {
    debug!("[Polkit] Authenticating / performing UV");
    
    let auth_future = async {
        let connection = Connection::system().await?;
        let proxy = AuthorityProxy::new(&connection).await?;
        // ... rest of auth logic
    };
    
    match timeout(Duration::from_secs(30), auth_future).await {
        Ok(result) => result,
        Err(_) => {
            warn!("[Polkit] Authentication timed out");
            Err(anyhow!("Authentication timeout"))
        }
    }
}

3. Enhance Error Context

Use anyhow::Context for better error messages:

use anyhow::Context;

async fn unlock(&self, user_id: &str, _hwnd: Vec<u8>) -> Result<Vec<u8>> {
    if !polkit_authenticate_bitwarden_policy()
        .await
        .context("Polkit authentication failed")? 
    {
        return Err(anyhow!("Authentication failed"));
    }

    self.secure_memory
        .lock()
        .await
        .get(user_id)
        .ok_or_else(|| anyhow!("No key found for user"))
}

4. Consider Audit Logging

For security-critical operations like unlock attempts, consider adding audit logging:

async fn unlock(&self, user_id: &str, _hwnd: Vec<u8>) -> Result<Vec<u8>> {
    info!("Unlock attempt for user_id (redacted)");
    
    let authenticated = polkit_authenticate_bitwarden_policy().await?;
    if !authenticated {
        warn!("Unlock denied by Polkit for user");
        return Err(anyhow!("Authentication failed"));
    }
    
    // ... rest of unlock logic
}

5. Improve Test Coverage

The single test is ignored. Consider adding:

  • Unit tests for key storage/retrieval
  • Tests for concurrent access patterns
  • Mock tests for Polkit authentication flows
Example Test Structure
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_provide_and_retrieve_key() {
        let system = BiometricLockSystem::new();
        let user_id = "test_user";
        let key = b"test_key_data";
        
        system.provide_key(user_id, key).await;
        assert!(system.unlock_available(user_id).await.unwrap());
    }

    #[tokio::test]
    async fn test_unenroll_removes_key() {
        let system = BiometricLockSystem::new();
        let user_id = "test_user";
        let key = b"test_key_data";
        
        system.provide_key(user_id, key).await;
        system.unenroll(user_id).await.unwrap();
        assert!(!system.unlock_available(user_id).await.unwrap());
    }

    #[tokio::test]
    async fn test_concurrent_access() {
        let system = Arc::new(BiometricLockSystem::new());
        // Test concurrent provide_key and unlock_available calls
    }
}

6. Documentation Improvements

Security comment (line 4-11): Has grammatical issues:

//! # Security
//! This section describes the assumed security model and security guarantees achieved. In the required security
//! guarantee is that a locked vault - a running app - cannot be unlocked when the device (user-space)
//! is compromised in this state.

Should be:

//! # Security
//! This section describes the assumed security model and security guarantees.
//! 
//! The primary security guarantee is that a locked vault in a running app cannot be 
//! unlocked when the device (user-space) is compromised while in this locked state.

Line 9: "memfd_secret. This makes it inaccessible to other processes, even if they compromise root, a kernel compromise has circumventable best-effort protections."

This sentence is confusing. Suggest:

//! protected by memfd_secret. This makes it inaccessible to other processes, even to 
//! root. Kernel compromises can circumvent these protections, but best-effort 
//! protections are in place.

Good Practices Observed

  • Clean separation of concerns with trait implementation
  • Async/await properly used throughout
  • Arc<Mutex<>> for thread-safe shared state
  • Default implementation provided
  • Uses existing battle-tested EncryptedMemoryStore infrastructure
  • Proper use of tracing for debug/warn logging
  • Integration with system authentication (Polkit) rather than rolling custom auth

Action Items for Author

Must Fix:

  1. ⚠️ Address race condition in unlock() method (Issue i18n #1)
  2. ⚠️ Review and unify error handling in Polkit functions (Issue Overlay Popup #3)

Should Fix:
3. 📝 Sanitize error logging to avoid potential information leakage (Issue #2)
4. 📝 Fix grammar and clarity in security documentation comments
5. 📝 Add non-test unit tests or remove the #[ignore] attribute with explanation

Consider:
6. 🤔 Add timeout handling for Polkit operations
7. 🤔 Implement audit logging for security-critical operations
8. 🤔 Add rate limiting or document reliance on Polkit's rate limiting
9. 🎨 Enhance error messages with context using anyhow::Context


Alignment with Project Guidelines

✅ CRITICAL rules followed:

  • No new encryption logic added (uses existing infrastructure)
  • No unencrypted vault data sent to APIs
  • No secrets committed
  • No logging of decrypted data or keys (though error logging could be more careful)

✅ Architecture:

  • Respects monorepo boundaries (all changes in apps/desktop)
  • Follows async patterns with proper Observable/Future usage
  • Clean trait implementation pattern

@quexten

quexten commented Oct 29, 2025

Copy link
Copy Markdown
Contributor Author

Merging since this does not yet use the code actively. Next PR will make use of it and get QA'd.

@quexten
quexten merged commit b1738cc into main Oct 29, 2025
@quexten
quexten deleted the km/linux-biometrics-v2 branch October 29, 2025 14:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants