passless-core 0.11.1

Core types and configuration for Passless
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Application configuration using clap-serde-derive
//!
//! This module provides a unified configuration approach where settings can come from:
//! 1. CLI arguments (highest priority)
//! 2. Configuration file (medium priority)
//! 3. Default values (lowest priority)

use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;

use clap::{ArgAction, Parser, Subcommand};
use clap_serde_derive::ClapSerde;
use libc::{PR_SET_DUMPABLE, prctl};
use libc::{mlock, munlock};
use log::debug;
use nix::sys::resource::{Resource, setrlimit};
use passless_config_doc::ConfigDoc;
use serde::{Deserialize, Serialize};

/// Compute default local storage path
pub fn local_path() -> String {
    dirs::data_dir()
        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
        .join("passless/local")
        .to_string_lossy()
        .into_owned()
}

/// Local backend configuration
#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
#[group(id = "local-backend-config")]
pub struct LocalBackendConfig {
    /// Path to local storage directory
    #[arg(
        long = "local-path",
        env = "PASSLESS_LOCAL_PATH",
        id = "local-path",
        value_name = "PATH"
    )]
    #[serde(default)]
    #[default(local_path())]
    pub path: String,
}

/// Compute default password-store path
pub fn pass_store_path() -> String {
    dirs::home_dir()
        .expect("Could not determine home directory: $HOME")
        .join(".password-store")
        .to_string_lossy()
        .into_owned()
}
/// Pass (password-store) backend configuration
#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
#[group(id = "pass-backend-config")]
pub struct PassBackendConfig {
    /// Path to password store directory
    #[arg(
        long = "pass-store-path",
        env = "PASSLESS_PASS_STORE_PATH",
        id = "pass-store-path",
        value_name = "PATH"
    )]
    #[serde(default)]
    #[default(pass_store_path())]
    pub store_path: String,

    /// Relative path within password store for FIDO2 entries
    #[arg(
        long = "pass-path",
        env = "PASSLESS_PASS_PATH",
        id = "pass-path",
        value_name = "PATH"
    )]
    #[serde(default)]
    #[default("fido2".to_string())]
    pub path: String,

    /// GPG backend: "gpgme" or "gnupg-bin"
    #[arg(
        long = "pass-gpg-backend",
        env = "PASSLESS_PASS_GPG_BACKEND",
        value_name = "BACKEND"
    )]
    #[serde(default)]
    #[default("gnupg-bin".to_string())]
    pub gpg_backend: String,
}

/// Compute default TPM storage path
pub fn tpm_path() -> String {
    dirs::data_dir()
        .expect("Could not determine data directory: $XDG_DATA_HOME or $HOME/.local/share")
        .join("passless/tpm")
        .to_string_lossy()
        .into_owned()
}

/// TPM backend configuration
#[cfg(feature = "tpm")]
#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
#[group(id = "tpm-backend-config")]
pub struct TpmBackendConfig {
    /// Path to TPM storage directory
    #[arg(
        long = "tpm-path",
        env = "PASSLESS_TPM_PATH",
        id = "tpm-path",
        value_name = "PATH"
    )]
    #[serde(default)]
    #[default(tpm_path())]
    pub path: String,

    /// TPM TCTI (TPM Command Transmission Interface) configuration
    #[arg(long = "tpm-tcti", env = "PASSLESS_TPM_TCTI", value_name = "TCTI")]
    #[serde(default)]
    #[default("device:/dev/tpmrm0".to_string())]
    pub tcti: String,
}

/// Security configuration
#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
#[group(id = "security")]
pub struct SecurityConfig {
    /// Check if mlock is available to prevent credentials from being swapped to disk
    #[arg(long = "check-mlock", env = "PASSLESS_CHECK_MLOCK")]
    #[serde(default)]
    #[default(true)]
    pub check_mlock: bool,

    /// Disable core dumps to prevent credential leakage
    #[arg(long = "disable-core-dumps", env = "PASSLESS_DISABLE_CORE_DUMPS")]
    #[serde(default)]
    #[default(true)]
    pub disable_core_dumps: bool,

    /// Enable constant signature counter to help RPs detect cloned authenticators
    #[arg(
        long = "constant-signature-counter",
        env = "PASSLESS_CONSTANT_SIGNATURE_COUNTER",
        action = ArgAction::Set,
        require_equals = true,
        num_args = 0..=1,
        default_missing_value = "true"
    )]
    #[serde(default)]
    pub constant_signature_counter: bool,

    /// Always require user verification for all operations
    /// - When PIN is set + pin.enforcement="required": requires PIN
    /// - When PIN is set + pin.enforcement="optional": depends on context
    /// - When PIN is set + pin.enforcement="never": uses notification fallback
    /// - When PIN not set: uses notification
    #[arg(
        long = "always-uv",
        env = "PASSLESS_ALWAYS_UV",
        action = ArgAction::Set,
        require_equals = true,
        num_args = 0..=1,
        default_value = "true",
        default_missing_value = "true"
    )]
    #[serde(default)]
    #[default(true)]
    pub always_uv: bool,

    /// Show user verification notification during registration
    #[arg(
        long = "user-verification-registration",
        env = "PASSLESS_USER_VERIFICATION_REGISTRATION"
    )]
    #[serde(default)]
    #[default(true)]
    pub user_verification_registration: bool,

    /// Show user verification notification during authentication
    #[arg(
        long = "user-verification-authentication",
        env = "PASSLESS_USER_VERIFICATION_AUTHENTICATION"
    )]
    #[serde(default)]
    #[default(true)]
    pub user_verification_authentication: bool,

    /// Notification timeout in seconds (0 = no timeout)
    #[arg(
        long = "notification-timeout",
        env = "PASSLESS_NOTIFICATION_TIMEOUT",
        value_name = "SECONDS"
    )]
    #[serde(default)]
    #[default(30)]
    pub notification_timeout: u32,
}

/// PIN enforcement policy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PinEnforcement {
    /// Never require PIN, always use notification fallback (backward compatible)
    Never,
    /// Use PIN only when always_uv=true or client requests UV
    #[default]
    Optional,
    /// Always require PIN when set (most secure)
    Required,
}

impl std::str::FromStr for PinEnforcement {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "never" => Ok(PinEnforcement::Never),
            "optional" => Ok(PinEnforcement::Optional),
            "required" => Ok(PinEnforcement::Required),
            _ => Err(format!(
                "Invalid PIN enforcement '{}'. Must be: never, optional, or required",
                s
            )),
        }
    }
}

impl std::fmt::Display for PinEnforcement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PinEnforcement::Never => write!(f, "never"),
            PinEnforcement::Optional => write!(f, "optional"),
            PinEnforcement::Required => write!(f, "required"),
        }
    }
}

/// PIN configuration
#[derive(ClapSerde, Debug, Clone, Serialize, Deserialize, ConfigDoc)]
#[group(id = "pin")]
pub struct PinConfig {
    /// PIN enforcement policy when PIN is set:
    /// - "never": Always use notification fallback (backward compatible, convenience)
    /// - "optional": Use PIN only when always_uv=true or client requests UV
    /// - "required": Always require PIN when set (most secure)
    #[arg(
        long = "pin-enforcement",
        env = "PASSLESS_PIN_ENFORCEMENT",
        value_name = "POLICY"
    )]
    #[serde(default)]
    #[default(PinEnforcement::Optional)]
    pub enforcement: PinEnforcement,

    /// Minimum PIN length in characters (CTAP spec: 4-63)
    #[arg(
        long = "pin-min-length",
        env = "PASSLESS_PIN_MIN_LENGTH",
        value_name = "LENGTH"
    )]
    #[serde(default)]
    #[default(4)]
    pub min_length: u8,

    /// Maximum PIN retry attempts before lockout (CTAP spec: 8)
    #[arg(
        long = "pin-max-retries",
        env = "PASSLESS_PIN_MAX_RETRIES",
        value_name = "RETRIES"
    )]
    #[serde(default)]
    #[default(8)]
    pub max_retries: u8,

    /// Auto-lock timeout in seconds after max failed attempts (0 = disabled)
    /// After lockout, authenticator must be reset to use PIN again
    #[arg(
        long = "pin-auto-lock-timeout",
        env = "PASSLESS_PIN_AUTO_LOCK_TIMEOUT",
        value_name = "SECONDS"
    )]
    #[serde(default)]
    #[default(0)]
    pub auto_lock_timeout: u32,
}

impl SecurityConfig {
    /// Apply security hardening measures
    pub fn apply_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
        if self.disable_core_dumps {
            self.disable_core_dumps_impl()?;
        }
        if self.check_mlock {
            self.probe_mlock_capability()?;
        }
        Ok(())
    }

    /// Disable core dumps to prevent credential leakage
    fn disable_core_dumps_impl(&self) -> Result<(), Box<dyn std::error::Error>> {
        debug!("Disabling core dumps to prevent credential leakage");
        setrlimit(Resource::RLIMIT_CORE, 0, 0)?;
        let r = unsafe { prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) };
        if r != 0 {
            log::warn!("prctl(PR_SET_DUMPABLE) failed: {}", r);
        }
        Ok(())
    }

    /// Probe mlock capability by testing with a small allocation
    fn probe_mlock_capability(&self) -> Result<(), Box<dyn std::error::Error>> {
        debug!("Check mlock capability");

        let test_size = 4096;
        let test_buffer = vec![0u8; test_size];
        let ptr = test_buffer.as_ptr() as *const libc::c_void;

        let lock_result = unsafe { mlock(ptr, test_size) };

        if lock_result == 0 {
            unsafe { munlock(ptr, test_size) };
            log::debug!("MLOCK is enabled - sensitive data will not be swapped to disk");
        } else {
            log::warn!(
                "mlock capability probe failed - memory locking may not be available.\n\
                 Hint: grant CAP_IPC_LOCK to the binary with: 'sudo setcap cap_ipc_lock=+ep $(which passless)'"
            );
        }
        Ok(())
    }
}

/// Main application configuration
/// Note: Cannot derive Clone/Debug because it has #[clap_serde] fields
#[derive(ClapSerde, Serialize, Deserialize, Debug, ConfigDoc)]
pub struct AppConfig {
    /// Storage backend type: pass, tpm (experimental), or local (for testing)
    #[arg(short = 't', long = "backend-type", env = "PASSLESS_BACKEND_TYPE")]
    #[serde(default)]
    #[default("pass".to_string())]
    pub backend_type: String,

    /// Enable verbose logging
    // workaround for allowing `-v` syntax instead of `-v=true`
    #[arg(
        short,
        long,
        env = "PASSLESS_VERBOSE",
        action = ArgAction::Set,
        require_equals = true,
        num_args = 0..=1,
        default_missing_value = "true"
    )]
    #[default(true)]
    #[serde(default)]
    pub verbose: bool,

    /// Pass backend configuration
    #[clap_serde]
    #[serde(default)]
    #[command(flatten)]
    pub pass: PassBackendConfig,

    /// TPM backend configuration
    #[cfg(feature = "tpm")]
    #[clap_serde]
    #[serde(default)]
    #[command(flatten)]
    pub tpm: TpmBackendConfig,

    /// Local backend configuration
    #[clap_serde]
    #[serde(default)]
    #[command(flatten)]
    pub local: LocalBackendConfig,

    /// Security hardening configuration
    #[clap_serde]
    #[serde(default)]
    #[command(flatten)]
    pub security: SecurityConfig,

    /// PIN configuration
    #[clap_serde]
    #[serde(default)]
    #[command(flatten)]
    pub pin: PinConfig,
}

/// Backend-specific configuration
#[derive(Debug, Clone)]
pub enum BackendConfig {
    Local {
        path: String,
    },
    Pass {
        store_path: String,
        path: String,
        gpg_backend: String,
    },
    #[cfg(feature = "tpm")]
    Tpm {
        path: String,
        tcti: String,
    },
}

impl AppConfig {
    /// Load configuration with precedence: CLI > config file > defaults
    pub fn load(args: &mut Args) -> Self {
        // Try to load config file
        let default_config_path = dirs::config_dir().map(|p| p.join("passless/config.toml"));

        let config_file_path = args
            .config_path
            .as_ref()
            .or(default_config_path.as_ref())
            .filter(|p| p.exists());

        if let Some(path) = config_file_path
            && let Ok(f) = File::open(path)
        {
            log::info!("Loading configuration from: {}", path.display());
            let content = std::io::read_to_string(BufReader::new(f)).unwrap_or_default();
            match toml::from_str::<<AppConfig as ClapSerde>::Opt>(&content) {
                Ok(file_config) => {
                    // Deserialize into Opt, then convert with defaults and merge CLI args
                    return AppConfig::from(file_config).merge(&mut args.config);
                }
                Err(e) => log::warn!("Failed to parse config file {}: {}", path.display(), e),
            }
        }

        // No config file or parse failed - use CLI args + defaults
        AppConfig::from(&mut args.config)
    }

    /// Get the backend configuration based on the backend_type
    pub fn backend(&self) -> crate::error::Result<BackendConfig> {
        match self.backend_type.as_str() {
            "local" => Ok(BackendConfig::Local {
                path: self.local.path.clone(),
            }),
            "pass" => Ok(BackendConfig::Pass {
                store_path: self.pass.store_path.clone(),
                path: self.pass.path.clone(),
                gpg_backend: self.pass.gpg_backend.clone(),
            }),
            #[cfg(feature = "tpm")]
            "tpm" => Ok(BackendConfig::Tpm {
                path: self.tpm.path.clone(),
                tcti: self.tpm.tcti.clone(),
            }),
            _ => Err(crate::error::Error::Config(format!(
                "Invalid backend_type '{}'. Must be one of: local, pass, tpm",
                self.backend_type
            ))),
        }
    }

    /// Apply security hardening measures
    pub fn apply_security_hardening(&self) -> Result<(), Box<dyn std::error::Error>> {
        self.security.apply_hardening()
    }

    /// Get security configuration
    pub fn security_config(&self) -> SecurityConfig {
        self.security.clone()
    }

    /// Get PIN configuration
    pub fn pin_config(&self) -> PinConfig {
        self.pin.clone()
    }
}

/// CLI arguments structure
#[derive(Parser)]
#[command(author, version, about)]
pub struct Args {
    /// Path to configuration file (TOML format)
    #[arg(short, long, env = "PASSLESS_CONFIG")]
    pub config_path: Option<PathBuf>,

    /// Application configuration (can come from CLI or config file)
    #[command(flatten)]
    pub config: <AppConfig as ClapSerde>::Opt,

    /// Subcommands
    #[command(subcommand)]
    pub command: Option<Commands>,
}

/// Output format for client commands
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable plain text output
    Plain,
    /// JSON output for programmatic consumption
    Json,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "plain" => Ok(OutputFormat::Plain),
            "json" => Ok(OutputFormat::Json),
            _ => Err(format!(
                "Invalid output format '{}'. Must be 'plain' or 'json'",
                s
            )),
        }
    }
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputFormat::Plain => write!(f, "plain"),
            OutputFormat::Json => write!(f, "json"),
        }
    }
}

/// Subcommands for passless
#[derive(Subcommand, Debug, Clone)]
pub enum Commands {
    /// Configuration management commands
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// FIDO2 client commands for managing authenticators
    ///
    /// These commands require a running authenticator. For testing:
    /// 1. Start authenticator: PASSLESS_E2E_AUTO_ACCEPT_UV=1 cargo run -- --backend-type local
    /// 2. Run client commands in another terminal with the same environment variable
    Client {
        /// Select device by index (0-based) or name. Use 'devices' subcommand to list available devices.
        #[arg(short = 'D', long = "device", value_name = "INDEX|NAME", global = true)]
        device: Option<String>,

        /// Output format: plain (default) or json
        #[arg(
            short = 'o',
            long = "output",
            value_name = "FORMAT",
            default_value = "plain",
            global = true
        )]
        output: OutputFormat,

        #[command(subcommand)]
        action: ClientAction,
    },
}

/// Configuration actions
#[derive(Subcommand, Debug, Clone)]
pub enum ConfigAction {
    /// Print the default configuration in TOML format
    Print,
}

/// Client actions for FIDO2 authenticator management
#[derive(Subcommand, Debug, Clone)]
pub enum ClientAction {
    /// List all available FIDO2 authenticators/devices
    Devices,
    /// Get authenticator information (capabilities, AAGUID, versions, etc.)
    Info,
    /// Reset the authenticator (WARNING: deletes ALL credentials)
    Reset {
        /// Confirmation flag that must be provided twice for safety
        #[arg(long = "yes-i-really-want-to-reset-my-device", action = ArgAction::Count)]
        confirm: u8,
    },
    /// List all credentials on the authenticator
    List {
        /// Filter by relying party ID (domain)
        #[arg(short = 'd', long = "domain", value_name = "DOMAIN")]
        rp_id: Option<String>,
    },
    /// Show detailed information about a specific credential
    Show {
        /// Credential ID in hexadecimal format
        #[arg(value_name = "CREDENTIAL_ID")]
        credential_id: String,
    },
    /// Delete a specific credential by ID
    Delete {
        /// Credential ID in hexadecimal format
        #[arg(value_name = "CREDENTIAL_ID")]
        credential_id: String,
    },
    /// Rename a credential (update user name and/or display name)
    Rename {
        /// Credential ID in hexadecimal format
        #[arg(value_name = "CREDENTIAL_ID")]
        credential_id: String,
        /// New user name (login identifier)
        #[arg(short = 'u', long = "user-name", value_name = "NAME")]
        user_name: Option<String>,
        /// New display name (friendly name)
        #[arg(short = 'n', long = "display-name", value_name = "NAME")]
        display_name: Option<String>,
    },
    /// PIN management commands
    Pin {
        #[command(subcommand)]
        action: PinAction,
    },
}

/// PIN management actions
#[derive(Subcommand, Debug, Clone)]
pub enum PinAction {
    /// Set a new PIN (authenticator must not have a PIN set)
    Set {
        /// The new PIN (minimum 4 characters)
        #[arg(value_name = "PIN")]
        pin: String,
    },
    /// Change the existing PIN
    Change {
        /// The current PIN
        #[arg(value_name = "OLD_PIN")]
        old_pin: String,
        /// The new PIN (minimum 4 characters)
        #[arg(value_name = "NEW_PIN")]
        new_pin: String,
    },
}