auc-tool 0.1.0

Machine-local software passkey authenticator exposed through Linux UHID.
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
use std::fs;
use std::os::unix::fs::{FileTypeExt, MetadataExt};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail};
use capulus::managed::{
    BuildArtifacts, JobId, RedeployCoordinator, SystemInstallation, SystemUninstallation,
    UnixAccount,
};
use serde::{Deserialize, Serialize};

use crate::product::{ACCESS_GROUP, managed_product, wait_until_healthy};
use crate::vault::Vault;

const ACCESS_POLICY_PATH: &str = "/var/lib/auc/access-policy.json";
const ACCESS_POLICY_SCHEMA: u16 = 1;
const COMMAND_OUTPUT_LIMIT: usize = 64 * 1024;

pub async fn install(operator_uid: u32) -> Result<()> {
    require_root()?;
    validate_audit_login(operator_uid)?;
    let operator = UnixAccount::by_uid(operator_uid)?;
    operator.validate_interactive()?;
    ensure_uhid_device()?;
    let product = managed_product()?;
    let artifacts =
        BuildArtifacts::from_local_directory(&product, local_binary_directory()?, &operator)?;
    Vault::open().context("failed to initialize or validate the auc vault")?;
    let mut access = AccessGroupSetup::prepare(operator)?;
    let mut installation =
        match SystemInstallation::prepare(&product, JobId::random(), &artifacts, &access.operator)
            .await
        {
            Ok(installation) => installation,
            Err(error) => {
                access.rollback()?;
                return Err(error.context("failed to prepare the auc system installation"));
            }
        };
    if let Err(error) = installation.commit_files() {
        return Err(rollback_installation(&mut installation, &mut access, error).await);
    }
    if let Err(error) = installation.activate().await {
        return Err(rollback_installation(&mut installation, &mut access, error).await);
    }
    let version = product.version().clone();
    let health =
        tokio::task::spawn_blocking(move || wait_until_healthy(&version, Duration::from_secs(60)))
            .await
            .context("auc installation health task panicked")?;
    if let Err(error) = health {
        return Err(rollback_installation(&mut installation, &mut access, error).await);
    }
    if let Err(error) = access.commit() {
        return Err(rollback_installation(&mut installation, &mut access, error).await);
    }
    if let Err(error) = installation.finalize() {
        if installation.acceptance_committed() {
            access.finish();
            return Err(error.context(
                "auc is installed and healthy, but committed installation cleanup failed",
            ));
        }
        return Err(rollback_installation(&mut installation, &mut access, error).await);
    }
    access.finish();
    Ok(())
}

pub async fn uninstall(operator_uid: u32, purge_vault: bool) -> Result<()> {
    require_root()?;
    validate_audit_login(operator_uid)?;
    let operator = UnixAccount::by_uid(operator_uid)?;
    operator.validate_interactive()?;
    let policy = read_access_policy()?.ok_or_else(|| anyhow!("auc access policy is missing"))?;
    if !policy.operator_uids.contains(&operator_uid) || !user_has_group(&operator)? {
        bail!("the invoking user is not an authorized auc operator");
    }
    let product = Arc::new(managed_product()?);
    if RedeployCoordinator::new(Arc::clone(&product))?
        .reconciled_active()
        .await?
        .is_some_and(|job| !job.phase.is_terminal())
    {
        bail!("auc cannot be uninstalled while a redeploy is active");
    }
    ensure_no_pending_presence()?;
    let mut uninstallation = SystemUninstallation::prepare(&product, JobId::random()).await?;
    if let Err(error) = uninstallation.deactivate().await {
        return Err(rollback_uninstallation(&mut uninstallation, error).await);
    }
    if let Err(error) = uninstallation.remove_files() {
        return Err(rollback_uninstallation(&mut uninstallation, error).await);
    }
    if let Err(error) = uninstallation.finalize().await {
        if uninstallation.removal_committed() {
            return Err(error.context(
                "auc system files were removed, but committed uninstall cleanup is incomplete",
            ));
        }
        return Err(rollback_uninstallation(&mut uninstallation, error).await);
    }
    if purge_vault {
        Vault::purge().context("auc system files were removed, but vault destruction failed")?;
        checked_command(
            "/usr/sbin/groupdel",
            &[ACCESS_GROUP],
            "remove the auc access group",
        )
        .context("auc and its vault were removed, but the access group remains")?;
    }
    Ok(())
}

async fn rollback_uninstallation(
    uninstallation: &mut SystemUninstallation,
    cause: anyhow::Error,
) -> anyhow::Error {
    match uninstallation.rollback().await {
        Ok(()) => cause.context("auc uninstall failed and the installation was restored"),
        Err(rollback) => anyhow!(
            "auc uninstall failed: {cause:#}; restoring the installation also failed: {rollback:#}"
        ),
    }
}

fn ensure_no_pending_presence() -> Result<()> {
    use crate::application::{ApplicationClient, ApplicationRequest, ApplicationResponse};
    use crate::product::APPLICATION_SOCKET_PATH;

    match ApplicationClient::new(APPLICATION_SOCKET_PATH).request(ApplicationRequest::Status)? {
        ApplicationResponse::Status(status) if status.pending_touch => {
            bail!("auc cannot be uninstalled while a presence request is pending")
        }
        ApplicationResponse::Status(_) => Ok(()),
        _ => bail!("auc-agent returned the wrong status response before uninstall"),
    }
}

async fn rollback_installation(
    installation: &mut SystemInstallation,
    access: &mut AccessGroupSetup,
    cause: anyhow::Error,
) -> anyhow::Error {
    let installation_rollback = installation.rollback().await;
    let access_rollback = access.rollback();
    match (installation_rollback, access_rollback) {
        (Ok(()), Ok(())) => cause.context("auc installation failed and was rolled back"),
        (system, group) => anyhow!(
            "auc installation failed: {cause:#}; system rollback: {}; access-group rollback: {}",
            outcome(&system),
            outcome(&group),
        ),
    }
}

fn outcome(result: &Result<()>) -> String {
    match result {
        Ok(()) => "succeeded".to_string(),
        Err(error) => format!("failed: {error:#}"),
    }
}

fn local_binary_directory() -> Result<PathBuf> {
    let executable = fs::canonicalize("/proc/self/exe")
        .context("failed to resolve the running auc-agent executable")?;
    if executable.file_name().and_then(|name| name.to_str()) != Some("auc-agent") {
        bail!("the installation executable is not named auc-agent");
    }
    executable
        .parent()
        .map(Path::to_path_buf)
        .ok_or_else(|| anyhow!("auc-agent executable has no parent directory"))
}

fn validate_audit_login(operator_uid: u32) -> Result<()> {
    let value = fs::read_to_string("/proc/self/loginuid")
        .context("failed to read the kernel audit login UID")?;
    let login_uid = value
        .trim()
        .parse::<u32>()
        .context("kernel audit login UID is malformed")?;
    if login_uid == u32::MAX {
        bail!("kernel audit login UID is unset; run auc system install from a real login session");
    }
    if login_uid != operator_uid {
        bail!("requested auc operator does not match the kernel audit login UID");
    }
    Ok(())
}

fn ensure_uhid_device() -> Result<()> {
    let path = Path::new("/dev/uhid");
    if fs::symlink_metadata(path).is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound) {
        checked_command(
            "/usr/sbin/modprobe",
            &["uhid"],
            "load the Linux UHID kernel module",
        )?;
    }
    let metadata = fs::symlink_metadata(path).context("Linux did not expose /dev/uhid")?;
    if !metadata.file_type().is_char_device() {
        bail!("/dev/uhid is not a real character device");
    }
    Ok(())
}

struct AccessGroupSetup {
    operator: UnixAccount,
    policy: AccessPolicy,
    group_created: bool,
    member_added: bool,
    policy_written: bool,
    finished: bool,
}

impl AccessGroupSetup {
    fn prepare(operator: UnixAccount) -> Result<Self> {
        let existing_policy = read_access_policy()?;
        let group_exists = command_success("/usr/bin/getent", &["group", ACCESS_GROUP])?;
        let group_created = match (existing_policy.is_some(), group_exists) {
            (true, true) => false,
            (true, false) => bail!("auc access policy exists but its Unix group is missing"),
            (false, true) => bail!("refusing to take ownership of a pre-existing auc Unix group"),
            (false, false) => {
                checked_command(
                    "/usr/sbin/groupadd",
                    &["--system", ACCESS_GROUP],
                    "create the auc access group",
                )?;
                true
            }
        };
        let policy = existing_policy.unwrap_or(AccessPolicy {
            schema: ACCESS_POLICY_SCHEMA,
            operator_uids: Vec::new(),
        });
        policy.validate()?;
        Ok(Self {
            operator,
            policy,
            group_created,
            member_added: false,
            policy_written: false,
            finished: false,
        })
    }

    fn commit(&mut self) -> Result<()> {
        if !self.policy.operator_uids.contains(&self.operator.uid) {
            checked_command(
                "/usr/sbin/usermod",
                &["--append", "--groups", ACCESS_GROUP, &self.operator.name],
                "add the selected user to the auc access group",
            )?;
            self.member_added = true;
            self.policy.operator_uids.push(self.operator.uid);
            self.policy.operator_uids.sort_unstable();
        }
        if !user_has_group(&self.operator)? {
            bail!("selected auc operator did not acquire access-group membership");
        }
        capulus::store::atomic_write(
            Path::new(ACCESS_POLICY_PATH),
            &serde_json::to_vec(&self.policy)?,
            Some(0o600),
            None,
        )?;
        self.policy_written = true;
        Ok(())
    }

    fn rollback(&mut self) -> Result<()> {
        let mut errors = Vec::new();
        if self.policy_written {
            if self.group_created {
                if let Err(error) = fs::remove_file(ACCESS_POLICY_PATH)
                    && error.kind() != std::io::ErrorKind::NotFound
                {
                    errors.push(anyhow!(error).context("remove new auc access policy"));
                }
            } else if self.member_added {
                self.policy
                    .operator_uids
                    .retain(|uid| *uid != self.operator.uid);
                if let Err(error) = capulus::store::atomic_write(
                    Path::new(ACCESS_POLICY_PATH),
                    &serde_json::to_vec(&self.policy)?,
                    Some(0o600),
                    None,
                ) {
                    errors.push(error.context("restore auc access policy"));
                }
            }
            self.policy_written = false;
        }
        if self.group_created {
            if let Err(error) = checked_command(
                "/usr/sbin/groupdel",
                &[ACCESS_GROUP],
                "remove the new auc access group",
            ) {
                errors.push(error);
            }
            self.group_created = false;
            self.member_added = false;
        } else if self.member_added {
            if let Err(error) = checked_command(
                "/usr/bin/gpasswd",
                &["--delete", &self.operator.name, ACCESS_GROUP],
                "restore auc access-group membership",
            ) {
                errors.push(error);
            }
            self.member_added = false;
        }
        if errors.is_empty() {
            Ok(())
        } else {
            bail!(
                "{}",
                errors
                    .into_iter()
                    .map(|error| format!("{error:#}"))
                    .collect::<Vec<_>>()
                    .join("; ")
            )
        }
    }

    fn finish(&mut self) {
        self.finished = true;
    }
}

impl Drop for AccessGroupSetup {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.rollback();
        }
    }
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct AccessPolicy {
    schema: u16,
    operator_uids: Vec<u32>,
}

impl AccessPolicy {
    fn validate(&self) -> Result<()> {
        if self.schema != ACCESS_POLICY_SCHEMA
            || self.operator_uids.len() > 64
            || self.operator_uids.contains(&0)
            || self
                .operator_uids
                .windows(2)
                .any(|window| window[0] >= window[1])
        {
            bail!("auc access policy is invalid");
        }
        Ok(())
    }
}

fn read_access_policy() -> Result<Option<AccessPolicy>> {
    let path = Path::new(ACCESS_POLICY_PATH);
    let metadata = match fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    if !metadata.file_type().is_file()
        || metadata.uid() != 0
        || metadata.gid() != 0
        || metadata.mode() & 0o7777 != 0o600
        || metadata.len() > 16 * 1024
    {
        bail!("auc access policy failed ownership, type, mode, or size validation");
    }
    let policy: AccessPolicy = serde_json::from_slice(&fs::read(path)?)?;
    policy.validate()?;
    Ok(Some(policy))
}

pub(crate) fn operator_is_authorized(uid: u32) -> Result<bool> {
    Ok(
        read_access_policy()?
            .is_some_and(|policy| policy.operator_uids.binary_search(&uid).is_ok()),
    )
}

fn user_has_group(account: &UnixAccount) -> Result<bool> {
    let output = checked_output(
        "/usr/bin/id",
        &["--name", "--groups", &account.name],
        "inspect auc access-group membership",
    )?;
    Ok(String::from_utf8(output.stdout)?
        .split_whitespace()
        .any(|group| group == ACCESS_GROUP))
}

fn command_success(program: &str, arguments: &[&str]) -> Result<bool> {
    let output = Command::new(program)
        .env_clear()
        .env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
        .env("LANG", "C.UTF-8")
        .args(arguments)
        .output()?;
    ensure_bounded_output(&output)?;
    match output.status.code() {
        Some(0) => Ok(true),
        Some(2) => Ok(false),
        _ => bail!("{} failed: {}", program, output_detail(&output)),
    }
}

fn checked_command(program: &str, arguments: &[&str], action: &str) -> Result<()> {
    checked_output(program, arguments, action).map(|_| ())
}

fn checked_output(program: &str, arguments: &[&str], action: &str) -> Result<Output> {
    let output = Command::new(program)
        .env_clear()
        .env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin")
        .env("LANG", "C.UTF-8")
        .args(arguments)
        .output()
        .with_context(|| format!("failed to {action}"))?;
    ensure_bounded_output(&output)?;
    if !output.status.success() {
        bail!("failed to {action}: {}", output_detail(&output));
    }
    Ok(output)
}

fn ensure_bounded_output(output: &Output) -> Result<()> {
    if output.stdout.len() > COMMAND_OUTPUT_LIMIT || output.stderr.len() > COMMAND_OUTPUT_LIMIT {
        bail!("system account command output exceeded its safety limit");
    }
    Ok(())
}

fn output_detail(output: &Output) -> String {
    String::from_utf8_lossy(if output.stderr.is_empty() {
        &output.stdout
    } else {
        &output.stderr
    })
    .trim()
    .to_string()
}

fn require_root() -> Result<()> {
    if rustix::process::geteuid().is_root() {
        Ok(())
    } else {
        bail!("auc system installation requires root")
    }
}