podbox-cli 0.7.1

Declarative Podman-native container environment manager. Define an environment as a TOML file and let systemd own its lifecycle.
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
//! Per-message protocol handlers for the host socket server (`hello`,
//! `host-exec`, `notify`, `xdg-open`, `clipboard`). Single cohesive concern;
//! stays above ~300 LOC because the message-dispatch contract is one unit
//! (documented exemption, per the modularization guide 1/8).
use std::io::Write;
use std::os::unix::net::UnixStream;
use std::time::Duration;

use crate::config::IntegrationConfig;
use crate::protocol::{HostMessage, write_frame};

/// Outcome of a `Hello` handshake.
pub(super) enum HelloOutcome {
    /// Handshake accepted; carries the list of granted capabilities.
    Accepted(Vec<String>),
    /// Handshake rejected (e.g. protocol version mismatch).
    Rejected,
}

/// Handle a `Hello` handshake from the guest.
///
/// On success returns the list of accepted capabilities, which the connection
/// uses to gate subsequent messages. A protocol version mismatch is a failed
/// negotiation and must not grant any capability or claim the daemon stream.
pub(super) fn handle_hello(
    stream: &mut UnixStream,
    config: &IntegrationConfig,
    idle_timeout_secs: u64,
    protocol_version: u32,
    guest_version: String,
    container: String,
    capabilities: Vec<String>,
) -> anyhow::Result<HelloOutcome> {
    if protocol_version != crate::protocol::PROTOCOL_VERSION {
        tracing::error!(
            "protocol mismatch — got v{}, expected v{}",
            protocol_version,
            crate::protocol::PROTOCOL_VERSION
        );
        write_frame(stream, &HostMessage::Shutdown)?;
        return Ok(HelloOutcome::Rejected);
    }
    tracing::info!(
        "guest hello (v{}, container: {}, caps: {:?})",
        guest_version,
        container,
        capabilities
    );
    let mut accepted = Vec::new();
    let mut rejected = Vec::new();
    for cap in capabilities {
        let enabled = match cap.as_str() {
            crate::protocol::CAP_NOTIFY => config.notify,
            crate::protocol::CAP_XDG_OPEN => config.xdg_open,
            crate::protocol::CAP_CLIPBOARD => config.clipboard,
            crate::protocol::CAP_HOST_EXEC => config.host_exec.enabled,
            _ => false,
        };
        if enabled {
            accepted.push(cap);
        } else {
            rejected.push(cap);
        }
    }
    let host_exec_shims = if config.host_exec.enabled {
        config.host_exec.guest_shims()
    } else {
        Vec::new()
    };
    let response = HostMessage::HelloAck {
        accepted: accepted.clone(),
        rejected,
        idle_timeout_secs,
        host_exec_shims,
    };
    write_frame(stream, &response)?;
    Ok(HelloOutcome::Accepted(accepted))
}

/// Handle a `Notify` message from the guest.
pub(super) fn handle_notify(
    stream: &mut UnixStream,
    summary: String,
    body: String,
    actions: Vec<crate::protocol::NotifyAction>,
) -> anyhow::Result<()> {
    if actions.is_empty() {
        let _ = notify_rust::Notification::new()
            .summary(&summary)
            .body(&body)
            .show();
    } else {
        let mut notif = notify_rust::Notification::new();
        notif.summary(&summary).body(&body);
        for action in &actions {
            notif.action(&action.key, &action.label);
        }
        let handle = match notif.show() {
            Ok(h) => h,
            Err(_) => {
                let _ = write_frame(
                    stream,
                    &HostMessage::NotifyActionResult {
                        notification_id: 0,
                        action_key: String::new(),
                    },
                );
                return Ok(());
            }
        };
        let mut chosen_key = String::new();
        handle.wait_for_action(|action| {
            chosen_key = action.to_string();
        });
        let _ = write_frame(
            stream,
            &HostMessage::NotifyActionResult {
                notification_id: 0,
                action_key: chosen_key,
            },
        );
    }
    Ok(())
}

/// Handle an `XdgOpen` message from the guest.
pub(super) fn handle_xdg_open(uri: String) -> anyhow::Result<()> {
    if let Some(validated) = validate_uri(&uri) {
        let args = [validated.into()];
        let _ =
            crate::process::spawn_interactive_timeout("xdg-open", &args, Duration::from_secs(30));
    }
    Ok(())
}

/// Handle a `ClipboardSet` message from the guest.
pub(super) fn handle_clipboard_set(text: String) -> anyhow::Result<()> {
    let mut child = std::process::Command::new("wl-copy")
        .stdin(std::process::Stdio::piped())
        .spawn()?;
    if let Some(ref mut stdin) = child.stdin {
        let _ = stdin.write_all(text.as_bytes());
    }
    drop(child.stdin.take());
    let _ = crate::process::wait_child_timeout(child, Duration::from_secs(10))?;
    Ok(())
}

/// Handle a `ClipboardGet` message from the guest.
pub(super) fn handle_clipboard_get(stream: &mut UnixStream) -> anyhow::Result<()> {
    let output = std::process::Command::new("wl-paste").output()?;
    let text = String::from_utf8_lossy(&output.stdout);
    let response = HostMessage::ClipboardData {
        text: text.trim().to_string(),
    };
    write_frame(stream, &response)?;
    Ok(())
}

/// Handle a `HostExec` message from the guest.
pub(super) fn handle_host_exec(
    stream: &mut UnixStream,
    config: &IntegrationConfig,
    cmd: String,
    args: Vec<String>,
) -> anyhow::Result<()> {
    if !config.host_exec.enabled {
        write_frame(
            stream,
            &HostMessage::HostExecStderr {
                data: "host-exec is disabled".into(),
            },
        )?;
        write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
        return Ok(());
    }

    let entry = match config.host_exec.resolve(&cmd) {
        Some(e) => e,
        None => {
            let allowed = config
                .host_exec
                .allowlist
                .as_ref()
                .map(|m| m.keys().cloned().collect::<Vec<_>>().join(", "))
                .unwrap_or_default();
            write_frame(
                stream,
                &HostMessage::HostExecStderr {
                    data: format!(
                        "Permission denied: '{cmd}' is not in the host-exec allowlist\nAllowed commands: {allowed}"
                    ),
                },
            )?;
            write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
            return Ok(());
        }
    };

    // Conditional argument filtering: when `filter = false` the blocklist is
    // bypassed for this command (execution still uses execve, not a shell).
    if entry.filter_enabled() {
        if let Err(msg) = validate_host_exec_args(&args) {
            write_frame(
                stream,
                &HostMessage::HostExecStderr {
                    data: format!("Security violation: {msg}"),
                },
            )?;
            write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
            return Ok(());
        }
    } else {
        tracing::debug!(
            "host-exec: security argument filter bypassed for '{cmd}' (filter = false)"
        );
    }
    let resolved = entry.path();

    // Canonicalize the resolved path to mitigate TOCTOU symlink swaps.
    // If the path resolves outside expected system directories (e.g.
    // /nix/store, /usr/bin, etc.), we still allow it — the important thing
    // is that it points to a real regular file right now.
    let canonical_path = match std::fs::canonicalize(resolved) {
        Ok(p) => p,
        Err(e) => {
            tracing::error!("host-exec: failed to canonicalize '{}': {e}", resolved);
            write_frame(
                stream,
                &HostMessage::HostExecStderr {
                    data: format!("Failed to resolve executable path '{resolved}': {e}"),
                },
            )?;
            write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
            return Ok(());
        }
    };
    if !canonical_path.is_file() {
        write_frame(
            stream,
            &HostMessage::HostExecStderr {
                data: format!("'{}' is not a regular file", canonical_path.display()),
            },
        )?;
        write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
        return Ok(());
    }
    tracing::info!(
        "host-exec: resolved '{}' -> {}",
        resolved,
        canonical_path.display()
    );

    match std::process::Command::new(&canonical_path)
        .args(&args)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
    {
        Ok(child) => {
            let output = crate::process::wait_child_timeout(child, Duration::from_mins(1))?;
            if !output.stdout.is_empty() {
                write_frame(
                    stream,
                    &HostMessage::HostExecStdout {
                        data: String::from_utf8_lossy(&output.stdout).to_string(),
                    },
                )?;
            }
            if !output.stderr.is_empty() {
                write_frame(
                    stream,
                    &HostMessage::HostExecStderr {
                        data: String::from_utf8_lossy(&output.stderr).to_string(),
                    },
                )?;
            }
            let code = output.status.code().unwrap_or(1);
            write_frame(stream, &HostMessage::HostExecDone { exit_code: code })?;
        }
        Err(e) => {
            let msg = if e.kind() == std::io::ErrorKind::NotFound {
                format!("host-exec: '{cmd}' not found in allowlist path or host $PATH")
            } else {
                format!("host-exec: failed to execute '{cmd}': {e}")
            };
            write_frame(stream, &HostMessage::HostExecStderr { data: msg })?;
            write_frame(stream, &HostMessage::HostExecDone { exit_code: 1 })?;
        }
    }
    Ok(())
}

/// Validate arguments for host-exec, rejecting shell metacharacters and
/// dangerous flag patterns that could alter the behaviour of a whitelisted
/// binary (e.g. `git --exec-path=…`).
///
/// # Security model and limitations
///
/// Arguments are validated with a substring blocklist. Commands run via
/// `execve` directly — **not** through `/bin/sh` — so metacharacters like
/// `;`, `|`, `$(` cannot cause shell injection on ordinary ELF binaries.
/// The blocklist exists to reduce misuse, not to make arbitrary allowlist
/// entries safe.
///
/// Known bypass classes that this filter **cannot** prevent:
///
/// * Versatile binaries: any program with code-execution or file-access
///   flags defeats substring filtering regardless of metacharacters —
///   e.g. `git -C /root …`, `git clone --upload-pack=…`, `find -exec …`,
///   `tar --to-command=…`, `python -c …`, `ssh -oProxyCommand=…`.
/// * Flag synonyms: only a small set of dangerous prefixes is known; an
///   allowlisted binary may expose others (`--pager`, `-c`, `--eval`, …).
///
/// Therefore:
///
/// * Allowlist only restricted binaries or dedicated wrapper scripts.
/// * Prefer wrappers that pin the arguments (e.g. a script exposing exactly
///   `systemctl --user status <unit>`), rather than raw `git`, `python`,
///   `tar`, `find`, or shells.
/// * Treat every allowlist entry as granting the guest that binary's full
///   capability surface on the host.
///
/// False positives are expected: benign messages containing `<()`, globs,
/// or parentheses are rejected. Affected users should route those commands
/// through a wrapper script instead of loosening this filter.
pub(super) fn validate_host_exec_args(args: &[String]) -> Result<(), String> {
    for arg in args {
        if arg.contains(';')
            || arg.contains('|')
            || arg.contains('&')
            || arg.contains('$')
            || arg.contains('`')
            || arg.contains('\n')
            || arg.contains('\r')
        {
            return Err(format!("argument {arg:?} contains shell metacharacters"));
        }
        if arg.contains('<') || arg.contains('>') {
            return Err(format!("argument {arg:?} contains redirection operators"));
        }
        if arg.contains('*')
            || arg.contains('?')
            || arg.contains('[')
            || arg.contains(']')
            || arg.contains('{')
            || arg.contains('}')
        {
            return Err(format!(
                "argument {arg:?} contains glob or brace characters"
            ));
        }
        if arg.contains('(') || arg.contains(')') || arg.contains('\\') {
            return Err(format!(
                "argument {arg:?} contains subshell or escape characters"
            ));
        }
        let lower = arg.to_ascii_lowercase();
        if lower.starts_with("--exec-path")
            || lower.starts_with("--config")
            || lower.starts_with("--plugin")
            || lower.starts_with("--load")
            || lower.starts_with("--module")
            || lower.starts_with("--remote=")
            || lower == "-o"
        {
            return Err(format!("argument {arg:?} uses a restricted flag pattern"));
        }
    }
    Ok(())
}

pub(super) fn validate_uri(uri: &str) -> Option<String> {
    let s = uri.trim();
    if s.is_empty() || s.starts_with('/') || s.starts_with('.') {
        return None;
    }

    match url::Url::parse(s) {
        Ok(parsed) => {
            let scheme = parsed.scheme().to_ascii_lowercase();

            // Blacklist local disk access, XSS, and command-injection vectors
            let dangerous_schemes = [
                "file",
                "javascript",
                "data",
                "ghelp",
                "help",
                "info",
                "man",
                "shell",
                "exec",
                "run",
                "local",
                "ssh",
            ];

            if dangerous_schemes.contains(&scheme.as_str()) {
                return None;
            }

            // Ensure the schema format complies with RFC 3986 standards
            let is_valid_format = scheme.starts_with(|c: char| c.is_ascii_alphabetic())
                && scheme
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '.' || c == '-');

            if is_valid_format {
                Some(s.to_string())
            } else {
                None
            }
        }
        Err(url::ParseError::RelativeUrlWithoutBase) => {
            // Automatically wrap raw hostnames like "github.com"
            Some(format!("https://{s}"))
        }
        _ => None,
    }
}