Repository navigation
Expand file tree
/
Copy pathserver.rs
More file actions
1638 lines (1526 loc) · 67.3 KB
/
Copy pathserver.rs
File metadata and controls
1638 lines (1526 loc) · 67.3 KB
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashSet, VecDeque};
use std::fs;
use std::io::{self, ErrorKind, Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant};
use crate::audit::{AuditConfig, AuditLog, Event, Outcome, Reject};
use crate::executor::{exec_direct, exec_pkexec, exec_sudo, sanitize_env};
use crate::mode::Mode;
use crate::protocol::{Request, Response, ValidatedRequest};
use crate::tui::{self, Prompter, ResultSink};
const PROMPT_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_REQUEST_AGE: Duration = Duration::from_secs(60);
/// How far in the future a request's `time` may be. A request to a remote
/// daemon carries the *client's* clock, so a little skew is tolerated; beyond
/// it the request is rejected. Without this bound a future-dated request
/// stayed fresh forever and became replayable once its id was evicted
/// (GHSA-h6r4-gh2r-qr98).
const MAX_FUTURE_SKEW: Duration = Duration::from_secs(30);
/// How long replay-protection ids are remembered. A request accepted at `t`
/// has `time <= t + MAX_FUTURE_SKEW`, so it can pass the freshness check
/// again only until `t + MAX_FUTURE_SKEW + MAX_REQUEST_AGE`. Retention must
/// cover that span so any id that could still pass freshness is still in the
/// set; the assertion below enforces it at compile time.
const REPLAY_RETENTION: Duration = Duration::from_secs(120);
const _: () = assert!(
REPLAY_RETENTION.as_secs() >= MAX_REQUEST_AGE.as_secs() + MAX_FUTURE_SKEW.as_secs(),
"REPLAY_RETENTION must cover MAX_REQUEST_AGE + MAX_FUTURE_SKEW"
);
/// Per-syscall read/write timeout. Bounds any single I/O operation.
const CONNECTION_IO_TIMEOUT: Duration = Duration::from_secs(5);
/// Wall-clock deadline for completing the request handshake (read+parse).
/// CONNECTION_IO_TIMEOUT bounds each syscall, but a slow-loris client
/// could trickle bytes within each window indefinitely. This deadline
/// puts an upper bound on the whole handshake regardless of pacing.
const HANDSHAKE_DEADLINE: Duration = Duration::from_secs(10);
/// Hard cap on the size of one JSON request line, including the trailing
/// newline. Bounds the per-connection read buffer.
const MAX_REQUEST_BYTES: usize = 1_048_576;
/// Default ceiling on concurrent handler threads. A buggy or hostile
/// same-UID process that opens N connections must not be able to spawn N
/// threads; once the cap is reached, new connections receive a `busy`
/// error and are closed without spawning. Soft cap — chosen high enough
/// that legitimate burst usage is unaffected.
pub const DEFAULT_MAX_IN_FLIGHT: usize = 64;
/// Returns the SSH_AUTH_SOCK forwarded to the daemon, if any.
///
/// Read from the daemon's *own* environment (set by sshd when the user
/// opened the tunnel with `-A`), never from a request — the request env
/// is controlled by the local peer. Used by the executor to inject the
/// socket into unprivileged children that requested `forward_agent`.
///
/// The daemon never mutates its own environment, so live-reading gives a
/// stable value across the daemon's lifetime; we don't bother caching.
pub fn forwarded_agent_socket() -> Option<String> {
std::env::var("SSH_AUTH_SOCK").ok()
}
/// Reject requests whose `time` is missing, malformed, older than
/// MAX_REQUEST_AGE, or more than MAX_FUTURE_SKEW in the future. Performed at
/// connection-handler entry, before any TTY contention, so a request's
/// freshness is judged at acceptance rather than after waiting in line.
fn check_freshness(req: &Request) -> Result<(), String> {
if req.time.is_empty() {
return Err("missing time field".to_string());
}
let age = parse_age(&req.time).ok_or_else(|| "malformed time field".to_string())?;
check_age(age)
}
/// The freshness window on a signed age (seconds; negative = future-dated).
/// Split from `check_freshness` so the window can be tested without a clock.
fn check_age(age: i64) -> Result<(), String> {
if age < 0 && age.unsigned_abs() > MAX_FUTURE_SKEW.as_secs() {
return Err(format!(
"request time is {}s in the future (max skew {}s)",
age.unsigned_abs(),
MAX_FUTURE_SKEW.as_secs()
));
}
if age > 0 && age.unsigned_abs() > MAX_REQUEST_AGE.as_secs() {
return Err(format!(
"request too old: {age}s (max {}s)",
MAX_REQUEST_AGE.as_secs()
));
}
Ok(())
}
/// Reject a `stop` dated before this daemon instance started (issue #63).
///
/// Replay protection (`SeenIds`) is in memory, per instance, so on its own it
/// would let a stop captured from a previous instance stop a freshly restarted
/// one while still inside the freshness window. Any stop accepted by an
/// earlier instance is dated before that instance exited, hence before this
/// one started. The comparison is strict: `time` has one-second resolution and
/// a legitimate request satisfies `floor(sent) >= floor(started)`, so `<` never
/// rejects one (barring clock skew between client and daemon). The residual
/// gap is a restart within the same wall-clock second as the original stop.
fn check_not_before_start(req_epoch: u64, started_epoch: u64) -> Result<(), String> {
if req_epoch < started_epoch {
return Err(format!(
"stop request predates this daemon instance (request {}s before start)",
started_epoch - req_epoch
));
}
Ok(())
}
/// Recover poisoned mutex guards. The two mutexes in this module guard
/// `SeenIds` (whose only mutation is insert / evict — no broken
/// invariant after a panic) and `()` (the TTY serializer — no state).
/// A panicking prompter must not poison the daemon for every subsequent
/// request.
fn lock_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// ` [req <requester>]` for the daemon's stderr log lines, or empty when the
/// peer declared none — so "approved, requested by an AI" is greppable until
/// the append-only audit log (#6) persists the field. Self-declared, unverified.
fn requester_tag(req: &Request) -> String {
if req.requester.is_empty() {
String::new()
} else {
format!(" [req {}]", req.requester)
}
}
/// Log the underlying `io::Error` from a failed `Prompter::prompt`.
///
/// Verbose-only because a healthy daemon never hits this branch; when
/// it does, the kind + raw_os_error is what distinguishes a benign
/// `BrokenPipe` (peer hung up mid-prompt) from a residual
/// background-pgrp `EIO` (the fix from PR #22 turned the daemon-stop
/// hang into this errno; if it ever recurs, it shows up here).
fn log_prompt_io_error(verbose: bool, id: &str, e: &io::Error) {
if !verbose {
return;
}
eprintln!(
"[{id}] prompt io error: kind={:?} raw_os_error={:?}: {e}",
e.kind(),
e.raw_os_error()
);
}
/// RAII decrement of `in_flight` on drop. Plain `fetch_sub` after
/// `handle_connection` would be skipped on panic, leaking the counter.
struct InFlightGuard {
counter: Arc<AtomicUsize>,
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
self.counter.fetch_sub(1, Ordering::Relaxed);
}
}
/// Parse an ISO 8601 UTC timestamp and return its signed age relative to
/// now, in seconds: positive for the past, negative for the future. A future
/// timestamp is no longer clamped to 0 — `check_age` bounds it.
fn parse_age(timestamp: &str) -> Option<i64> {
let ts_secs = parse_epoch(timestamp)?;
let now_secs = i64::try_from(now_epoch()?).ok()?;
let ts_secs = i64::try_from(ts_secs).ok()?;
now_secs.checked_sub(ts_secs)
}
/// Current wall-clock time in whole seconds since the Unix epoch.
fn now_epoch() -> Option<u64> {
use std::time::SystemTime;
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.ok()
.map(|d| d.as_secs())
}
/// Parse an ISO 8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`) into seconds
/// since the Unix epoch. Pure: no clock read.
fn parse_epoch(timestamp: &str) -> Option<u64> {
// Expect format: 2026-02-13T14:30:00Z or similar
// Minimal parser for YYYY-MM-DDTHH:MM:SSZ
let ts = timestamp.trim().trim_end_matches('Z');
let parts: Vec<&str> = ts.split('T').collect();
if parts.len() != 2 {
return None;
}
let date_parts: Vec<u64> = parts[0].split('-').filter_map(|s| s.parse().ok()).collect();
let time_parts: Vec<u64> = parts[1].split(':').filter_map(|s| s.parse().ok()).collect();
if date_parts.len() != 3 || time_parts.len() != 3 {
return None;
}
// The pure date-arithmetic core lives in `datetime::ymd_hms_to_epoch`
// (the reverse of `epoch_to_iso`), where Kani proves it panic/overflow/
// wrap-free over the whole u64 domain — see docs/formalisation-roadmap.md.
crate::datetime::ymd_hms_to_epoch(
date_parts[0],
date_parts[1],
date_parts[2],
time_parts[0],
time_parts[1],
time_parts[2],
)
}
fn runtime_dir() -> PathBuf {
let dir = std::env::var("XDG_RUNTIME_DIR")
.unwrap_or_else(|_| format!("/run/user/{}", unsafe { libc::getuid() }));
PathBuf::from(dir)
}
pub fn default_socket_path() -> PathBuf {
runtime_dir().join("sudo-proxy.sock")
}
/// Local tunnel endpoint path for a remote host's sudo-proxy socket.
/// Caller must validate `host` with [`validate_host`] first.
pub fn remote_socket_path(host: &str) -> PathBuf {
runtime_dir().join(format!("sudo-proxy-{host}.sock"))
}
/// Reject host strings that would escape the socket directory, be passed
/// as an option flag to ssh, or carry shell metacharacters into a downstream
/// `sh -c` style call site. Strict allowlist: ASCII alphanumerics plus
/// `.`, `-`, `_`, `@`, `:`. Everything else (including the shell
/// metacharacters `;`, `|`, `&`, `$`, backtick, `(`, `)`, `<`, `>`, `*`, `?`,
/// braces, brackets, quotes, `=`, `,`, etc.) is rejected. Bare-form IPv6
/// (`::1`, `user@::1`) works because `:` is allowed; bracketed `[::1]` is
/// not.
pub fn validate_host(host: &str) -> Result<(), String> {
if host.is_empty() {
return Err("host must not be empty".into());
}
if host.starts_with('-') {
return Err("host must not start with '-'".into());
}
for c in host.chars() {
let ok = c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '@' | ':');
if !ok {
return Err(format!("host contains forbidden character: {c:?}"));
}
}
Ok(())
}
/// This machine's hostname (from `/etc/hostname`), used by [`is_local_host`] to
/// recognise a request that names the local box. Falls back to an empty string
/// (which matches nothing) if the file is unreadable, keeping the classifier
/// fail-closed toward "remote".
pub fn own_hostname() -> String {
std::fs::read_to_string("/etc/hostname")
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// True if `host` denotes the machine this proxy runs on, so a request naming
/// it must route to the *local* path rather than an SSH tunnel. This is the C9
/// normaliser (invariant G7): it folds loopback literals and the machine's own
/// hostname to "local" so a self-target cannot masquerade as remote — e.g.
/// `execute(host="127.0.0.1")` must not open an SSH-to-self tunnel that routes
/// around local policy.
///
/// Best-effort by construction: ssh-config aliases and NAT hairpin can hide a
/// self-target it cannot see. G7 does not rest on catching every alias (see
/// C10) — local unprivileged is delegated to the Bash tool and every remote
/// daemon still gates unattended execution, so an undetected self-alias routed
/// SSH-to-self still lands on a gated daemon.
///
/// `own_hostname` is injected rather than read here, so the classification is a
/// pure function of its inputs and the property test stays hermetic.
pub fn is_local_host(host: &str, own_hostname: &str) -> bool {
// Drop an optional `user@` prefix and a single trailing FQDN dot; compare
// case-insensitively.
let h = host.rsplit('@').next().unwrap_or(host);
let h = h.strip_suffix('.').unwrap_or(h);
let h_lower = h.to_ascii_lowercase();
if h_lower == "localhost" {
return true;
}
// The whole 127.0.0.0/8 block is loopback — parse it, don't string-match,
// so `127.0.0.1.evil.com` is NOT treated as local.
if let Ok(v4) = h.parse::<std::net::Ipv4Addr>() {
return v4.octets()[0] == 127;
}
if let Ok(v6) = h.parse::<std::net::Ipv6Addr>() {
return v6.is_loopback();
}
// The machine's own name — full FQDN, or a bare label matching our first
// label (so `box` matches a hostname of `box.local`). A dotted FQDN must
// match in full, so an unrelated `box.example.com` is not caught. An empty
// `own_hostname` (unreadable /etc/hostname) matches nothing.
if !own_hostname.is_empty() {
let own_lower = own_hostname.to_ascii_lowercase();
if h_lower == own_lower {
return true;
}
if !h_lower.contains('.') {
let own_label = own_lower.split('.').next().unwrap_or(&own_lower);
if !own_label.is_empty() && h_lower == own_label {
return true;
}
}
}
false
}
/// Sessions a human has granted unattended unprivileged execution, by pressing
/// `a` on an eligible daemon (barrier 2 of G7). Keyed by the request's
/// `session`, so a grant made for one client does not open the gate for the
/// others sharing the daemon (issue #8). `session` is self-declared, so this
/// separates well-behaved clients; it is not a boundary against a same-UID
/// client that claims another's session name (which could already run
/// unprivileged code directly). In memory only, never persisted.
#[derive(Default)]
pub(crate) struct UnattendedGrants(Mutex<HashSet<String>>);
impl UnattendedGrants {
pub(crate) fn is_granted(&self, session: &str) -> bool {
lock_recover(&self.0).contains(session)
}
pub(crate) fn grant(&self, session: &str) {
lock_recover(&self.0).insert(session.to_string());
}
}
/// Bounded set of recently-seen request ids, evicted by age.
pub(crate) struct SeenIds {
set: HashSet<String>,
queue: VecDeque<(String, Instant)>,
now: Box<dyn Fn() -> Instant + Send>,
}
impl SeenIds {
pub(crate) fn new<F: Fn() -> Instant + Send + 'static>(now: F) -> Self {
Self {
set: HashSet::new(),
queue: VecDeque::new(),
now: Box::new(now),
}
}
/// Atomic check-and-insert: returns `true` if `id` was new (and is now
/// remembered), `false` if it was already in the set. Combining the two
/// steps into one critical section closes the TOCTOU window between
/// concurrent connection threads.
pub(crate) fn try_insert(&mut self, id: String) -> bool {
self.evict_stale();
if self.set.contains(&id) {
return false;
}
self.set.insert(id.clone());
self.queue.push_back((id, (self.now)()));
true
}
#[cfg(test)]
pub(crate) fn contains(&self, id: &str) -> bool {
self.set.contains(id)
}
fn evict_stale(&mut self) {
let now = (self.now)();
while let Some((_, t)) = self.queue.front() {
if now.duration_since(*t) > REPLAY_RETENTION {
let (old, _) = self.queue.pop_front().unwrap();
self.set.remove(&old);
} else {
break;
}
}
}
}
/// Read SO_PEERCRED for a connected Unix socket and return the peer UID.
/// Linux-specific. Used to refuse cross-UID connections as defense-in-depth
/// — the socket file is already 0600 in a 0700 runtime dir.
fn peer_uid(stream: &UnixStream) -> io::Result<u32> {
let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
let rc = unsafe {
libc::getsockopt(
stream.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERCRED,
&mut cred as *mut _ as *mut libc::c_void,
&mut len,
)
};
if rc != 0 {
return Err(io::Error::last_os_error());
}
Ok(cred.uid)
}
/// Bind the listener, refusing to clobber an active server. If the socket
/// path is already bound and accepts connections, error out. If the file
/// exists but no peer accepts, treat it as stale and replace it.
fn bind_listener(socket_path: &Path) -> io::Result<UnixListener> {
// Tighten umask so the socket is created 0600 even before the explicit
// chmod below — closes the bind→chmod TOCTOU window.
let prev_umask = unsafe { libc::umask(0o077) };
let first = UnixListener::bind(socket_path);
unsafe { libc::umask(prev_umask) };
let listener = match first {
Ok(l) => l,
Err(e) if e.kind() == ErrorKind::AddrInUse => {
if UnixStream::connect(socket_path).is_ok() {
return Err(io::Error::new(
ErrorKind::AddrInUse,
format!(
"sudo-proxy is already running on {}",
socket_path.display()
),
));
}
fs::remove_file(socket_path)?;
let prev = unsafe { libc::umask(0o077) };
let l = UnixListener::bind(socket_path);
unsafe { libc::umask(prev) };
l?
}
Err(e) => return Err(e),
};
fs::set_permissions(socket_path, fs::Permissions::from_mode(0o600))?;
Ok(listener)
}
/// Tunable knobs for `run`. Holds the static configuration that doesn't
/// change over the daemon's lifetime; runtime objects (prompter, sink,
/// shutdown, counter) stay separate so tests can inject fakes.
pub struct ServerConfig {
pub mode: Mode,
pub pkexec_only: bool,
pub verbose: bool,
/// Log each request's command as pretty-printed JSON (just the `plan`, or a
/// legacy `pipeline`) to stderr, before validation — a debug aid for
/// inspecting what a client (e.g. the MCP server) actually sent. Independent
/// of `verbose`.
pub log_json: bool,
/// Whether this daemon *may* offer the session-scoped `a` answer at an
/// unprivileged prompt (invariant G7, first barrier). Read from the
/// `unattended_eligible` policy in `hosts.json` at startup and immutable
/// thereafter — no wire field, MCP flag, or keypress changes it. Default
/// `false` (fail-closed): every unprivileged command is prompted.
pub unattended_eligible: bool,
/// Strict "structured or nothing" mode: reject, before prompting, any
/// request with an opaque stage (a `Shell` node, or an `Exec` of a shell).
/// Read from `policy.no_shell` in `hosts.json` or `--no-shell` /
/// `--allow-shell` at startup; immutable thereafter. Default `false`.
pub no_shell: bool,
pub max_in_flight: usize,
/// Persistent audit sinks (issue #65). The stderr audit line is always
/// written; `Default` turns the file and syslog sinks off.
pub audit: AuditConfig,
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
mode: Mode::Local,
pkexec_only: false,
verbose: false,
log_json: false,
unattended_eligible: false,
no_shell: false,
max_in_flight: DEFAULT_MAX_IN_FLIGHT,
audit: AuditConfig::default(),
}
}
}
pub fn run(
socket_path: &Path,
config: ServerConfig,
prompter: Arc<dyn Prompter>,
result_sink: Arc<dyn ResultSink>,
shutdown: Arc<AtomicBool>,
in_flight: Arc<AtomicUsize>,
tty_lock: Arc<Mutex<()>>,
) -> std::io::Result<()> {
// Taken before the socket exists, so no request this instance can
// receive is dated earlier than a legitimate sender could have stamped it.
let started_epoch = now_epoch()
.ok_or_else(|| io::Error::other("system clock is before the Unix epoch"))?;
// Open the audit sinks before binding: an operator who expects an audit
// trail must not get a running daemon that silently records nothing.
let audit = Arc::new(AuditLog::open(&config.audit).map_err(|e| {
io::Error::new(e.kind(), format!("cannot open audit log: {e}"))
})?);
let listener = bind_listener(socket_path)?;
listener.set_nonblocking(true)?;
if config.verbose {
eprintln!("sudo-proxy listening on {}", socket_path.display());
eprintln!("mode: {}", config.mode.label());
if forwarded_agent_socket().is_some() {
eprintln!("ssh agent forwarding: available");
}
}
let our_uid = unsafe { libc::getuid() };
let seen_ids = Arc::new(Mutex::new(SeenIds::new(Instant::now)));
// Eligibility is a runtime-immutable config input (barrier 1). The session
// grants (barrier 2) start EMPTY and only an interactive `a` can add one —
// for the requesting `session` only, in memory only, never persisted. They
// die with the daemon, i.e. with the SSH tunnel for a remote host, so no
// grant can outlive the daemon (invariant G7).
let unattended_eligible = config.unattended_eligible;
let unattended_grants = Arc::new(UnattendedGrants::default());
loop {
if shutdown.load(Ordering::Relaxed) {
return Ok(());
}
let (mut stream, _addr) = match listener.accept() {
Ok(pair) => pair,
Err(e) if e.kind() == ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(50));
continue;
}
Err(e)
if matches!(
e.raw_os_error(),
Some(libc::EMFILE) | Some(libc::ENFILE)
) =>
{
eprintln!("accept: file-descriptor pressure ({e}); backing off");
thread::sleep(Duration::from_millis(50));
continue;
}
Err(e) => {
eprintln!("accept error: {e}");
continue;
}
};
// Backpressure: if the cap is reached, reject inline rather than
// spawn another handler thread. We don't read anything from the
// peer here — just write a fixed busy response and close. The
// socket file is 0600 in a 0700 dir so only same-UID peers reach
// this path; no need to verify SO_PEERCRED before declining.
if in_flight.load(Ordering::Relaxed) >= config.max_in_flight {
let _ = stream.set_write_timeout(Some(CONNECTION_IO_TIMEOUT));
let resp = Response::error("", "server busy: too many in-flight requests");
audit.record(&Event {
outcome: Some(Outcome::Rejected(Reject::Busy)),
detail: resp.message.clone(),
..Default::default()
});
let _ = write_response(&mut stream, &resp);
continue;
}
in_flight.fetch_add(1, Ordering::Relaxed);
let prompter = Arc::clone(&prompter);
let sink = Arc::clone(&result_sink);
let seen = Arc::clone(&seen_ids);
let tty = Arc::clone(&tty_lock);
let guard = InFlightGuard {
counter: Arc::clone(&in_flight),
};
let mode = config.mode;
let pkexec_only = config.pkexec_only;
let verbose = config.verbose;
let log_json = config.log_json;
let no_shell = config.no_shell;
let unattended_grants = Arc::clone(&unattended_grants);
let shutdown = Arc::clone(&shutdown);
let audit = Arc::clone(&audit);
thread::spawn(move || {
let _guard = guard;
handle_connection(
stream,
our_uid,
mode,
pkexec_only,
verbose,
log_json,
unattended_eligible,
no_shell,
unattended_grants,
prompter,
sink,
seen,
tty,
shutdown,
started_epoch,
&audit,
);
});
}
}
/// For `--log-json`: print just the command portion of a received request — the
/// `plan` (or, for a legacy flat request, the `pipeline`) — pretty-printed
/// (2-space indent, one element per line) to stderr. Serializing the *typed*
/// `Plan` keeps serde's on-wire key order (`op` first, then fields in
/// declaration order) rather than the alphabetical order a `Value` round-trip
/// would impose. Falls back to the whole raw line if the body is not valid JSON.
///
/// This runs *before* validation and writes to the approval terminal, so every
/// byte is passed through [`escape_for_terminal`]: a request must not be able
/// to redraw the prompt with raw escape or bidi sequences.
fn log_plan_json(line: &[u8]) {
let raw = || escape_for_terminal(String::from_utf8_lossy(line).trim_end());
let Ok(req) = serde_json::from_slice::<Request>(line) else {
eprintln!("[json] {}", raw());
return;
};
let (label, pretty) = if let Some(plan) = &req.plan {
("plan", serde_json::to_string_pretty(plan))
} else if !req.pipeline.is_empty() {
("pipeline", serde_json::to_string_pretty(&req.pipeline))
} else {
eprintln!("[json] (control request — no plan)");
return;
};
match pretty {
Ok(s) => eprintln!("[json] {label}:\n{}", escape_for_terminal(&s)),
Err(_) => eprintln!("[json] {}", raw()),
}
}
/// Make untrusted text safe to print on the approval terminal: C0 controls
/// (except newline and tab), DEL, C1 controls, and the zero-width / bidi
/// characters `has_dangerous_chars` forbids are written as `\u{…}` escapes.
fn escape_for_terminal(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
let u = c as u32;
let unsafe_char = (u < 0x20 && c != '\n' && c != '\t')
|| (0x7F..=0x9F).contains(&u)
|| matches!(u, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069);
if unsafe_char {
out.push_str(&format!("\\u{{{u:x}}}"));
} else {
out.push(c);
}
}
out
}
#[allow(clippy::too_many_arguments)]
fn handle_connection(
mut stream: UnixStream,
our_uid: u32,
mode: Mode,
pkexec_only: bool,
verbose: bool,
log_json: bool,
unattended_eligible: bool,
no_shell: bool,
unattended_grants: Arc<UnattendedGrants>,
prompter: Arc<dyn Prompter>,
result_sink: Arc<dyn ResultSink>,
seen_ids: Arc<Mutex<SeenIds>>,
tty_lock: Arc<Mutex<()>>,
shutdown: Arc<AtomicBool>,
started_epoch: u64,
audit: &AuditLog,
) {
// Audit context, filled in as the connection progresses. Every return
// below goes through `reject` or the final `record`, so each request
// leaves exactly one audit event (issue #65). The one exception is a peer
// that closes before sending a byte (e.g. a liveness probe): no request,
// nothing to record.
let mut ev = Event::default();
// The record is written *before* the reply, so the log never lags what a
// client has been told.
let reject = |stream: &mut UnixStream, ev: &Event, why: Reject, resp: Response| {
audit.record(&Event {
outcome: Some(Outcome::Rejected(why)),
detail: resp.message.clone(),
..ev.clone()
});
let _ = write_response(stream, &resp);
};
// Defense-in-depth: refuse connections from other UIDs even though the
// socket file is 0600 inside a 0700 runtime dir.
// Nothing is written back to a rejected peer.
match peer_uid(&stream) {
Ok(uid) if uid == our_uid => ev.peer_uid = Some(uid),
Ok(uid) => {
audit.record(&Event {
peer_uid: Some(uid),
outcome: Some(Outcome::Rejected(Reject::PeerUid)),
detail: Some(format!("expected uid {our_uid}")),
..Default::default()
});
return;
}
Err(e) => {
audit.record(&Event {
outcome: Some(Outcome::Rejected(Reject::PeerCred)),
detail: Some(e.to_string()),
..Default::default()
});
return;
}
}
let _ = stream.set_write_timeout(Some(CONNECTION_IO_TIMEOUT));
let line = match read_request_line(&mut stream, Instant::now() + HANDSHAKE_DEADLINE) {
Ok(b) if b.is_empty() => return,
Ok(b) => b,
Err(e) if e.kind() == ErrorKind::TimedOut => {
let resp = Response::error("", "handshake deadline exceeded");
reject(&mut stream, &ev, Reject::Handshake, resp);
return;
}
Err(e) => {
let resp = Response::error("", &format!("read error: {e}"));
reject(&mut stream, &ev, Reject::Read, resp);
return;
}
};
// JSON logging (debug aid): pretty-print just the command portion of the
// request, before validation. Gated on its own flag.
if log_json {
log_plan_json(&line);
}
let req: Request = match serde_json::from_slice(&line) {
Ok(r) => r,
Err(e) => {
let resp = Response::error("", &format!("invalid JSON: {e}"));
reject(&mut stream, &ev, Reject::InvalidJson, resp);
return;
}
};
// Unvalidated until `validate` succeeds; `audit` escapes and clips them.
ev.id = req.id.clone();
ev.session = req.session.clone();
ev.host = req.host.clone();
ev.requester = req.requester.clone();
// Validate before anything privileged can touch the request. `exec_*` and
// `prompter.prompt` accept only `&ValidatedRequest`, so this conversion is
// the single, type-enforced gate between the wire and dispatch. `req` is
// shadowed by the validated value; field reads below go through its `Deref`.
let req_id = req.id.clone();
let req = match ValidatedRequest::validate(req) {
Ok(v) => v,
Err(msg) => {
let resp = Response::error(&req_id, &msg);
reject(&mut stream, &ev, Reject::Invalid, resp);
return;
}
};
ev.privileged = Some(req.effective_privileged());
// Agent forwarding is unprivileged-only. A privileged child runs under
// sudo (which env_resets) or pkexec (which we env_clear), so the socket
// would be silently dropped — but we reject explicitly so a misconfigured
// caller fails loudly instead of being puzzled by a missing key. A plan
// that escalates via a `run-as` node counts as privileged here too.
if req.forward_agent && req.effective_privileged() {
let resp = Response::error(
&req.id,
"forward_agent is only allowed for unprivileged commands",
);
reject(&mut stream, &ev, Reject::ForwardAgent, resp);
return;
}
// Freshness is checked at handler entry, NOT after the TTY lock — a
// request must not age past MAX_REQUEST_AGE just because it queued
// behind another user's prompt.
if let Err(msg) = check_freshness(&req) {
let resp = Response::error(&req.id, &msg);
reject(&mut stream, &ev, Reject::Time, resp);
return;
}
let mut env = match sanitize_env(&req.env) {
Ok(e) => e,
Err(msg) => {
let resp = Response::error(&req.id, &msg);
reject(&mut stream, &ev, Reject::Env, resp);
return;
}
};
// Command-mode SSH skips PAM session, so the daemon (and every
// env_clear()'d child) starts with no HOME/USER/LOGNAME/PATH.
// Inject defaults from /etc/passwd so opam/git/ssh stop silently
// misbehaving — see issue #23.
crate::executor::apply_login_env_defaults(&mut env);
// Atomic check-and-insert: closes the TOCTOU window between
// contains() and insert() that exists when two threads race the
// same request id.
{
let mut ids = lock_recover(&seen_ids);
if !ids.try_insert(req.id.clone()) {
drop(ids);
let resp = Response::error(&req.id, &format!("duplicate request id: {}", req.id));
reject(&mut stream, &ev, Reject::DuplicateId, resp);
return;
}
}
// Control actions, dispatched only after every gate above (peer uid,
// validation, freshness, replay). Replay protection is per instance; a
// stop additionally must not predate this instance (issue #63), so a
// captured stop can be replayed neither here nor against a restart.
match req.action {
crate::protocol::Action::Ping => {
if verbose {
let client_ver = if req.version.is_empty() { "unknown" } else { req.version.as_str() };
eprintln!("[{}] ping from {} (client {client_ver})", req.id, req.session);
}
let mut resp = Response::ok(&req.id, vec![], b"");
resp.message = Some("pong".to_string());
ev.outcome = Some(Outcome::Ping);
audit.record(&ev);
let _ = write_response(&mut stream, &resp);
return;
}
crate::protocol::Action::Stop => {
// `time` already parsed in `check_freshness`; re-parse is total.
let gate = parse_epoch(&req.time)
.ok_or_else(|| "malformed time field".to_string())
.and_then(|t| check_not_before_start(t, started_epoch));
if let Err(msg) = gate {
let resp = Response::error(&req.id, &msg);
reject(&mut stream, &ev, Reject::StopBeforeStart, resp);
return;
}
// No approval prompt (by design): a same-UID peer can already
// SIGTERM the daemon, so the gate would add friction without
// adding a security boundary. The TTY notice keeps the human
// informed; try_lock so a pending prompt can't delay shutdown.
if let Ok(_g) = tty_lock.try_lock() {
let _ = tui::display_notice(&format!(
"sudo-proxy stopped by {}",
req.session
));
}
// Reply before flipping the flag so the client reliably reads
// the Ok response before the process exits.
let resp = Response::ok(&req.id, vec![], b"");
ev.outcome = Some(Outcome::Stop);
audit.record(&ev);
let _ = write_response(&mut stream, &resp);
shutdown.store(true, Ordering::Relaxed);
return;
}
crate::protocol::Action::Exec => {}
}
// Reject a structurally-invalid plan (e.g. redirect of a composite, a
// disallowed setenv) before prompting — the human should never be asked to
// approve something the executor cannot run. Cheap compile; the executor
// compiles again at run time.
let views = match crate::executor::plan_display(&req) {
Ok(v) => v,
Err(msg) => {
let resp = Response::error(&req.id, &format!("invalid plan: {msg}"));
reject(&mut stream, &ev, Reject::InvalidPlan, resp);
return;
}
};
// Strict no-shell policy: reject any opaque stage (a `Shell` node or an
// `Exec` of a shell) before prompting and before the unattended grant or
// `--pkexec` paths. It reads the same `opaque` bit the prompt renders, so
// what the prompt would flag is exactly what is refused.
if no_shell {
if let Some(v) = views.iter().find(|v| v.opaque) {
let prog = v.argv.first().map(String::as_str).unwrap_or("");
let resp = Response::error(
&req.id,
&format!(
"shell escape hatch rejected by policy (no_shell): stage {} runs {prog}; \
express it with structured ops (run/seq/alt/pipe/redirect/setenv/chdir/run-as)",
v.stage_id
),
);
reject(&mut stream, &ev, Reject::NoShell, resp);
return;
}
}
let effective_privileged = req.effective_privileged();
ev.command = Some(crate::tui::command_summary(&req));
if verbose {
let priv_label = if effective_privileged {
"privileged"
} else {
"unprivileged"
};
let cmd_display = crate::tui::command_summary(&req);
let client_ver = if req.version.is_empty() { "unknown" } else { req.version.as_str() };
eprintln!(
"[{}] [{}] [client {}]{} {}",
req.id,
priv_label,
client_ver,
requester_tag(&req),
cmd_display
);
}
// --pkexec hands approval to pkexec's own dialog, which shows only one
// escalated leaf's argv. That is sound only for a request that is
// privileged as a whole (every leaf escalates, so every leaf raises a
// dialog). A request that is privileged only through `run-as` nodes may
// carry unescalated leaves that pkexec never sees, so it takes the TUI
// prompt (and sudo) like any other privileged plan.
let use_pkexec = pkexec_only && mode == Mode::Local && req.privileged;
let (resp, outcome) = if effective_privileged {
if use_pkexec {
// --pkexec: pkexec itself handles auth and approval; no TTY lock.
(exec_pkexec(&req, &env, &tty_lock), Outcome::Pkexec)
} else {
// The TTY lock is shared with `executor::ForegroundGuard`, so a
// prompt blocks until any in-flight exec has released the
// foreground pgrp. Without that, the daemon would be in a
// background pgrp on /dev/tty during the prompt and reads /
// writes would EIO (PR #22 turned the prior SIGTTIN stop into
// EIO). Released before exec so the same lock can be re-taken
// by ForegroundGuard for the swap.
let prompt_result = {
let _g = lock_recover(&tty_lock);
prompter.prompt(&req, unattended_eligible, PROMPT_TIMEOUT)
};
match prompt_result {
Ok(tui::PromptResult::Approved) => {
(exec_sudo(&req, &env, &tty_lock), Outcome::Approved)
}
// The TUI never emits ApprovedAlways for privileged
// requests; treat defensively as denial if it ever
// appears here so no policy can pre-grant root.
Ok(tui::PromptResult::ApprovedAlways)
| Ok(tui::PromptResult::Denied) => (Response::denied(&req.id), Outcome::Denied),
Ok(tui::PromptResult::Timeout) => (Response::timeout(&req.id), Outcome::Timeout),
Err(e) => {
log_prompt_io_error(verbose, &req.id, &e);
(
Response::error(&req.id, &format!("prompt error: {e}")),
Outcome::PromptError,
)
}
}
}
} else if unattended_grants.is_granted(&req.session) {
// This request's session holds a grant: this daemon is eligible AND a
// human pressed `a` on an earlier request from the same `session`. Run
// unattended. Other sessions are unaffected (issue #8). The audit
// record (written below, unconditionally, with session and requester)
// is the reliable record of what ran in this no-prompt window, and
// unlike the TTY banner it never depends on the tty_lock, so an
// unprivileged command is never blocked behind an in-flight privileged
// prompt. The TTY banner stays best-effort (try_lock) for on-screen
// visibility. The grant lives only in memory and dies with the
// daemon/tunnel; it is never persisted.
if let Ok(_g) = tty_lock.try_lock() {
let _ = tui::display_banner(&req);
}
(exec_direct(&req, &env), Outcome::Unattended)
} else {
// Default unprivileged path: prompt every command. `a` is offered only
// when eligible; on an eligible daemon an `a` press approves this
// command AND grants this request's `session` in memory. When not eligible,
// `a` degrades to approve-once and grants nothing.
let prompt_result = {
let _g = lock_recover(&tty_lock);
prompter.prompt(&req, unattended_eligible, PROMPT_TIMEOUT)
};
match prompt_result {
Ok(tui::PromptResult::Approved) => (exec_direct(&req, &env), Outcome::Approved),
Ok(tui::PromptResult::ApprovedAlways) => {
// Grant the session only when eligible — never persisted, no
// hosts.json write. Barrier 1 (eligibility) gates barrier 2.
// When not eligible, `a` degrades to approve-once.
let outcome = if unattended_eligible {
unattended_grants.grant(&req.session);
Outcome::ApprovedSession
} else {