breakmancer 0.6.0

Drop a breakpoint into any shell.
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Controller side of the protocol (run on the developer's laptop).

use std::{
    io::{self, Write},
    net::{IpAddr, Ipv6Addr, SocketAddr, ToSocketAddrs},
    sync::LazyLock,
    time::Duration,
};

use clap::{Parser, ValueEnum};
use indoc::indoc;
use regex::{self, Regex};
use rustyline_async::{Readline, ReadlineEvent};
use tokio::{net::TcpListener, signal};

use crate::{
    protocol::{
        self, AuthVersion, Command, Connection, ExitBreak, OutputType, SecureMsg, TerminateCmd,
        XWingKeypair,
    },
    sigint, util,
};

#[derive(Clone, Debug)]
enum BinaryLoc {
    /// Assume breakmancer will already be on the PATH.
    SystemPath,

    /// Use a hosted version of breakmancer, downloaded as needed.
    FetchHosted,

    /// Use the provided path.
    Provided(String),
}

impl BinaryLoc {
    /// Parse `--bin` argument.
    fn parse_arg(value: &str) -> Result<BinaryLoc, String> {
        match value {
            "@PATH" => Ok(BinaryLoc::SystemPath),
            "@FETCH" => Ok(BinaryLoc::FetchHosted),
            path => match path.chars().next() {
                None => Err("Path may not be empty")?,
                Some('.' | '/') => Ok(BinaryLoc::Provided(path.to_owned())),
                _ => Err("Path must start with '.' or '/'")?,
            },
        }
    }

    /// Convert to a shell-encoded string suitable for passing to `--bin`.
    fn format_arg(&self) -> String {
        match self {
            BinaryLoc::SystemPath => String::from("'@PATH'"),
            BinaryLoc::FetchHosted => String::from("'@FETCH'"),
            BinaryLoc::Provided(path) => util::shell_escape(path),
        }
    }
}

/// Start a new session.
///
/// When the controller starts, it will give you a command to run on
/// the breakpoint host. The breakpoint end will try to open a connection
/// to the callback address, at which point a secure handshake
/// will occur and a debugging session can start.
#[derive(Parser, Debug)]
pub struct Cli {
    /// Authentication protocol.
    ///
    /// Only one supported value: `dual-pub`
    ///
    /// If not provided, you will be prompted with some questions to
    /// determine whether the available protocol will work.
    #[arg(long, value_enum)]
    auth: Option<AuthVersion>,

    /// Callback address and port.
    ///
    /// IP address or domain name that the developer's machine can be reached at,
    /// and the public-facing port to use. This must not be
    /// obstructed by NAT or firewall.
    ///
    /// IPV6 addresses must be enclosed in `[square brackets]`.
    #[arg(required = true, value_name = "HOST:PORT")]
    callback: String,

    #[arg(verbatim_doc_comment)]
    #[doc = "Binary path to use in breakpoint command line.

This only changes what the suggested invocation will be when printing \
the breakmancer command to use on the breakpoint side; you can always \
adjust it manually as needed.

- Use the special string `@PATH` to expect a binary called `breakmancer` \
  on the system path.
- Use the special string `@FETCH` to create a command line that will \
  fetch the binary on demand from a server.
- Use any path starting with `/` or `.` to specify a path to a binary on \
  the breakpoint side, e.g. `/opt/bin/breakmancer` or `./bin/breakmancer`.

If not specified, you will be asked interactively which one you prefer."]
    #[arg(long = "bin")]
    binary: Option<String>,

    /// Local port to listen on for callback.
    ///
    /// If not specified, defaults to the port from the callback
    /// option. Set this value if you use port-forwarding and have
    /// differing external and internal ports.
    #[arg(long)]
    local_port: Option<u16>,
}

/// Session params, processed from CLI args.
struct Params {
    pub callback: String,
    pub binary: BinaryLoc,
    pub listen: SocketAddr,
}

// Should work for listening on both IPv4 and IPv6.
const UNSPECIFIED_IP: IpAddr = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));

/// Ask the user if the protocol will work for them.
///
/// Return Err if can't understand answer or no options are acceptable
/// to user.
fn protocol_wizard() -> Result<AuthVersion, String> {
    println!(
        "Will you be able to view stdout from your process as it runs? \
         This is required for finding the verification string during \
         connection setup.\n"
    );
    print!("Answer [y/n]: ");
    io::stdout().flush().unwrap();
    let mut answer = String::new();
    io::stdin().read_line(&mut answer).unwrap();

    println!();
    println!("============================================================");
    println!();

    match answer.trim().to_lowercase().as_str() {
        "y" | "yes" => Ok(AuthVersion::DualPub),
        "n" | "no" => Err("This program currently cannot meet your needs. \
                 If after reviewing your answers you find they are unchanged, \
                 consider submitting a bug report describing your use-case \
                 and its constraints."
            .to_string()),
        _ => Err("Unrecognized answer".to_string()),
    }
}

/// Ask the user how they want to run the breakpoint binary.
///
/// If the answer is a Provided, it will be normalized to start with
/// '/' or '.' if needed.
///
/// Return Err if can't understand answer.
fn binary_source_wizard() -> Result<BinaryLoc, String> {
    println!("How will you be running breakmancer on the breakpoint side?");
    println!();
    println!("1) It's already installed globally or otherwise is on the PATH, i.e. `breakmancer`");
    println!("2) I'd like it to be downloaded temporarily from the maintainer's server");
    println!(
        "3) I've installed the binary in some other location (give me a \
              command line and I'll adjust it myself)"
    );
    println!();
    print!("Choice [1/2/3]: ");
    io::stdout().flush().unwrap();

    let mut answer = String::new();
    io::stdin().read_line(&mut answer).unwrap();
    println!();

    #[allow(clippy::items_after_statements)]
    fn ask_for_path() -> Result<String, String> {
        println!("Please enter the path on the breakpoint side:\n");
        let mut answer = String::new();
        io::stdin().read_line(&mut answer).unwrap();
        println!();

        let answer = answer.trim_end_matches(['\r', '\n']).to_string();
        if answer.is_empty() {
            Err("Provided path was empty".to_string())
        } else if answer.starts_with(['/', '.']) {
            Ok(answer)
        } else {
            // Put it into the expected format
            Ok(format!("./{answer}"))
        }
    }

    let answer = match answer.trim().to_lowercase().as_str() {
        "1" => Ok(BinaryLoc::SystemPath),
        "2" => Ok(BinaryLoc::FetchHosted),
        "3" => Ok(BinaryLoc::Provided(ask_for_path()?)),
        _ => Err("Unrecognized answer".to_string()),
    };

    println!("============================================================");
    println!();

    answer
}

/// Parse CLI args into session params.
///
/// If any necessary args are missing, enter guided mode.
fn parse_args(args: &Cli) -> Result<Params, String> {
    let mut tips = vec![];

    // We can't really validate the callback address beyond checking
    // if it's well-formed; it's possible that the breakpoint needs to
    // be given a domain name that won't resolve from the controller's
    // vantage point.
    let (_, callback_port) = util::parse_address(&args.callback)
        .map_err(|err| format!("Invalid callback address: {err}"))?;
    // We'll still use it if it doesn't resolve, but at least warn the user.
    match &args.callback.to_socket_addrs() {
        Ok(addrs) => {
            if addrs.len() == 0 {
                eprintln!("[WARNING] Callback host did not resolve to any IP addresses.");
            }
        }
        Err(err) => eprintln!("[WARNING] Could not resolve callback host to an IP address: {err}"),
    }
    let listen_port = args.local_port.unwrap_or(callback_port);

    let binary_maybe = args
        .binary
        .as_ref()
        .map(|choice| BinaryLoc::parse_arg(choice).map_err(|err| format!("--bin: {err}")))
        .transpose()?;

    // Now we've exhausted all of the things we can parse without
    // asking the user questions about missing params.

    if args.auth.is_none() {
        let chosen = protocol_wizard()?;
        let arg_val = chosen
            .to_possible_value()
            .expect("None of the selectable AuthVersion variants should be skipped.");
        tips.push(format!("--auth={}", arg_val.get_name()));
    }

    let binary = if let Some(choice) = binary_maybe {
        choice
    } else {
        let chosen = binary_source_wizard()?;
        tips.push(format!("--bin={}", chosen.format_arg()));
        chosen
    };

    if !tips.is_empty() {
        println!(
            "Tip: The following command line options contain your selections, \
             and will allow you to skip those questions in the future:\n\n  {}",
            tips.join(" "),
        );
        println!();
        println!("============================================================");
        println!();
    }

    Ok(Params {
        callback: args.callback.to_string(),
        binary,
        listen: SocketAddr::new(UNSPECIFIED_IP, listen_port),
    })
}

/// Print bytes as string (lossy Unicode conversion) and add a newline
/// on the end if there wasn't one already.
fn print_with_trailing_newline(data: &[u8]) {
    print!("{}", String::from_utf8_lossy(data));
    if !data.ends_with("\n".as_bytes()) {
        println!();
    }
}

const CMD_EXIT: &str = "exit";
static CMD_EXIT_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!("(?i)\\s*{CMD_EXIT}\\s*")).unwrap());

/// What the user did when we asked them for a command at the REPL.
enum ReplInput {
    /// A command the user wants to have run.
    Command(String),
    /// An interrupt of some sort, possibly signaling a desire to
    /// leave the REPL.
    Interrupted,
}

/// Prompt the user for a command at the REPL.
async fn ask_user_next_command(
    cmd_history: &mut Vec<String>,
    sigint_manager: &mut sigint::Manager,
) -> Result<ReplInput, String> {
    // Set up a new readline each time we need one, because
    // otherwise we can't use regular printlns everywhere. (It has
    // to be dropped in order to get the terminal out of raw mode
    // again.) Maybe
    // change to a persistent readline once we switch to a unified
    // logging system or something. The big downside is having to
    // maintain an external history and re-import it repeatedly.
    let (mut readline, rl_writer) = Readline::new(">> ".to_string())
        .map_err(|err| format!("Could not set up input prompt: {err}"))?;
    for cmd in &mut *cmd_history {
        readline.add_history_entry((*cmd).to_string());
    }

    // Suppress the default ^C handler we have set up.
    let suppress_sigint = sigint_manager.suppress();
    let readline_result = readline.readline().await;
    suppress_sigint.release();

    // Prevent dangling prompt
    readline.flush().unwrap();
    // Keep the writer open this long. Otherwise we get `Couldn't read
    // input: line writers closed` and the session keeps restarting.
    drop(rl_writer);

    match readline_result {
        Ok(ReadlineEvent::Line(command)) => Ok(ReplInput::Command(command)),
        Ok(ReadlineEvent::Eof | ReadlineEvent::Interrupted) => Ok(ReplInput::Interrupted),
        Err(err) => Err(format!("Couldn't read input: {err}")),
    }
}

/// Tell the breakpoint to exit (continue);
///
/// Consumes the connection, as it will stop working immediately anyhow.
async fn hangup(conn: Connection) -> Result<(), String> {
    conn.send(SecureMsg::ExitBreak(ExitBreak {}))
        .await
        .map_err(|err| format!("Could not tell breakpoint to exit: {err}"))?;
    Ok(())
}

/// What the user wants to have happen after the session ends.
enum AfterSession {
    /// Breakpoint should exit, but controller should wait for a new connection.
    Iterate,
    /// Both breakpoint and controller should exit.
    Exit,
}

/// Listen for a connection and perform one shell session.
///
/// The `cmd_history` will be updated with new commands run in this
/// session.
///
/// An Ok return means the session ended normally, without an error
/// (that is, the user asked to end the session). The Ok arm indicates
/// what should happen next.
///
/// The connection is consumed; when the function ends, the connection
/// is dropped, which cancels its tasks.
async fn run_session(
    mut conn: Connection,
    cmd_history: &mut Vec<String>,
    sigint_manager: &mut sigint::Manager,
) -> Result<AfterSession, String> {
    println!("Session ready. You can enter single-line commands. Use `{CMD_EXIT}` to exit.");

    // Each iteration of the loop is a command/response interaction on the REPL.
    let mut cmd_seq = 0;
    loop {
        // Try to get a command to run, or get an interrupt/exit
        // request. Convert these to Some vs. None.
        let command: Option<String> =
            match ask_user_next_command(cmd_history, sigint_manager).await? {
                ReplInput::Command(command) => {
                    if command.is_empty() {
                        continue; // just re-show the prompt
                    }

                    if CMD_EXIT_PATTERN.is_match(&command) {
                        // Another way of exiting the session, besides
                        // ^C/^D. We'll treat it the same way as an
                        // interrupt.
                        None
                    } else {
                        Some(command)
                    }
                }
                ReplInput::Interrupted => None,
            };

        // If there was an interrupt/exit, figure out if they meant it
        // (and return) or whether they actually want to stay in the
        // REPL.
        let Some(command) = command else {
            match ask_user_exit_choice().await {
                ExitChoice::Resume => {
                    // User maybe interrupted by accident, and just
                    // wants to go back to entering commands.
                    continue;
                }
                ExitChoice::Iterate => {
                    hangup(conn).await?;
                    return Ok(AfterSession::Iterate);
                }
                ExitChoice::Exit => {
                    hangup(conn).await?;
                    return Ok(AfterSession::Exit);
                }
            }
        };

        // We actually have a command to run! Save it in the history
        // if it's new and not space-prefixed. (ignorespace,
        // ignoredups)
        if !command.starts_with(' ') && Some(&command) != cmd_history.last() {
            cmd_history.push(command.clone());
        }
        conn.send(SecureMsg::Command(Command {
            command: command.clone(),
            seq: cmd_seq,
        }))
        .await
        .map_err(|err| format!("Could not send command to breakpoint: {err}"))?;

        // Once we send the message, we expect zero or more output
        // lines and then an outcome.

        // Whether we're currently trying to kill the remote command
        // (e.g. because it's hanging).
        let mut killing = false;
        loop {
            tokio::select! {
                // Always check the ^C first, to ensure it is handled
                // on a fast stream.
                biased;

                // We turn ^C into a termination command
                _ = signal::ctrl_c() => {
                    if !killing {
                        println!(); // get onto a new line after the ^C
                        println!("Attempting to terminate command...");
                        conn.send(
                            SecureMsg::TerminateCmd(TerminateCmd { seq: cmd_seq })
                        ).await.map_err(|err| format!("Could not send termination command to breakpoint: {err}"))?;
                        killing = true;
                    }
                },

                // But otherwise just stream the output
                msg = conn.recv() => match msg.ok_or("Error reading from breakpoint.")? {
                    SecureMsg::OutputLine(output) => {
                        if output.seq != cmd_seq {
                            return Err(format!(
                                "Received output for command #{} instead of #{}",
                                output.seq, cmd_seq
                            ));
                        }
                        let log_tag = match output.gender {
                            OutputType::Stdout => "out",
                            OutputType::Stderr => "err",
                        };
                        print!("[{log_tag}] ");
                        print_with_trailing_newline(&output.bytes);
                    }
                    SecureMsg::Finished(outcome) => {
                        if outcome.seq != cmd_seq {
                            return Err(format!(
                                "Received completion notification for command #{} instead of #{}",
                                outcome.seq, cmd_seq
                            ));
                        }
                        match outcome.exit_code {
                            Some(status) => println!("[exit: {status}]"),
                            None => println!("[exit: terminated by signal]"),
                        }
                        break;
                    }
                    wrong_variant => Err(format!(
                        "Received unexpected message type: {}",
                        Into::<&str>::into(wrong_variant)
                    ))?,
                },
            };
        }

        cmd_seq += 1;
    }
}

/// User's confirmation of how they want to exit the REPL.
enum ExitChoice {
    /// They don't actually want to exit, and want to stay in the REPL.
    Resume,
    /// See [`AfterSession::Iterate`].
    Iterate,
    /// See [`AfterSession::Exit`].
    Exit,
}

/// The user has used an interrupt while the REPL was idle -- what do they want to do next?
async fn ask_user_exit_choice() -> ExitChoice {
    println!(indoc! {
        "You've left the command shell. Do you want to resume, or exit?

         [1] Resume: Go back to issuing commands to the breakpoint.
         [2] Iterate: Exit from breakpoint on remote end, running script normally, but leave controller running with same keys.
         [3] Exit: Exit from breakpoint and controller. For additional debugging you'll need to provision the breakpoint with a new key and secret."
    });
    println!();

    let (mut readline, mut rl_writer) = Readline::new("Choice [1/2/3]: ".to_string()).unwrap();
    let choice = loop {
        match readline.readline().await {
            Ok(ReadlineEvent::Line(choice)) => match choice.as_str() {
                "1" => break ExitChoice::Resume,
                "2" => break ExitChoice::Iterate,
                "3" => break ExitChoice::Exit,
                _ => (),
            },
            Ok(ReadlineEvent::Eof) => (),
            Ok(ReadlineEvent::Interrupted) => break ExitChoice::Exit,
            Err(err) => {
                rl_writer
                    .write_all(format!("Failed to read input, exiting: {err}\n").as_bytes())
                    .unwrap();
                break ExitChoice::Exit;
            }
        }
    };
    readline.flush().unwrap(); // prevent dangling prompt
    choice
}

/// Print connection instructions for the user.
fn print_connection_instructions(controller_keypair: &XWingKeypair, params: &Params) {
    let controller_digest = protocol::controller_digest(&controller_keypair.public_key);
    let binary_base = match &params.binary {
        BinaryLoc::SystemPath => String::from("breakmancer"),
        BinaryLoc::FetchHosted => String::from(
            "curl -sS https://codeberg.org/timmc/breakmancer/raw/branch/master/fetch-and-run.sh \
             \\\n    | bash -s --",
        ),
        BinaryLoc::Provided(path) => util::shell_escape(path),
    };
    println!(
        indoc! {r#"Run the following command from the environment you want to inspect:

          {} break --auth dual-pub -c {} -i {}

        You can add --which="some location" to distinguish between breakpoints.

        (Now listening on {} for callback...)"#},
        binary_base, &params.callback, &controller_digest, &params.listen,
    );
}

pub async fn run(args: &Cli) -> Result<(), String> {
    let params = parse_args(args)?;

    // Allow override by debug keys
    let (controller_keypair, debug_breakpoint_digest) = match crate::debug_utils::get_debug_keys() {
        Some(keys) => (
            keys.controller_keypair,
            Some(protocol::breakpoint_digest(
                &keys.breakpoint_keypair.public_key,
            )),
        ),
        None => (XWingKeypair::new(), None),
    };

    // We need this signal manager for suppressing ^C during certain
    // operations.
    //
    // Except... that's not quite true. We actually *already* suppress
    // ^C at all times, because rustyline-async and tokio's ctrl_c
    // both register a signal handler, and that removes the default
    // action of ^C. So what this manager *actually* does is register
    // yet another handler that exits on ^C, and then provides a way
    // to *specifically* suppress that one handler for certain
    // operations.
    let mut sigint_manager = sigint::Manager::setup();

    let server_socket = TcpListener::bind(params.listen)
        .await
        .map_err(|err| format!("Could not listen on {}: {}", &params.listen, err))?;

    print_connection_instructions(&controller_keypair, &params);

    // Share the readline (and its history) across sessions.
    let mut command_history = Vec::<String>::new();

    loop {
        let backoff = Duration::from_secs(10);
        // New connection created (and destroyed) on every loop
        // iteration. This minimizes lingering state to reduce the
        // opportunity for vulnerabilities or other bugs (including
        // leftover in-flight messages).
        let conn_partial = match protocol::controller_open_connection(
            controller_keypair.clone(),
            &server_socket,
        )
        .await
        {
            Ok(conn) => conn,
            Err(err) => {
                println!(
                    "Failed to start controller connection; waiting {backoff:?} and trying again: {err}"
                );
                tokio::time::sleep(backoff).await;
                continue;
            }
        };

        let expected_breakpoint_digest = match debug_breakpoint_digest.as_ref() {
            None => {
                print!("Enter the verification string the breakpoint has printed to stdout: ");
                io::stdout().flush().unwrap();
                let mut expected_breakpoint_digest = String::new();
                io::stdin()
                    .read_line(&mut expected_breakpoint_digest)
                    .map_err(|err| format!("Error while reading input: {err}"))?;
                expected_breakpoint_digest
            }
            Some(debug_value) => {
                println!("[WARNING] Using debug breakpoint digest.");
                debug_value.clone()
            }
        };
        let (conn, breakpoint_intro) = match conn_partial
            .verify_breakpoint_and_complete_setup(&expected_breakpoint_digest)
            .await
        {
            Ok(conn_and_info) => conn_and_info,
            Err(err) => {
                println!("Unable to complete connection: {err}");
                continue;
            }
        };

        if let Some(which) = breakpoint_intro.which {
            println!("Breakpoint: {which}");
        }

        match run_session(conn, &mut command_history, &mut sigint_manager).await {
            Ok(AfterSession::Iterate) => {
                println!("Will wait for new connection...");
            }
            Ok(AfterSession::Exit) => {
                return Ok(());
            }
            Err(err) => {
                println!("Encountered error, restarting connection: {err}");
            }
        }
    }
}