Security (M2): a line that looks as if it holds a secret is not sent, kept or passed on
llembas-term / linux (push) Failing after 35s
llembas-term / linux (push) Failing after 35s
With AI autocomplete on, the line being typed went to the engine after a pause with no check for secrets: an exported key, a password on a database client's command line, an Authorization header, a URL with credentials. llembas_line::secret::looks_secret is a pure, table-driven matcher (no dependency), and core.looks_secret is the same rules in Lua; both are held to one table of cases, llembas/tests/secrets.txt (92 lines that must be taken for a secret, 171 ordinary commands that must not). It is applied: - before any AI autocomplete request (complete::decide -> Skip::Secret; the status says "not asked: the line looks like it holds a secret", never the line), whatever the engine itself checks; - before a command is kept in the terminal's own history (history::accepts), and a history file that holds such a line is rewritten without it on load; - to a context file: a command that looks so is replaced by a placeholder and its output is not read; a line of output or of the screen that looks so is replaced too. A secret is recognised from the first character of its value, so nothing of it is on a line that still passes while it is typed (tested a character at a time); a URL's password is caught before its `@` is typed. The README says what is recognised and what cannot be. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
10 files changed
+1875
-15
No files matched your search
@@ -84,6 +84,17 @@ What is carried over, once, at the first start of the renamed terminal:
|
||||
question opens a new one and closes the old pane, and the shell that keeps a failed
|
||||
display's last sentence on screen no longer reads from the pane.
|
||||
|
||||
- **AI autocomplete sent secrets typed on the command line.** With AI autocomplete on, any
|
||||
line you paused on was sent for a completion — also `export SOME_KEY=…`, a password given
|
||||
to a database client, an `Authorization` header, a URL with a password in it. The terminal
|
||||
now looks at every line itself, before it goes anywhere: a line that looks as if it holds
|
||||
a secret is **not sent** (the autocomplete status says "not asked: the line looks like it
|
||||
holds a secret"), is **not kept in the terminal's command history** (a history file from
|
||||
an earlier version is cleaned of such lines when it is next read), and is **left out of
|
||||
what is passed on with a question**, together with its output; a line of output or of the
|
||||
screen that looks so is left out too. The README lists exactly what is recognised and what
|
||||
cannot be (*Secrets on a command line*).
|
||||
|
||||
### Added
|
||||
|
||||
- **`Ctrl+Tab` on the ask line switches the mode**, manual ↔ auto. What stands before your
|
||||
|
||||
@@ -196,12 +196,60 @@ input line — never what.
|
||||
**AI autocomplete**, when you turned it on: the line you are typing is sent to
|
||||
`lembas complete` after a pause, when your own history has no suggestion for it — never an
|
||||
empty line, a line of fewer than three characters, a line that starts with a space, a
|
||||
private pane, or a shell on another machine. What comes back is shown as text; nothing runs
|
||||
private pane, a shell on another machine, **or a line that looks as if it holds a secret**
|
||||
(*Secrets on a command line*, below). What comes back is shown as text; nothing runs
|
||||
until you take it and press Enter. The engine is given eight seconds for an answer
|
||||
(`autocomplete_timeout_ms`), and twenty for the first one after you switch autocomplete on or
|
||||
change its model: a model on your own machine may have to be loaded. The last few attempts — the start of the line, how long it took, what came back — are
|
||||
kept in memory for *LLeMbas: autocomplete status* and go when the terminal closes.
|
||||
|
||||
### Secrets on a command line
|
||||
|
||||
A command line can hold a password, a token or a key. The terminal looks for that itself,
|
||||
before anything of a line goes anywhere, and independently of what the LLeMbas CLI checks:
|
||||
|
||||
- **AI autocomplete does not ask about such a line.** *LLeMbas: autocomplete status* then
|
||||
says "not asked: the line looks like it holds a secret" — and never the line.
|
||||
- **It is not kept in the terminal's command history**, so it is never suggested back and
|
||||
never part of anything sent later. A history file written by an earlier version is
|
||||
cleaned of such lines the next time it is read.
|
||||
- **In what is passed on with a question**, a command that looks so is replaced by
|
||||
"[a command that looked as if it held a secret was left out, with its output]" — its output
|
||||
is not read at all — and a line of another command's output, or of the screen, that looks
|
||||
so is replaced by "[a line that looked as if it held a secret was left out]".
|
||||
|
||||
What is taken for a secret, erring on the side of not sending:
|
||||
|
||||
- `NAME=value` and `name: value` where the name contains *password*, *passwd*, *passphrase*,
|
||||
*secret*, *token* or *credential* — or *key*, *auth* or *pwd*, unless the value is plainly a
|
||||
path or a number: assignments and exports, options with `=`, headers, fields of JSON,
|
||||
parts of a query string;
|
||||
- options whose value follows as a word: `--password x`, `--token x`, `--api-key x`,
|
||||
`--secret x` and their like;
|
||||
- a program's own way of taking a password: `mysql -pX` (and the other MySQL and MariaDB
|
||||
clients), `sshpass -p X`, `… login -p X`, `redis-cli -a X`, `unzip -P X`, `7z -pX`,
|
||||
`ldapsearch -w X`, `mongosh -p X`, `openssl … pass:X`, `htpasswd -b`;
|
||||
- `user:password` given to `curl -u` (and `wget`, `http`, `xh`, `aria2c`, `ab`, `svn`), and
|
||||
in a URL: `scheme://user:password@host`;
|
||||
- `Authorization:` headers, `Bearer …`, `Basic …`;
|
||||
- a line that feeds a password to a program: `… | sudo -S`, `chpasswd`, `passwd --stdin`,
|
||||
`--password-stdin`;
|
||||
- keys by their well-known beginning: `sk-…`, `ghp_…`, `github_pat_…`, `glpat-…`,
|
||||
`xoxb-…`, `AKIA…`, `-----BEGIN … PRIVATE KEY`;
|
||||
- a word of 32 or more letters and digits that looks random (small letters, capitals and
|
||||
at least two digits; a commit's hash, a UUID and a path are not taken for one).
|
||||
|
||||
Not taken for one: a value that only refers to a variable (`TOKEN=$OTHER`, `"$TOKEN"`,
|
||||
`$(command)`), and a name without a value (`export TOKEN`, `--password` alone, which asks).
|
||||
|
||||
What this cannot know, so do not rely on it for those: a password given as a plain argument
|
||||
to a program the list above does not name (`mytool alice hunter2`); a key that has only its
|
||||
shape to tell it by, while less of it stands on the line than the rule needs (a 40-character
|
||||
key typed by hand, one character at a time, is asked about until enough of it is there —
|
||||
pasted, it is there at once); and anything a program prints that does not look like one of
|
||||
the forms above. A pane marked private (`Ctrl+Shift+H`) passes nothing on at all, and a line
|
||||
that starts with a space is neither sent nor remembered.
|
||||
|
||||
## Settings
|
||||
|
||||
What you switch and choose in the terminal is remembered: AI on or off, AI autocomplete,
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! What comes back from the engine is a model's text: it is cleaned to one
|
||||
//! plain line ([`crate::suggest`]) and only ever offered, never run.
|
||||
|
||||
use crate::suggest;
|
||||
use crate::{secret, suggest};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
@@ -81,6 +81,9 @@ pub enum Skip {
|
||||
LeadingSpace,
|
||||
TooShort,
|
||||
TooLong,
|
||||
/// The line looks as if it holds a secret ([`crate::secret`]): a
|
||||
/// password, a token, a key. It is not sent anywhere.
|
||||
Secret,
|
||||
/// The terminal's own history had a suggestion: that one is shown.
|
||||
History,
|
||||
}
|
||||
@@ -100,6 +103,7 @@ impl Skip {
|
||||
Skip::LeadingSpace => "the line starts with a space",
|
||||
Skip::TooShort => "the line was shorter than 3 characters",
|
||||
Skip::TooLong => "the line was too long",
|
||||
Skip::Secret => secret::SENTENCE,
|
||||
Skip::History => "your own command history had a suggestion, and that one is shown",
|
||||
}
|
||||
}
|
||||
@@ -149,6 +153,11 @@ pub fn decide<'a>(c: &Conditions, typed: &'a str) -> Result<&'a str, Skip> {
|
||||
if typed.len() > MAX_BYTES || typed.chars().any(|c| c == '\n' || c == '\r') {
|
||||
return Err(Skip::TooLong);
|
||||
}
|
||||
// before anything else could send it: a line that looks as if it holds a
|
||||
// secret never reaches the engine, whatever else is on
|
||||
if secret::looks_secret(typed) {
|
||||
return Err(Skip::Secret);
|
||||
}
|
||||
if c.history {
|
||||
return Err(Skip::History);
|
||||
}
|
||||
@@ -616,6 +625,46 @@ mod tests {
|
||||
assert_eq!(decide(&c, "a\nb c"), Err(Skip::TooLong), "one line only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_that_holds_a_secret_is_never_asked_about() {
|
||||
let c = all_on();
|
||||
for line in [
|
||||
"export GITHUB_TOKEN=abc123",
|
||||
"mysql -u root -pS3cretWord shop",
|
||||
"curl -H 'Authorization: Bearer abc123def456' https://example.org",
|
||||
"git clone https://alice:hunter2@example.org/repo.git",
|
||||
"cli --password hunter2",
|
||||
"cli --token abc123",
|
||||
] {
|
||||
assert_eq!(decide(&c, line), Err(Skip::Secret), "{}", line);
|
||||
}
|
||||
// also when the history would have had a suggestion for it
|
||||
let with_history = Conditions { history: true, ..c };
|
||||
assert_eq!(
|
||||
decide(&with_history, "export GITHUB_TOKEN=abc123"),
|
||||
Err(Skip::Secret)
|
||||
);
|
||||
// the name alone is not the secret
|
||||
assert_eq!(
|
||||
decide(&c, "export GITHUB_TOKEN="),
|
||||
Ok("export GITHUB_TOKEN=")
|
||||
);
|
||||
assert_eq!(
|
||||
Skip::Secret.sentence(),
|
||||
"the line looks like it holds a secret"
|
||||
);
|
||||
let mut log = Log::default();
|
||||
log.skip(SystemTime::UNIX_EPOCH, Skip::Secret);
|
||||
let status = log.status(SystemTime::UNIX_EPOCH, "/bin/lembas", "", 0);
|
||||
assert!(
|
||||
status.contains("not asked")
|
||||
&& status.contains("the line looks like it holds a secret"),
|
||||
"{}",
|
||||
status
|
||||
);
|
||||
assert!(!status.contains("abc123"), "and never the line itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_keeps_a_line_from_being_asked_about() {
|
||||
let typed = "git che";
|
||||
@@ -651,6 +700,7 @@ mod tests {
|
||||
Skip::LeadingSpace,
|
||||
Skip::TooShort,
|
||||
Skip::TooLong,
|
||||
Skip::Secret,
|
||||
Skip::History,
|
||||
] {
|
||||
assert!(!skip.sentence().is_empty());
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
//! What is kept of a command: its text, how it ended, the directory it ran in
|
||||
//! and when. What is never kept: a line that starts with a space (the shells'
|
||||
//! own way of saying "do not remember this"), a line of several lines, a
|
||||
//! command that was not found, anything with a control character in it. A
|
||||
//! pane marked private records nothing, which is the caller's to see to.
|
||||
//! command that was not found, anything with a control character in it, and
|
||||
//! a line that looks as if it holds a secret ([`crate::secret`]): what is not
|
||||
//! kept is never offered back and never goes anywhere later. A pane marked
|
||||
//! private records nothing, which is the caller's to see to.
|
||||
//!
|
||||
//! The file is the person's alone (mode 0600), one command a line, appended
|
||||
//! to as commands run and rewritten smaller when it has grown.
|
||||
@@ -43,6 +45,7 @@ pub fn accepts(command: &str, exit: i32) -> bool {
|
||||
!trimmed.is_empty()
|
||||
&& trimmed.len() <= MAX_COMMAND_BYTES
|
||||
&& !trimmed.chars().any(|c| c.is_control())
|
||||
&& !crate::secret::looks_secret(trimmed)
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
@@ -215,7 +218,10 @@ fn private_options() -> std::fs::OpenOptions {
|
||||
}
|
||||
|
||||
/// Read the history file. A file that is not there is an empty history. When
|
||||
/// the file has grown to more than twice what is kept, it is rewritten.
|
||||
/// the file has grown to more than twice what is kept, it is rewritten; and
|
||||
/// so it is when it holds a line that is not kept (one that looks as if it
|
||||
/// holds a secret, written before that was looked for): such a line does not
|
||||
/// stay on disk.
|
||||
pub fn load(path: &Path, max: usize) -> std::io::Result<History> {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
Ok(text) => text,
|
||||
@@ -223,7 +229,11 @@ pub fn load(path: &Path, max: usize) -> std::io::Result<History> {
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let (history, lines) = History::parse(&text, max);
|
||||
if lines > max.saturating_mul(2) + 16 {
|
||||
// a line that is no entry: among them one `from_line` does not keep
|
||||
let unkept = text
|
||||
.lines()
|
||||
.any(|line| !line.is_empty() && !line.starts_with('#') && Entry::from_line(line).is_none());
|
||||
if unkept || lines > max.saturating_mul(2) + 16 {
|
||||
save(path, &history)?;
|
||||
}
|
||||
Ok(history)
|
||||
@@ -324,6 +334,40 @@ mod tests {
|
||||
assert!(!accepts("echo \u{1b}[31m", 0), "a control character");
|
||||
let long: String = std::iter::repeat('a').take(MAX_COMMAND_BYTES + 1).collect();
|
||||
assert!(!accepts(&long, 0));
|
||||
// a line that looks as if it holds a secret
|
||||
assert!(!accepts("export GITHUB_TOKEN=abc123", 0));
|
||||
assert!(!accepts("mysql -u root -pS3cretWord shop", 0));
|
||||
assert!(!accepts("curl -u alice:hunter2 https://example.org", 1));
|
||||
assert!(accepts("export GITHUB_TOKEN=$(gh auth token)", 0));
|
||||
assert!(accepts("mysql -u root -p shop", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_is_neither_kept_nor_left_in_the_file() {
|
||||
let mut h = History::new(10);
|
||||
assert!(h.add(entry("git status", 0)));
|
||||
assert!(!h.add(entry("export GITHUB_TOKEN=abc123", 0)));
|
||||
assert_eq!(h.len(), 1);
|
||||
assert_eq!(h.suggest("export"), None, "never offered back");
|
||||
|
||||
// a file from before this was looked for
|
||||
let dir = scratch("secret");
|
||||
let path = dir.join("history");
|
||||
let old = format!(
|
||||
"{}\n{}\n{}\n{}\n",
|
||||
HEADER,
|
||||
entry("git status", 0).to_line(),
|
||||
entry("export GITHUB_TOKEN=abc123", 0).to_line(),
|
||||
entry("ls -la", 0).to_line()
|
||||
);
|
||||
std::fs::write(&path, old).unwrap();
|
||||
let h = load(&path, 100).unwrap();
|
||||
assert_eq!(h.len(), 2, "read without it");
|
||||
assert_eq!(h.suggest("export"), None);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(!text.contains("abc123"), "and it is gone from the disk");
|
||||
assert!(text.contains("git status") && text.contains("ls -la"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
//! - [`history`]: the terminal's own history of commands it saw run.
|
||||
//! - [`mark`]: the input mark, by which LLeMbas knows a prompt is empty.
|
||||
//! - [`migrate`]: what is carried over from the terminal's earlier name.
|
||||
//! - [`secret`]: whether a command line looks as if it holds a secret - such
|
||||
//! a line is not sent for a completion and not kept in the history.
|
||||
//! - [`suggest`]: what is offered after the cursor, and how much a key takes.
|
||||
//! - [`tokens`]: the parts of a shell command line, for its colours.
|
||||
//! - [`complete`]: asking LLeMbas for the rest of a line - whether to, how the
|
||||
@@ -20,6 +22,7 @@ pub mod editor;
|
||||
pub mod history;
|
||||
pub mod mark;
|
||||
pub mod migrate;
|
||||
pub mod secret;
|
||||
pub mod suggest;
|
||||
pub mod tokens;
|
||||
pub mod zone;
|
||||
@@ -0,0 +1,762 @@
|
||||
//! Does a command line look as if it holds a secret?
|
||||
//!
|
||||
//! A line that does is not sent to LLeMbas for a completion and is not kept in
|
||||
//! the terminal's own history of commands (so it is never offered back, nor
|
||||
//! sent as context later). The rule errs on the side of not sending: a line
|
||||
//! taken for one that holds a secret costs a suggestion, the other mistake
|
||||
//! puts a password in a request.
|
||||
//!
|
||||
//! The same rules, in the same order, are `core.looks_secret` of the Lua
|
||||
//! layer, which keeps such a command out of a context file. Both are held to
|
||||
//! one table of cases, `llembas/tests/secrets.txt`: lines that must be taken
|
||||
//! for a secret, and ordinary commands that must not.
|
||||
//!
|
||||
//! What is looked for, in this order:
|
||||
//!
|
||||
//! 1. a key by its well-known beginning (`sk-`, `ghp_`, `github_pat_`,
|
||||
//! `glpat-`, `xoxb-`…, `AKIA…`, `-----BEGIN … PRIVATE KEY`);
|
||||
//! 2. a header that carries a credential (`Authorization:`, `Bearer …`,
|
||||
//! `Basic …`);
|
||||
//! 3. a URL with a name and a password (`scheme://user:pass@host`);
|
||||
//! 4. `name=value` and `name: value` where the name says what the value is
|
||||
//! (password, passwd, passphrase, secret, token, credential; key, auth and
|
||||
//! pwd too, unless the value is plainly a path or a number) - an
|
||||
//! assignment, an export, an option with `=`, a header, a field of JSON, a
|
||||
//! part of a query;
|
||||
//! 5. an option whose value is a word of its own (`--password x`,
|
||||
//! `--token x`, `--api-key x`), a program's own way of taking a password
|
||||
//! (`mysql -pX`, `sshpass -p X`, `redis-cli -a X`, `unzip -P X`…), and
|
||||
//! `user:pass` given to `curl -u` and its like;
|
||||
//! 6. a line that feeds a password to a program (`… | sudo -S`, `chpasswd`,
|
||||
//! `--password-stdin`, `openssl … pass:X`, `htpasswd -b`);
|
||||
//! 7. a long word that looks random: 32 or more of `[A-Za-z0-9+/=_-]` with a
|
||||
//! small letter, a capital and two digits in it, and at most two slashes.
|
||||
//!
|
||||
//! A value that is a reference to a variable (`$TOKEN`, `"$TOKEN"`,
|
||||
//! `$(command)`) is not a secret on the line, and neither is a name with no
|
||||
//! value (`export TOKEN`, `--password` alone, which asks).
|
||||
//!
|
||||
//! What it cannot know: a password given as a plain argument of a program it
|
||||
//! has never heard of, and a key that has only its shape to tell it by while
|
||||
//! less of it stands on the line than the rule needs.
|
||||
|
||||
/// In words, for the person: why the line was not asked about.
|
||||
pub const SENTENCE: &str = "the line looks like it holds a secret";
|
||||
|
||||
fn at(s: &[u8], i: usize) -> Option<u8> {
|
||||
s.get(i).copied()
|
||||
}
|
||||
|
||||
fn before(s: &[u8], i: usize) -> Option<u8> {
|
||||
if i == 0 {
|
||||
None
|
||||
} else {
|
||||
s.get(i - 1).copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn is_alnum(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| b.is_ascii_alphanumeric())
|
||||
}
|
||||
|
||||
fn is_digit(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn is_space(b: Option<u8>) -> bool {
|
||||
matches!(b, Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r'))
|
||||
}
|
||||
|
||||
/// `[A-Za-z0-9_-]`
|
||||
fn is_word(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
|
||||
})
|
||||
}
|
||||
|
||||
/// A byte of a name in the lowered line: `[a-z0-9_.-]`
|
||||
fn is_name(b: Option<u8>) -> bool {
|
||||
b.map_or(false, |b| {
|
||||
b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'.' || b == b'-'
|
||||
})
|
||||
}
|
||||
|
||||
fn is_quote(b: Option<u8>) -> bool {
|
||||
matches!(b, Some(b'"') | Some(b'\''))
|
||||
}
|
||||
|
||||
/// Every place `needle` starts in `hay`.
|
||||
fn find_all(hay: &[u8], needle: &[u8]) -> Vec<usize> {
|
||||
let mut found = Vec::new();
|
||||
if needle.is_empty() || hay.len() < needle.len() {
|
||||
return found;
|
||||
}
|
||||
for i in 0..=hay.len() - needle.len() {
|
||||
if &hay[i..i + needle.len()] == needle {
|
||||
found.push(i);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The beginning, and the fewest characters after it. Few where the
|
||||
/// beginning itself is unmistakable: a key typed by hand is then known for
|
||||
/// one after its first characters, before most of it stands on the line.
|
||||
const BEGINNINGS: &[(&str, usize)] = &[
|
||||
("sk-proj-", 1),
|
||||
("sk-ant-", 1),
|
||||
("sk-", 20),
|
||||
("ghp_", 8),
|
||||
("gho_", 8),
|
||||
("ghu_", 8),
|
||||
("ghs_", 8),
|
||||
("ghr_", 8),
|
||||
("github_pat_", 1),
|
||||
("glpat-", 1),
|
||||
("xoxb-", 4),
|
||||
("xoxa-", 4),
|
||||
("xoxp-", 4),
|
||||
("xoxr-", 4),
|
||||
("xoxs-", 4),
|
||||
];
|
||||
|
||||
/// 1. A key by its well-known beginning.
|
||||
fn beginning(line: &[u8]) -> bool {
|
||||
for (prefix, least) in BEGINNINGS {
|
||||
for i in find_all(line, prefix.as_bytes()) {
|
||||
if is_alnum(before(line, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
while is_word(at(line, i + prefix.len() + n)) {
|
||||
n += 1;
|
||||
}
|
||||
if n >= *least {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for prefix in ["AKIA", "ASIA"] {
|
||||
for i in find_all(line, prefix.as_bytes()) {
|
||||
if is_alnum(before(line, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
while at(line, i + prefix.len() + n)
|
||||
.map_or(false, |b| b.is_ascii_uppercase() || b.is_ascii_digit())
|
||||
{
|
||||
n += 1;
|
||||
}
|
||||
if n >= 16 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
!find_all(line, b"-----BEGIN").is_empty() && !find_all(line, b"PRIVATE KEY").is_empty()
|
||||
}
|
||||
|
||||
/// 2. A header that carries a credential.
|
||||
fn header(line: &[u8], lower: &[u8]) -> bool {
|
||||
if let Some(i) = find_all(lower, b"authorization:").first().copied() {
|
||||
let mut p = i + "authorization:".len();
|
||||
while at(lower, p) == Some(b' ') {
|
||||
p += 1;
|
||||
}
|
||||
// past the scheme, when there is one: "Bearer …", "Basic …", "token …"
|
||||
let mut q = p;
|
||||
while is_alnum(at(lower, q)) {
|
||||
q += 1;
|
||||
}
|
||||
if q > p && at(lower, q) == Some(b' ') {
|
||||
p = q + 1;
|
||||
}
|
||||
// something stands there, and it is not a variable to be filled in
|
||||
let c = at(lower, p);
|
||||
if c.is_some() && !is_space(c) && !is_quote(c) && c != Some(b'$') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for i in find_all(lower, b"bearer ") {
|
||||
if is_alnum(before(lower, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
// [A-Za-z0-9._~+/=-]
|
||||
while at(line, i + 7 + n).map_or(false, |b| {
|
||||
b.is_ascii_alphanumeric()
|
||||
|| b == b'_'
|
||||
|| b == b'-'
|
||||
|| b == b'.'
|
||||
|| b == b'~'
|
||||
|| b == b'+'
|
||||
|| b == b'/'
|
||||
|| b == b'='
|
||||
}) {
|
||||
n += 1;
|
||||
}
|
||||
if n >= 8 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for i in find_all(lower, b"basic ") {
|
||||
if is_alnum(before(lower, i)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 0;
|
||||
let mut marked = false;
|
||||
// [A-Za-z0-9+/=]
|
||||
while let Some(b) = at(line, i + 6 + n) {
|
||||
if !(b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=') {
|
||||
break;
|
||||
}
|
||||
marked = marked || b.is_ascii_digit() || b == b'=';
|
||||
n += 1;
|
||||
}
|
||||
if n >= 12 && marked {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 3. A URL with a name and a password in it: `scheme://user:pass@host`.
|
||||
/// And one still being typed, where the `@` has not come yet:
|
||||
/// `scheme://user:pa` - told from `host:port` by what follows the colon not
|
||||
/// being a number (an image reference, `docker://name:tag`, is the one thing
|
||||
/// let through).
|
||||
fn url(line: &[u8], lower: &[u8]) -> bool {
|
||||
for i in find_all(line, b"://") {
|
||||
let start = i + 3;
|
||||
let mut end = start;
|
||||
// to the end of the authority: / ? # white space or a quote
|
||||
while let Some(b) = at(line, end) {
|
||||
if is_space(Some(b)) || b == b'/' || b == b'?' || b == b'#' || is_quote(Some(b)) {
|
||||
break;
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
let authority = &line[start..end];
|
||||
let colon = match authority.iter().position(|b| *b == b':') {
|
||||
Some(k) => k,
|
||||
None => continue,
|
||||
};
|
||||
match authority.iter().rposition(|b| *b == b'@') {
|
||||
Some(at_sign) => {
|
||||
if colon >= 1 && colon + 2 <= at_sign && authority[colon + 1] != b'$' {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if colon == 0 || colon + 1 >= authority.len() || authority[0] == b'[' {
|
||||
continue;
|
||||
}
|
||||
let mut s = i;
|
||||
while s > 0 && is_name(at(lower, s - 1)) {
|
||||
s -= 1;
|
||||
}
|
||||
let scheme = &lower[s..i];
|
||||
let rest = &authority[colon + 1..];
|
||||
if scheme != b"docker"
|
||||
&& scheme != b"oci"
|
||||
&& rest[0] != b'$'
|
||||
&& rest.iter().any(|b| !b.is_ascii_digit())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
/// The name says outright that the value is a secret.
|
||||
Strong,
|
||||
/// It may be one (a key, an auth, a pwd): a value that is plainly a path
|
||||
/// or a number is let through.
|
||||
Weak,
|
||||
}
|
||||
|
||||
const STRONG_NAMES: &[&str] = &[
|
||||
"password",
|
||||
"passwd",
|
||||
"passphrase",
|
||||
"secret",
|
||||
"token",
|
||||
"credential",
|
||||
];
|
||||
|
||||
fn has_part(name: &str, part: &str) -> bool {
|
||||
name.split(|c: char| c == '-' || c == '_' || c == '.')
|
||||
.any(|piece| piece == part)
|
||||
}
|
||||
|
||||
/// Is this name (lowered) one a secret is kept under? `sep` is `=` for
|
||||
/// `name=value` and `:` for `name: value`.
|
||||
fn name_kind(run: &str, sep: u8) -> Option<Kind> {
|
||||
let option = run.starts_with('-');
|
||||
let name = run.trim_start_matches(|c: char| c == '-' || c == '.');
|
||||
if name.is_empty() || name == "pwd" || name == "oldpwd" {
|
||||
return None;
|
||||
}
|
||||
if option && name.starts_with("no-") {
|
||||
return None;
|
||||
}
|
||||
if STRONG_NAMES.iter().any(|word| name.contains(*word)) {
|
||||
return Some(Kind::Strong);
|
||||
}
|
||||
let weak = if sep == b':' {
|
||||
(name.contains("key") && name.contains("api")) || has_part(name, "auth")
|
||||
} else if option {
|
||||
has_part(name, "key")
|
||||
|| has_part(name, "apikey")
|
||||
|| has_part(name, "auth")
|
||||
|| has_part(name, "pwd")
|
||||
|| has_part(name, "pass")
|
||||
} else {
|
||||
name.contains("key") || name.contains("auth") || name.contains("pwd")
|
||||
};
|
||||
if weak {
|
||||
Some(Kind::Weak)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Does a value stand at `v` that could be the secret itself? Not nothing,
|
||||
/// not a reference to a variable (`$NAME`, outside single quotes), and for a
|
||||
/// weak name not a path and not a number.
|
||||
fn value_at(line: &[u8], v: usize, kind: Kind) -> bool {
|
||||
let mut v = v;
|
||||
let mut quote = None;
|
||||
if is_quote(at(line, v)) {
|
||||
quote = at(line, v);
|
||||
v += 1;
|
||||
}
|
||||
let c = match at(line, v) {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
if is_space(Some(c)) || is_quote(Some(c)) {
|
||||
return false;
|
||||
}
|
||||
if c == b'$' && quote != Some(b'\'') {
|
||||
return false;
|
||||
}
|
||||
if kind == Kind::Weak {
|
||||
let d = at(line, v + 1);
|
||||
if c == b'/' || c == b'~' || (c == b'.' && (d == Some(b'/') || d == Some(b'.'))) {
|
||||
return false;
|
||||
}
|
||||
// a number is a column or a count, not a key
|
||||
let mut e = v;
|
||||
while at(line, e).map_or(false, |b| b.is_ascii_digit() || b == b',' || b == b'.') {
|
||||
e += 1;
|
||||
}
|
||||
let after = at(line, e);
|
||||
if e > v && (after.is_none() || is_space(after) || is_quote(after)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 4. `name=value` and `name: value`, wherever they stand.
|
||||
fn assignment(line: &[u8], lower: &[u8]) -> bool {
|
||||
let n = lower.len();
|
||||
let mut i = 0;
|
||||
while i < n {
|
||||
if !is_name(at(lower, i)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// the run of the name: i..=j
|
||||
let mut j = i;
|
||||
while is_name(at(lower, j + 1)) {
|
||||
j += 1;
|
||||
}
|
||||
let mut p = j + 1;
|
||||
let quoted = is_quote(at(lower, p));
|
||||
if quoted {
|
||||
p += 1;
|
||||
}
|
||||
let sep = at(lower, p);
|
||||
if sep == Some(b'=') || sep == Some(b':') {
|
||||
let sep = sep.unwrap_or(b'=');
|
||||
let run = std::str::from_utf8(&lower[i..=j]).unwrap_or("");
|
||||
if let Some(kind) = name_kind(run, sep) {
|
||||
let mut v = p + 1;
|
||||
let mut ok = true;
|
||||
if sep == b':' {
|
||||
let spaced = at(lower, v) == Some(b' ');
|
||||
if spaced {
|
||||
v += 1;
|
||||
}
|
||||
// name:value with nothing between is a header only when
|
||||
// it looks like one; host:port and image:tag are far
|
||||
// more common
|
||||
ok = (spaced || quoted || run.starts_with("x-")) && at(lower, v) != Some(b'/');
|
||||
}
|
||||
if ok && value_at(line, v, kind) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn unquoted(token: &str) -> &str {
|
||||
let first = match token.as_bytes().first().copied() {
|
||||
Some(q) if q == b'"' || q == b'\'' => q,
|
||||
_ => return token,
|
||||
};
|
||||
let rest = &token[1..];
|
||||
if rest.as_bytes().last().copied() == Some(first) {
|
||||
&rest[..rest.len() - 1]
|
||||
} else {
|
||||
rest
|
||||
}
|
||||
}
|
||||
|
||||
/// `user:pass`, as curl's `-u` takes it.
|
||||
fn is_user_pass(value: &str) -> bool {
|
||||
let v = unquoted(value);
|
||||
let colon = match v.find(':') {
|
||||
Some(colon) => colon,
|
||||
None => return false,
|
||||
};
|
||||
if colon == 0 || colon + 1 >= v.len() || v.as_bytes()[colon + 1] == b'$' {
|
||||
return false;
|
||||
}
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
!(digits(&v[..colon]) && digits(&v[colon + 1..]))
|
||||
}
|
||||
|
||||
const STRONG_PARTS: &[&str] = &[
|
||||
"password",
|
||||
"passwd",
|
||||
"passphrase",
|
||||
"pass",
|
||||
"token",
|
||||
"secret",
|
||||
"apikey",
|
||||
"credential",
|
||||
"credentials",
|
||||
];
|
||||
|
||||
/// The programs, the option, whether the value may be attached (`-pVALUE`)
|
||||
/// and whether it may stand apart (`-p VALUE`).
|
||||
const CLIENTS: &[(&[&str], &str, bool, bool)] = &[
|
||||
(
|
||||
&[
|
||||
"mysql",
|
||||
"mariadb",
|
||||
"mysqldump",
|
||||
"mariadb-dump",
|
||||
"mysqladmin",
|
||||
"mariadb-admin",
|
||||
"mysqlimport",
|
||||
"mysqlcheck",
|
||||
"mysqlsh",
|
||||
"mycli",
|
||||
],
|
||||
"-p",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
(&["sshpass"], "-p", true, true),
|
||||
(
|
||||
&["7z", "7za", "7zr", "7zz", "rar", "unrar"],
|
||||
"-p",
|
||||
true,
|
||||
false,
|
||||
),
|
||||
(&["zip", "unzip"], "-P", true, true),
|
||||
(
|
||||
&["redis-cli", "valkey-cli", "redis-benchmark"],
|
||||
"-a",
|
||||
false,
|
||||
true,
|
||||
),
|
||||
(
|
||||
&[
|
||||
"ldapsearch",
|
||||
"ldapmodify",
|
||||
"ldapadd",
|
||||
"ldapdelete",
|
||||
"ldapwhoami",
|
||||
"ldappasswd",
|
||||
],
|
||||
"-w",
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(
|
||||
&[
|
||||
"mongo",
|
||||
"mongosh",
|
||||
"mongodump",
|
||||
"mongorestore",
|
||||
"mongoexport",
|
||||
"mongoimport",
|
||||
],
|
||||
"-p",
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(&["mosquitto_pub", "mosquitto_sub"], "-P", false, true),
|
||||
(&["login"], "-p", true, true),
|
||||
];
|
||||
|
||||
const USER_PASS_CLIENTS: &[&str] = &["curl", "wget", "http", "https", "xh", "aria2c", "ab", "svn"];
|
||||
const USER_PASS_OPTIONS: &[&str] = &["-u", "--user", "--proxy-user", "-U", "-A", "-a"];
|
||||
|
||||
/// 5 and 6. Options whose value is a word of its own, a program's own way of
|
||||
/// taking a password, and lines that feed one to a program.
|
||||
fn words(line: &str, lower: &str) -> bool {
|
||||
let tokens: Vec<&str> = line.split_ascii_whitespace().collect();
|
||||
let lowered: Vec<&str> = lower.split_ascii_whitespace().collect();
|
||||
let has = |name: &str| {
|
||||
lowered
|
||||
.iter()
|
||||
.any(|token| unquoted(token).rsplit('/').next() == Some(name))
|
||||
};
|
||||
for (i, token) in lowered.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if token == "--password-stdin" {
|
||||
return true;
|
||||
}
|
||||
if token.starts_with("--") && !token.contains('=') && !token[2..].starts_with("no-") {
|
||||
let mut kind: Option<Kind> = None;
|
||||
let mut parts = 0;
|
||||
let mut key = false;
|
||||
for piece in token[2..].split(|c: char| c == '-' || c == '_') {
|
||||
if piece.is_empty() {
|
||||
continue;
|
||||
}
|
||||
parts += 1;
|
||||
if STRONG_PARTS.contains(&piece) {
|
||||
kind = Some(Kind::Strong);
|
||||
} else if piece == "auth" || piece == "pwd" {
|
||||
kind = kind.or(Some(Kind::Weak));
|
||||
} else if piece == "key" {
|
||||
key = true;
|
||||
}
|
||||
}
|
||||
if key && parts >= 2 {
|
||||
kind = kind.or(Some(Kind::Weak));
|
||||
}
|
||||
if let (Some(kind), Some(value)) = (kind, tokens.get(i + 1)) {
|
||||
if !value.starts_with('-') && value_at(value.as_bytes(), 0, kind) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// openssl's -passin pass:…
|
||||
if let Some(plain) = tokens.get(i).map(|token| unquoted(token)) {
|
||||
if plain.len() > 5 && plain.starts_with("pass:") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (programs, flag, attached, apart) in CLIENTS {
|
||||
if !programs.iter().any(|program| has(*program)) {
|
||||
continue;
|
||||
}
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if token == *flag {
|
||||
if let Some(value) = tokens.get(i + 1) {
|
||||
if *apart
|
||||
&& !value.starts_with('-')
|
||||
&& value_at(value.as_bytes(), 0, Kind::Strong)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if *attached && token.starts_with(*flag) && !token.starts_with("--") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if USER_PASS_CLIENTS.iter().any(|program| has(*program)) {
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
let token: &str = token;
|
||||
if USER_PASS_OPTIONS.contains(&token) {
|
||||
if tokens.get(i + 1).map_or(false, |value| is_user_pass(value)) {
|
||||
return true;
|
||||
}
|
||||
} else if let Some(rest) = token.strip_prefix("--user=") {
|
||||
if is_user_pass(rest) {
|
||||
return true;
|
||||
}
|
||||
} else if let Some(rest) = token.strip_prefix("--proxy-user=") {
|
||||
if is_user_pass(rest) {
|
||||
return true;
|
||||
}
|
||||
} else if token.len() > 2 && token.starts_with("-u") && is_user_pass(&token[2..]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if has("chpasswd") {
|
||||
return true;
|
||||
}
|
||||
let dash_s = tokens.iter().any(|token| *token == "-S");
|
||||
let stdin = tokens.iter().any(|token| *token == "--stdin");
|
||||
let flag_b = tokens.iter().any(|token| {
|
||||
let bytes = token.as_bytes();
|
||||
bytes.len() >= 2
|
||||
&& bytes[0] == b'-'
|
||||
&& bytes[1..].iter().all(|b| b.is_ascii_alphabetic())
|
||||
&& bytes[1..].contains(&b'b')
|
||||
});
|
||||
(has("sudo") && dash_s) || (has("passwd") && stdin) || (has("htpasswd") && flag_b)
|
||||
}
|
||||
|
||||
/// 7. A long word that looks random.
|
||||
fn random(line: &[u8]) -> bool {
|
||||
let in_run = |b: u8| {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'+' || b == b'/' || b == b'='
|
||||
};
|
||||
let mut i = 0;
|
||||
while i < line.len() {
|
||||
if !in_run(line[i]) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i;
|
||||
let mut small = false;
|
||||
let mut capital = false;
|
||||
let mut digits = 0usize;
|
||||
let mut slashes = 0usize;
|
||||
while j < line.len() && in_run(line[j]) {
|
||||
let b = line[j];
|
||||
if b.is_ascii_lowercase() {
|
||||
small = true;
|
||||
} else if b.is_ascii_uppercase() {
|
||||
capital = true;
|
||||
} else if b.is_ascii_digit() {
|
||||
digits += 1;
|
||||
} else if b == b'/' {
|
||||
slashes += 1;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 32 && small && capital && digits >= 2 && slashes <= 2 {
|
||||
return true;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Does this command line look as if it holds a secret?
|
||||
pub fn looks_secret(line: &str) -> bool {
|
||||
if line.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let lower = line.to_ascii_lowercase();
|
||||
beginning(line.as_bytes())
|
||||
|| header(line.as_bytes(), lower.as_bytes())
|
||||
|| url(line.as_bytes(), lower.as_bytes())
|
||||
|| assignment(line.as_bytes(), lower.as_bytes())
|
||||
|| words(line, &lower)
|
||||
|| random(line.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The table both implementations are held to: `+ ` before a line that
|
||||
/// holds a secret, `- ` before one that does not.
|
||||
const TABLE: &str = include_str!("../../tests/secrets.txt");
|
||||
|
||||
#[test]
|
||||
fn the_table_of_cases() {
|
||||
let mut held = 0;
|
||||
let mut ordinary = 0;
|
||||
let mut wrong = Vec::new();
|
||||
for line in TABLE.lines() {
|
||||
let (want, text) = if let Some(text) = line.strip_prefix("+ ") {
|
||||
(true, text)
|
||||
} else if let Some(text) = line.strip_prefix("- ") {
|
||||
(false, text)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if want {
|
||||
held += 1;
|
||||
} else {
|
||||
ordinary += 1;
|
||||
}
|
||||
if looks_secret(text) != want {
|
||||
wrong.push(format!(
|
||||
"{} {}",
|
||||
if want {
|
||||
"missed:"
|
||||
} else {
|
||||
"taken for a secret:"
|
||||
},
|
||||
text
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
held >= 80 && ordinary >= 150,
|
||||
"the table was read: {} and {} cases",
|
||||
held,
|
||||
ordinary
|
||||
);
|
||||
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_is_known_from_its_first_character() {
|
||||
// What is typed, a character at a time. The line is asked about at
|
||||
// every pause, so from the first character of the value on it must
|
||||
// be taken for a secret: nothing of the value may be on a line that
|
||||
// still passes. Each case: the line, and where its value starts.
|
||||
for (line, value_from) in [
|
||||
("export GITHUB_TOKEN=abc123", 20),
|
||||
("mysql -u root -pS3cret", 16),
|
||||
("curl -u alice:hunter2 https://example.org", 14),
|
||||
("curl -H \"Authorization: Bearer abc123def\"", 31),
|
||||
("cli --password hunter2", 15),
|
||||
("psql postgres://app:hunter2@db/shop", 20),
|
||||
("curl \"https://example.org/api?access_token=abc123\"", 43),
|
||||
] {
|
||||
for end in (value_from + 1)..=line.len() {
|
||||
let typed = &line[..end];
|
||||
assert!(looks_secret(typed), "typed so far: {:?}", typed);
|
||||
}
|
||||
}
|
||||
// and before the value there is nothing to keep back
|
||||
for typed in [
|
||||
"export GITHUB_TOKEN=",
|
||||
"export GITHUB_TOK",
|
||||
"mysql -u root -p",
|
||||
"curl -u alice",
|
||||
"curl -u alice:",
|
||||
"cli --password ",
|
||||
"psql postgres://app",
|
||||
"psql postgres://app:",
|
||||
"curl http://localhost:80",
|
||||
] {
|
||||
assert!(!looks_secret(typed), "typed so far: {:?}", typed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_is_not_ascii_is_only_text() {
|
||||
assert!(!looks_secret("echo žltý kôň"));
|
||||
assert!(!looks_secret("echo \u{4e2d}\u{6587}=\u{4e2d}"));
|
||||
assert!(looks_secret("export HESLO_TOKEN=žltý"));
|
||||
assert!(!looks_secret(""));
|
||||
assert!(!looks_secret(" "));
|
||||
}
|
||||
}
|
||||
@@ -982,6 +982,575 @@ function M.cwd_from(value)
|
||||
return nil
|
||||
end
|
||||
|
||||
----------------------------------------------------------------------------
|
||||
-- Does a command line look as if it holds a secret?
|
||||
--
|
||||
-- The same rules, in the same order, as `llembas_line::secret` (Rust), which
|
||||
-- keeps such a line from the AI's autocomplete and from the terminal's own
|
||||
-- command history; here they keep it out of a context file. Both are held to
|
||||
-- one table of cases, llembas/tests/secrets.txt. A line that looks so is
|
||||
-- never sent anywhere: when in doubt, it does.
|
||||
|
||||
local function is_alnum(b)
|
||||
return b ~= nil and ((b >= 48 and b <= 57) or (b >= 65 and b <= 90) or (b >= 97 and b <= 122))
|
||||
end
|
||||
|
||||
local function is_digit(b)
|
||||
return b ~= nil and b >= 48 and b <= 57
|
||||
end
|
||||
|
||||
local function is_space(b)
|
||||
return b == 32 or b == 9 or b == 10 or b == 13
|
||||
end
|
||||
|
||||
-- [A-Za-z0-9_-]
|
||||
local function is_word(b)
|
||||
return is_alnum(b) or b == 95 or b == 45
|
||||
end
|
||||
|
||||
-- a byte of a name in the lowered line: [a-z0-9_.-]
|
||||
local function is_name(b)
|
||||
return b ~= nil and ((b >= 97 and b <= 122) or (b >= 48 and b <= 57) or b == 95 or b == 46 or b == 45)
|
||||
end
|
||||
|
||||
local function is_quote(b)
|
||||
return b == 34 or b == 39
|
||||
end
|
||||
|
||||
-- { the beginning, the fewest characters after it }. Few where the
|
||||
-- beginning itself is unmistakable: a key typed by hand is then known for
|
||||
-- one after its first characters, before most of it stands on the line.
|
||||
local SECRET_BEGINNINGS = {
|
||||
{ 'sk-proj-', 1 },
|
||||
{ 'sk-ant-', 1 },
|
||||
{ 'sk-', 20 },
|
||||
{ 'ghp_', 8 },
|
||||
{ 'gho_', 8 },
|
||||
{ 'ghu_', 8 },
|
||||
{ 'ghs_', 8 },
|
||||
{ 'ghr_', 8 },
|
||||
{ 'github_pat_', 1 },
|
||||
{ 'glpat-', 1 },
|
||||
{ 'xoxb-', 4 },
|
||||
{ 'xoxa-', 4 },
|
||||
{ 'xoxp-', 4 },
|
||||
{ 'xoxr-', 4 },
|
||||
{ 'xoxs-', 4 },
|
||||
}
|
||||
|
||||
-- 1. A key by its well-known beginning.
|
||||
local function secret_beginning(line)
|
||||
for _, known in ipairs(SECRET_BEGINNINGS) do
|
||||
local from = 1
|
||||
while true do
|
||||
local i, j = line:find(known[1], from, true)
|
||||
if not i then
|
||||
break
|
||||
end
|
||||
if not is_alnum(line:byte(i - 1)) then
|
||||
local n = 0
|
||||
while is_word(line:byte(j + 1 + n)) do
|
||||
n = n + 1
|
||||
end
|
||||
if n >= known[2] then
|
||||
return true
|
||||
end
|
||||
end
|
||||
from = j + 1
|
||||
end
|
||||
end
|
||||
for _, prefix in ipairs { 'AKIA', 'ASIA' } do
|
||||
local from = 1
|
||||
while true do
|
||||
local i, j = line:find(prefix, from, true)
|
||||
if not i then
|
||||
break
|
||||
end
|
||||
if not is_alnum(line:byte(i - 1)) then
|
||||
local n = 0
|
||||
while true do
|
||||
local b = line:byte(j + 1 + n)
|
||||
if b ~= nil and ((b >= 65 and b <= 90) or is_digit(b)) then
|
||||
n = n + 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if n >= 16 then
|
||||
return true
|
||||
end
|
||||
end
|
||||
from = j + 1
|
||||
end
|
||||
end
|
||||
return line:find('-----BEGIN', 1, true) ~= nil and line:find('PRIVATE KEY', 1, true) ~= nil
|
||||
end
|
||||
|
||||
-- 2. A header that carries a credential.
|
||||
local function secret_header(line, lower)
|
||||
local i, j = lower:find('authorization:', 1, true)
|
||||
if i then
|
||||
local p = j + 1
|
||||
while lower:byte(p) == 32 do
|
||||
p = p + 1
|
||||
end
|
||||
-- past the scheme, when there is one: "Bearer …", "Basic …", "token …"
|
||||
local q = p
|
||||
while is_alnum(lower:byte(q)) do
|
||||
q = q + 1
|
||||
end
|
||||
if q > p and lower:byte(q) == 32 then
|
||||
p = q + 1
|
||||
end
|
||||
local c = lower:byte(p)
|
||||
-- something stands there, and it is not a variable to be filled in
|
||||
if c ~= nil and not is_space(c) and not is_quote(c) and c ~= 36 then
|
||||
return true
|
||||
end
|
||||
end
|
||||
local from = 1
|
||||
while true do
|
||||
i, j = lower:find('bearer ', from, true)
|
||||
if not i then
|
||||
break
|
||||
end
|
||||
if not is_alnum(lower:byte(i - 1)) then
|
||||
local n = 0
|
||||
while true do
|
||||
local b = line:byte(j + 1 + n)
|
||||
-- [A-Za-z0-9._~+/=-]
|
||||
if is_word(b) or b == 46 or b == 126 or b == 43 or b == 47 or b == 61 then
|
||||
n = n + 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if n >= 8 then
|
||||
return true
|
||||
end
|
||||
end
|
||||
from = j + 1
|
||||
end
|
||||
from = 1
|
||||
while true do
|
||||
i, j = lower:find('basic ', from, true)
|
||||
if not i then
|
||||
break
|
||||
end
|
||||
if not is_alnum(lower:byte(i - 1)) then
|
||||
local n, marked = 0, false
|
||||
while true do
|
||||
local b = line:byte(j + 1 + n)
|
||||
-- [A-Za-z0-9+/=]
|
||||
if is_alnum(b) or b == 43 or b == 47 or b == 61 then
|
||||
n = n + 1
|
||||
marked = marked or is_digit(b) or b == 61
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
if n >= 12 and marked then
|
||||
return true
|
||||
end
|
||||
end
|
||||
from = j + 1
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- 3. A URL with a name and a password in it: scheme://user:pass@host. And
|
||||
-- one still being typed, where the `@` has not come yet: scheme://user:pa -
|
||||
-- told from host:port by what follows the colon not being a number (an
|
||||
-- image reference, docker://name:tag, is the one thing let through).
|
||||
local function secret_url(line, lower)
|
||||
local from = 1
|
||||
while true do
|
||||
local i, j = line:find('://', from, true)
|
||||
if not i then
|
||||
return false
|
||||
end
|
||||
local e = j + 1
|
||||
while true do
|
||||
local b = line:byte(e)
|
||||
-- to the end of the authority: / ? # white space or a quote
|
||||
if b == nil or is_space(b) or b == 47 or b == 63 or b == 35 or is_quote(b) then
|
||||
break
|
||||
end
|
||||
e = e + 1
|
||||
end
|
||||
local authority = line:sub(j + 1, e - 1)
|
||||
local at
|
||||
for k = #authority, 1, -1 do
|
||||
if authority:byte(k) == 64 then
|
||||
at = k
|
||||
break
|
||||
end
|
||||
end
|
||||
local colon = authority:find(':', 1, true)
|
||||
if at then
|
||||
if colon and colon > 1 and colon + 1 <= at - 1 and authority:byte(colon + 1) ~= 36 then
|
||||
return true
|
||||
end
|
||||
elseif colon and colon > 1 and colon < #authority and authority:byte(1) ~= 91 then
|
||||
local s = i
|
||||
while s > 1 and is_name(lower:byte(s - 1)) do
|
||||
s = s - 1
|
||||
end
|
||||
local scheme = lower:sub(s, i - 1)
|
||||
local rest = authority:sub(colon + 1)
|
||||
if scheme ~= 'docker' and scheme ~= 'oci' and rest:byte(1) ~= 36 and rest:find('%D') then
|
||||
return true
|
||||
end
|
||||
end
|
||||
from = j + 1
|
||||
end
|
||||
end
|
||||
|
||||
local STRONG_NAMES = { 'password', 'passwd', 'passphrase', 'secret', 'token', 'credential' }
|
||||
|
||||
local function has_part(name, part)
|
||||
for piece in name:gmatch('[^%-_%.]+') do
|
||||
if piece == part then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- Is this name (lowered) one a secret is kept under? 'strong': it says so
|
||||
-- outright. 'weak': it may (a key, an auth, a pwd), and then a value that
|
||||
-- is plainly a path is let through. nil: no.
|
||||
-- sep: 61 for name=value, 58 for name: value
|
||||
local function secret_name(run, sep)
|
||||
local option = run:byte(1) == 45
|
||||
local name = run:gsub('^[%-%.]+', '')
|
||||
if name == '' or name == 'pwd' or name == 'oldpwd' then
|
||||
return nil
|
||||
end
|
||||
if option and name:sub(1, 3) == 'no-' then
|
||||
return nil
|
||||
end
|
||||
for _, word in ipairs(STRONG_NAMES) do
|
||||
if name:find(word, 1, true) then
|
||||
return 'strong'
|
||||
end
|
||||
end
|
||||
local weak
|
||||
if sep == 58 then
|
||||
weak = (name:find('key', 1, true) ~= nil and name:find('api', 1, true) ~= nil) or has_part(name, 'auth')
|
||||
elseif option then
|
||||
weak = has_part(name, 'key')
|
||||
or has_part(name, 'apikey')
|
||||
or has_part(name, 'auth')
|
||||
or has_part(name, 'pwd')
|
||||
or has_part(name, 'pass')
|
||||
else
|
||||
weak = name:find('key', 1, true) ~= nil or name:find('auth', 1, true) ~= nil or name:find('pwd', 1, true) ~= nil
|
||||
end
|
||||
return weak and 'weak' or nil
|
||||
end
|
||||
|
||||
-- Does a value stand at position v of the line that could be the secret
|
||||
-- itself? Not nothing, not a reference to a variable ($NAME, outside single
|
||||
-- quotes), and for a 'weak' name not a path.
|
||||
local function secret_value(line, v, kind)
|
||||
local quote = line:byte(v)
|
||||
if is_quote(quote) then
|
||||
v = v + 1
|
||||
else
|
||||
quote = nil
|
||||
end
|
||||
local c = line:byte(v)
|
||||
if c == nil or is_space(c) or is_quote(c) then
|
||||
return false
|
||||
end
|
||||
if c == 36 and quote ~= 39 then
|
||||
return false
|
||||
end
|
||||
if kind == 'weak' then
|
||||
local d = line:byte(v + 1)
|
||||
if c == 47 or c == 126 or (c == 46 and (d == 47 or d == 46)) then
|
||||
return false
|
||||
end
|
||||
-- a number is a column or a count, not a key
|
||||
local e = v
|
||||
while is_digit(line:byte(e)) or line:byte(e) == 44 or line:byte(e) == 46 do
|
||||
e = e + 1
|
||||
end
|
||||
local after = line:byte(e)
|
||||
if e > v and (after == nil or is_space(after) or is_quote(after)) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- 4. name=value and name: value, wherever they stand: an assignment, an
|
||||
-- export, an option with `=`, a header, a field of JSON, a part of a query.
|
||||
local function secret_assignment(line, lower)
|
||||
local n = #lower
|
||||
local i = 1
|
||||
while i <= n do
|
||||
if is_name(lower:byte(i)) then
|
||||
local j = i
|
||||
while is_name(lower:byte(j + 1)) do
|
||||
j = j + 1
|
||||
end
|
||||
local p = j + 1
|
||||
local quoted = is_quote(lower:byte(p))
|
||||
if quoted then
|
||||
p = p + 1
|
||||
end
|
||||
local sep = lower:byte(p)
|
||||
if sep == 61 or sep == 58 then
|
||||
local run = lower:sub(i, j)
|
||||
local kind = secret_name(run, sep)
|
||||
if kind then
|
||||
local v = p + 1
|
||||
local ok = true
|
||||
if sep == 58 then
|
||||
local spaced = lower:byte(v) == 32
|
||||
if spaced then
|
||||
v = v + 1
|
||||
end
|
||||
-- name:value with nothing between is a header only when it
|
||||
-- looks like one; host:port and image:tag are far more common
|
||||
ok = (spaced or quoted or run:sub(1, 2) == 'x-') and lower:byte(v) ~= 47
|
||||
end
|
||||
if ok and secret_value(line, v, kind) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
i = j + 1
|
||||
else
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function unquoted(token)
|
||||
local q = token:byte(1)
|
||||
if is_quote(q) then
|
||||
token = token:sub(2)
|
||||
if token:byte(#token) == q then
|
||||
token = token:sub(1, #token - 1)
|
||||
end
|
||||
end
|
||||
return token
|
||||
end
|
||||
|
||||
-- user:pass, as curl's -u takes it
|
||||
local function is_user_pass(value)
|
||||
local v = unquoted(value)
|
||||
local colon = v:find(':', 1, true)
|
||||
if not colon or colon == 1 or colon == #v or v:byte(colon + 1) == 36 then
|
||||
return false
|
||||
end
|
||||
return not (v:sub(1, colon - 1):match('^%d+$') and v:sub(colon + 1):match('^%d+$'))
|
||||
end
|
||||
|
||||
local STRONG_PARTS = {
|
||||
password = true,
|
||||
passwd = true,
|
||||
passphrase = true,
|
||||
pass = true,
|
||||
token = true,
|
||||
secret = true,
|
||||
apikey = true,
|
||||
credential = true,
|
||||
credentials = true,
|
||||
}
|
||||
|
||||
-- { the programs, the option, value attached (-pVALUE), value apart (-p VALUE) }
|
||||
local SECRET_CLIENTS = {
|
||||
{ { 'mysql', 'mariadb', 'mysqldump', 'mariadb-dump', 'mysqladmin', 'mariadb-admin', 'mysqlimport', 'mysqlcheck', 'mysqlsh', 'mycli' }, '-p', true, false },
|
||||
{ { 'sshpass' }, '-p', true, true },
|
||||
{ { '7z', '7za', '7zr', '7zz', 'rar', 'unrar' }, '-p', true, false },
|
||||
{ { 'zip', 'unzip' }, '-P', true, true },
|
||||
{ { 'redis-cli', 'valkey-cli', 'redis-benchmark' }, '-a', false, true },
|
||||
{ { 'ldapsearch', 'ldapmodify', 'ldapadd', 'ldapdelete', 'ldapwhoami', 'ldappasswd' }, '-w', true, true },
|
||||
{ { 'mongo', 'mongosh', 'mongodump', 'mongorestore', 'mongoexport', 'mongoimport' }, '-p', true, true },
|
||||
{ { 'mosquitto_pub', 'mosquitto_sub' }, '-P', false, true },
|
||||
{ { 'login' }, '-p', true, true },
|
||||
}
|
||||
|
||||
local USER_PASS_CLIENTS = { 'curl', 'wget', 'http', 'https', 'xh', 'aria2c', 'ab', 'svn' }
|
||||
local USER_PASS_OPTIONS = { ['-u'] = true, ['--user'] = true, ['--proxy-user'] = true, ['-U'] = true, ['-A'] = true, ['-a'] = true }
|
||||
|
||||
-- 5 and 6. Options whose value is a word of its own, a program's own way of
|
||||
-- taking a password, and lines that feed one to a program.
|
||||
local function secret_words(line, lower)
|
||||
local tokens, lowered, words = {}, {}, {}
|
||||
for token in line:gmatch('%S+') do
|
||||
tokens[#tokens + 1] = token
|
||||
end
|
||||
for token in lower:gmatch('%S+') do
|
||||
lowered[#lowered + 1] = token
|
||||
local base = unquoted(token):match('([^/]+)$')
|
||||
if base then
|
||||
words[base] = true
|
||||
end
|
||||
end
|
||||
for i, token in ipairs(lowered) do
|
||||
if token == '--password-stdin' then
|
||||
return true
|
||||
end
|
||||
if token:sub(1, 2) == '--' and not token:find('=', 1, true) and token:sub(3, 5) ~= 'no-' then
|
||||
local name = token:sub(3)
|
||||
local kind
|
||||
local parts = 0
|
||||
local key = false
|
||||
for piece in name:gmatch('[^%-_]+') do
|
||||
parts = parts + 1
|
||||
if STRONG_PARTS[piece] then
|
||||
kind = 'strong'
|
||||
elseif piece == 'auth' or piece == 'pwd' then
|
||||
kind = kind or 'weak'
|
||||
elseif piece == 'key' then
|
||||
key = true
|
||||
end
|
||||
end
|
||||
if key and parts >= 2 then
|
||||
kind = kind or 'weak'
|
||||
end
|
||||
local value = tokens[i + 1]
|
||||
if kind and value and value:byte(1) ~= 45 and secret_value(value, 1, kind) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
if unquoted(tokens[i]):sub(1, 5) == 'pass:' and #unquoted(tokens[i]) > 5 then
|
||||
return true -- openssl's -passin pass:…
|
||||
end
|
||||
end
|
||||
for _, client in ipairs(SECRET_CLIENTS) do
|
||||
local there = false
|
||||
for _, name in ipairs(client[1]) do
|
||||
there = there or words[name] == true
|
||||
end
|
||||
if there then
|
||||
local flag = client[2]
|
||||
for i, token in ipairs(tokens) do
|
||||
if token == flag then
|
||||
local value = tokens[i + 1]
|
||||
if client[4] and value and value:byte(1) ~= 45 and secret_value(value, 1, 'strong') then
|
||||
return true
|
||||
end
|
||||
elseif client[3] and token:sub(1, #flag) == flag and token:sub(1, 2) ~= '--' then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local asks = false
|
||||
for _, name in ipairs(USER_PASS_CLIENTS) do
|
||||
asks = asks or words[name] == true
|
||||
end
|
||||
if asks then
|
||||
for i, token in ipairs(tokens) do
|
||||
if USER_PASS_OPTIONS[token] then
|
||||
if tokens[i + 1] and is_user_pass(tokens[i + 1]) then
|
||||
return true
|
||||
end
|
||||
elseif token:sub(1, 7) == '--user=' then
|
||||
if is_user_pass(token:sub(8)) then
|
||||
return true
|
||||
end
|
||||
elseif token:sub(1, 13) == '--proxy-user=' then
|
||||
if is_user_pass(token:sub(14)) then
|
||||
return true
|
||||
end
|
||||
elseif token:sub(1, 2) == '-u' and #token > 2 and is_user_pass(token:sub(3)) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
if words['chpasswd'] then
|
||||
return true
|
||||
end
|
||||
local dash_s, stdin, flag_b = false, false, false
|
||||
for _, token in ipairs(tokens) do
|
||||
dash_s = dash_s or token == '-S'
|
||||
stdin = stdin or token == '--stdin'
|
||||
flag_b = flag_b or token:match('^%-%a*b%a*$') ~= nil
|
||||
end
|
||||
return (words['sudo'] == true and dash_s) or (words['passwd'] == true and stdin) or (words['htpasswd'] == true and flag_b)
|
||||
end
|
||||
|
||||
-- 7. A long word that looks random: 32 or more of [A-Za-z0-9+/=_-] with a
|
||||
-- small letter, a capital and two digits in it, and not a path (at most two
|
||||
-- slashes). A commit's hash and a UUID are not: they have no capitals.
|
||||
local function secret_random(line)
|
||||
local n = #line
|
||||
local i = 1
|
||||
while i <= n do
|
||||
local b = line:byte(i)
|
||||
if is_word(b) or b == 43 or b == 47 or b == 61 then
|
||||
local j = i
|
||||
local small, capital, digits, slashes = false, false, 0, 0
|
||||
while true do
|
||||
b = line:byte(j)
|
||||
if b == nil or not (is_word(b) or b == 43 or b == 47 or b == 61) then
|
||||
break
|
||||
end
|
||||
if b >= 97 and b <= 122 then
|
||||
small = true
|
||||
elseif b >= 65 and b <= 90 then
|
||||
capital = true
|
||||
elseif is_digit(b) then
|
||||
digits = digits + 1
|
||||
elseif b == 47 then
|
||||
slashes = slashes + 1
|
||||
end
|
||||
j = j + 1
|
||||
end
|
||||
if j - i >= 32 and small and capital and digits >= 2 and slashes <= 2 then
|
||||
return true
|
||||
end
|
||||
i = j
|
||||
else
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- What stands in a context file in place of a command that looked as if it
|
||||
-- held a secret (its output goes with it), and of a line of output or of
|
||||
-- the screen that did.
|
||||
M.SECRET_COMMAND = '[a command that looked as if it held a secret was left out, with its output]'
|
||||
M.SECRET_LINE = '[a line that looked as if it held a secret was left out]'
|
||||
|
||||
-- Text for a context file, a line at a time: a line that looks as if it
|
||||
-- holds a secret is replaced by M.SECRET_LINE.
|
||||
function M.scrub(text)
|
||||
if type(text) ~= 'string' or text == '' then
|
||||
return text
|
||||
end
|
||||
local out = {}
|
||||
local n = 0
|
||||
local ended = text:sub(-1) == '\n'
|
||||
for line in (ended and text or (text .. '\n')):gmatch('([^\n]*)\n') do
|
||||
n = n + 1
|
||||
out[n] = M.looks_secret(line) and M.SECRET_LINE or line
|
||||
end
|
||||
return table.concat(out, '\n') .. (ended and '\n' or '')
|
||||
end
|
||||
|
||||
function M.looks_secret(line)
|
||||
if type(line) ~= 'string' or line == '' then
|
||||
return false
|
||||
end
|
||||
local lower = line:lower()
|
||||
return secret_beginning(line)
|
||||
or secret_header(line, lower)
|
||||
or secret_url(line, lower)
|
||||
or secret_assignment(line, lower)
|
||||
or secret_words(line, lower)
|
||||
or secret_random(line)
|
||||
end
|
||||
|
||||
local function zone_before(a, b)
|
||||
if a.start_y ~= b.start_y then
|
||||
return a.start_y < b.start_y
|
||||
@@ -1046,15 +1615,25 @@ function M.blocks_from_zones(zones, text_of, limits)
|
||||
local g = run[i]
|
||||
local command = M.clean(text_of(g.input) or '', true)
|
||||
command = command:gsub('%s+$', '')
|
||||
command = M.tail(command, 50, 4096)
|
||||
local out = {}
|
||||
for _, z in ipairs(g.outputs) do
|
||||
out[#out + 1] = text_of(z) or ''
|
||||
local secret = M.looks_secret((command:gsub('\n', ' ')))
|
||||
for line in (command .. '\n'):gmatch('([^\n]*)\n') do
|
||||
secret = secret or M.looks_secret(line)
|
||||
end
|
||||
if secret then
|
||||
-- neither the command nor what it printed: the zones' text of its
|
||||
-- output is not even fetched
|
||||
blocks[#blocks + 1] = { command = M.SECRET_COMMAND, exit = M.null, output = '' }
|
||||
else
|
||||
command = M.tail(command, 50, 4096)
|
||||
local out = {}
|
||||
for _, z in ipairs(g.outputs) do
|
||||
out[#out + 1] = text_of(z) or ''
|
||||
end
|
||||
local output = M.clean(table.concat(out, '\n'), true)
|
||||
output = output:gsub('%s+$', '')
|
||||
output = M.scrub(M.tail(output, limits.output_lines, limits.output_bytes))
|
||||
blocks[#blocks + 1] = { command = command, exit = M.null, output = output }
|
||||
end
|
||||
local output = M.clean(table.concat(out, '\n'), true)
|
||||
output = output:gsub('%s+$', '')
|
||||
output = M.tail(output, limits.output_lines, limits.output_bytes)
|
||||
blocks[#blocks + 1] = { command = command, exit = M.null, output = output }
|
||||
end
|
||||
return blocks
|
||||
end
|
||||
|
||||
@@ -1065,7 +1065,8 @@ function M.gather_context(pane, explicit_screen)
|
||||
want_screen = #blocks == 0
|
||||
end
|
||||
if want_screen then
|
||||
screen = core.tail(core.clean(pane:get_lines_as_text(), true), limits.screen_lines, limits.output_bytes)
|
||||
-- a line of it that looks as if it holds a secret is left out
|
||||
screen = core.scrub(core.tail(core.clean(pane:get_lines_as_text(), true), limits.screen_lines, limits.output_bytes))
|
||||
end
|
||||
|
||||
local shell
|
||||
|
||||
@@ -428,6 +428,71 @@ end
|
||||
|
||||
local LIM = { blocks = 5, output_lines = 200, output_bytes = 16384 }
|
||||
|
||||
test('looks_secret: the table of cases the Rust side is held to as well', function()
|
||||
local held, ordinary = 0, 0
|
||||
for line in io.lines(here .. '/secrets.txt') do
|
||||
local sign, text = line:match('^([+-]) (.*)$')
|
||||
if sign == '+' then
|
||||
held = held + 1
|
||||
check(core.looks_secret(text) == true, 'missed: ' .. text)
|
||||
elseif sign == '-' then
|
||||
ordinary = ordinary + 1
|
||||
check(core.looks_secret(text) == false, 'taken for a secret: ' .. text)
|
||||
end
|
||||
end
|
||||
check(held >= 80 and ordinary >= 150, string.format('the table was read: %d and %d cases', held, ordinary))
|
||||
eq(core.looks_secret(''), false, 'nothing')
|
||||
eq(core.looks_secret(nil), false, 'not text')
|
||||
eq(core.looks_secret('export HESLO_TOKEN=žltý'), true, 'a value that is not ASCII')
|
||||
eq(core.looks_secret('echo žltý kôň'), false, 'text that is not ASCII is only text')
|
||||
end)
|
||||
|
||||
test('a context file: a command that looks as if it holds a secret is left out, with its output', function()
|
||||
local fetched = {}
|
||||
local function fetch(z)
|
||||
fetched[#fetched + 1] = z.text
|
||||
return z.text
|
||||
end
|
||||
local zones = {
|
||||
zone('Prompt', 0, '$ '),
|
||||
zone('Input', 0, 'export GITHUB_TOKEN=abc123'),
|
||||
zone('Prompt', 1, '$ '),
|
||||
zone('Input', 1, 'mysql -u root -pS3cretWord shop'),
|
||||
zone('Output', 2, 'ERROR 1045: Access denied for S3cretWord\n', 3),
|
||||
zone('Prompt', 4, '$ '),
|
||||
zone('Input', 4, 'env | sort'),
|
||||
zone('Output', 5, 'HOME=/home/u\nAPI_KEY=abc123\nLANG=C\n', 8),
|
||||
zone('Prompt', 9, '$ '),
|
||||
zone('Input', 9, 'git status'),
|
||||
zone('Output', 10, 'clean\n', 11),
|
||||
zone('Prompt', 12, '$ '),
|
||||
}
|
||||
local blocks = core.blocks_from_zones(zones, fetch, LIM)
|
||||
eq(#blocks, 4, 'four commands ran')
|
||||
eq(blocks[1].command, core.SECRET_COMMAND, 'the export is not there, only that there was one')
|
||||
eq(blocks[2].command, core.SECRET_COMMAND, 'nor the password on a command line')
|
||||
eq(blocks[2].output, '', 'and what it printed goes with it')
|
||||
eq(blocks[3].command, 'env | sort', 'an ordinary command stays')
|
||||
eq(blocks[3].output, 'HOME=/home/u\n' .. core.SECRET_LINE .. '\nLANG=C', 'a line of its output that holds one is left out')
|
||||
eq(blocks[4].command, 'git status', 'the next command is as it was')
|
||||
eq(blocks[4].output, 'clean', 'with its output')
|
||||
local json = core.encode_context(core.context { pane = 1, cwd = '/p', blocks = blocks })
|
||||
check(not json:find('abc123', 1, true) and not json:find('S3cretWord', 1, true), 'nothing of a secret is in the file')
|
||||
for _, text in ipairs(fetched) do
|
||||
check(not text:find('Access denied', 1, true), 'the output of such a command is not even read')
|
||||
end
|
||||
-- a command over several lines, the secret on its second
|
||||
local multi = core.blocks_from_zones({
|
||||
zone('Input', 0, 'curl https://example.org \\\n -H "Authorization: Bearer abc123def456"', 1),
|
||||
zone('Output', 2, 'ok\n'),
|
||||
zone('Prompt', 3, '$ '),
|
||||
}, text_of, LIM)
|
||||
eq(multi[1].command, core.SECRET_COMMAND, 'found on any of its lines')
|
||||
eq(core.scrub 'a\nPASSWORD=hunter2\nb\n', 'a\n' .. core.SECRET_LINE .. '\nb\n', 'the screen, a line at a time')
|
||||
eq(core.scrub 'plain', 'plain', 'nothing to leave out')
|
||||
eq(core.scrub '', '', 'empty')
|
||||
end)
|
||||
|
||||
test('blocks_from_zones: commands and their output', function()
|
||||
local zones = {
|
||||
zone('Prompt', 0, '$ '),
|
||||
@@ -1528,6 +1593,19 @@ test('a CLI that is too old: said in words', function()
|
||||
check(described(win):find('lembas update', 1, true), 'and how to update')
|
||||
end)
|
||||
|
||||
test('ask: a screen with a secret on it goes without that line', function()
|
||||
local dir = fresh_dir 'scrub'
|
||||
with_cli(dir)
|
||||
local _, w = new_layer {}
|
||||
local pane = fake.pane { id = 1, screen = '$ export API_KEY=abc123\n$ make\nerror: it broke\n' }
|
||||
fake.tab { pane }
|
||||
w.emit('llembas-ask-line', fake.window(), pane, 'why?')
|
||||
local text = read_file(context_files(dir)[1])
|
||||
check(not text:find('abc123', 1, true), 'the key is not in the file')
|
||||
check(text:find('left out', 1, true) ~= nil, 'that a line was left out is')
|
||||
check(text:find('error: it broke', 1, true) ~= nil, 'the rest of the screen is')
|
||||
end)
|
||||
|
||||
test('ask: no shell integration gives the screen', function()
|
||||
local dir = fresh_dir 'ask4'
|
||||
with_cli(dir)
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
# LLeMbas TERM: command lines that look as if they hold a secret, and ones that do not.
|
||||
#
|
||||
# One case a line: "+ " before a line that must be taken for one that holds a secret,
|
||||
# "- " before a line that must not. Both implementations of the rule are held to this
|
||||
# table: llembas/line/src/secret.rs (cargo test -p llembas-line) and core.looks_secret
|
||||
# (scripts/test-lua.sh). Nothing here is a real credential: every value is made up, and
|
||||
# shorter than the real thing where a real one has a fixed length.
|
||||
|
||||
# -- assignments and exports whose name says what it holds
|
||||
+ export OPENAI_API_KEY=sk-not-a-real-key
|
||||
+ export GITHUB_TOKEN=abc123
|
||||
+ API_KEY=abc123 ./deploy.sh
|
||||
+ MY_SECRET=hunter2 make release
|
||||
+ export DB_PASSWORD='correct horse'
|
||||
+ PGPASSWORD=hunter2 psql -h db.example.org -U app
|
||||
+ env MYSQL_PWD=hunter2 mysqldump shop
|
||||
+ export AWS_SECRET_ACCESS_KEY="madeUpValue"
|
||||
+ set -x CLIENT_SECRET madeup; export CLIENT_SECRET=madeup
|
||||
+ export passwd=hunter2
|
||||
+ CREDENTIALS=user:hunter2 ./run
|
||||
+ export HTTP_AUTH=alice:hunter2
|
||||
+ docker run -e POSTGRES_PASSWORD=hunter2 postgres
|
||||
+ docker run --env=API_TOKEN=abc123 app
|
||||
+ helm install db chart --set adminPassword=hunter2
|
||||
+ export TOKEN='$not-a-variable-in-single-quotes'
|
||||
+ git config --global user.signingkey=ABCDEF0123
|
||||
- export EDITOR=vim
|
||||
- export PATH=$HOME/.local/bin:$PATH
|
||||
- export GITHUB_TOKEN=$(gh auth token)
|
||||
- export API_KEY="$OTHER_KEY"
|
||||
- TOKEN=$CI_JOB_TOKEN ./deploy.sh
|
||||
- export PASSWORD=
|
||||
- export API_KEY
|
||||
- unset GITHUB_TOKEN
|
||||
- read -s PASSWORD
|
||||
- PWD=/tmp ls
|
||||
- cd "$OLDPWD"
|
||||
- SSH_AUTH_SOCK=/run/user/1000/keyring/ssh ssh example.org
|
||||
- XAUTHORITY=~/.Xauthority xterm
|
||||
- make CC=gcc -j8
|
||||
- LANG=C sort names.txt
|
||||
- echo $API_KEY
|
||||
- printenv GITHUB_TOKEN
|
||||
|
||||
# -- options that take a password, a token, a key
|
||||
+ mysql -u root -pS3cretWord shop
|
||||
+ mysqldump -pS3cretWord shop > shop.sql
|
||||
+ mariadb -uroot -phunter2
|
||||
+ mysql --password=hunter2 shop
|
||||
+ mysql --password hunter2 shop
|
||||
+ psql --password=hunter2
|
||||
+ wget --user=alice --password=hunter2 https://example.org/file
|
||||
+ gh auth login --with-token abc123
|
||||
+ vault login --token abc123def
|
||||
+ cli --api-key abc123 list
|
||||
+ cli --api-key=abc123 list
|
||||
+ cli --apikey abc123
|
||||
+ cli --secret abc123
|
||||
+ cli --client-secret=abc123
|
||||
+ cli --access-token abc123
|
||||
+ cli --auth-token=abc123
|
||||
+ sshpass -p hunter2 ssh example.org
|
||||
+ sshpass -phunter2 ssh example.org
|
||||
+ docker login -u alice -p hunter2 registry.example.org
|
||||
+ docker login --username alice --password hunter2
|
||||
+ echo hunter2 | docker login -u alice --password-stdin
|
||||
+ redis-cli -a hunter2 ping
|
||||
+ 7z a -phunter2 archive.7z files/
|
||||
+ unzip -P hunter2 archive.zip
|
||||
+ zip -P hunter2 out.zip file
|
||||
+ ldapsearch -D cn=admin -w hunter2 -b dc=example
|
||||
+ mongosh -u alice -p hunter2
|
||||
+ openssl rsa -in key.pem -passin pass:hunter2
|
||||
+ htpasswd -b .htpasswd alice hunter2
|
||||
+ echo 'hunter2' | sudo -S apt update
|
||||
+ echo "alice:hunter2" | chpasswd
|
||||
+ echo hunter2 | passwd --stdin alice
|
||||
- mysql -u root -p shop
|
||||
- mysql -u root -p
|
||||
- mysql -P 3306 -h db.example.org shop
|
||||
- psql --no-password shop
|
||||
- ssh -p 2222 example.org
|
||||
- mkdir -p build/out
|
||||
- cp -p a b
|
||||
- docker run -p 8080:80 nginx
|
||||
- docker run -u 1000:1000 app
|
||||
- docker run -u app:app app
|
||||
- git commit --author="Alice <alice@example.org>" -m fix
|
||||
- git log --author=alice
|
||||
- curl --key ~/.ssh/client.pem https://example.org
|
||||
- curl --key=/etc/ssl/client.pem https://example.org
|
||||
- ssh -i ~/.ssh/id_ed25519 example.org
|
||||
- ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
|
||||
- sort --key=2 file.txt
|
||||
- gpg --keyserver hkps://keys.example.org --recv-keys ABCDEF01
|
||||
- tar -xpf archive.tar
|
||||
- grep -rn password src/
|
||||
- grep -i "password" config.yaml
|
||||
- grep -rn 'Authorization:' src/
|
||||
- vim ~/.config/app/token.json
|
||||
- cat secret.txt
|
||||
- ls secrets/
|
||||
- kubectl get secret app-credentials -o yaml
|
||||
- pass show email/work
|
||||
- man passwd
|
||||
- passwd alice
|
||||
- sudo -s
|
||||
- sudo -u postgres psql
|
||||
- unzip archive.zip
|
||||
- 7z x archive.7z
|
||||
- redis-cli ping
|
||||
- htpasswd -c .htpasswd alice
|
||||
- npm login
|
||||
- gh auth login
|
||||
- gh auth status
|
||||
|
||||
# -- name and password together
|
||||
+ curl -u alice:hunter2 https://example.org/api
|
||||
+ curl --user alice:hunter2 https://example.org/api
|
||||
+ curl --user=alice:hunter2 https://example.org/api
|
||||
+ curl -ualice:hunter2 https://example.org
|
||||
+ curl --proxy-user alice:hunter2 https://example.org
|
||||
+ git clone https://alice:hunter2@example.org/repo.git
|
||||
+ psql postgres://app:hunter2@db.example.org:5432/shop
|
||||
+ mongosh "mongodb://alice:hunter2@db.example.org/admin"
|
||||
+ pip install --index-url https://alice:abc123@pypi.example.org/simple pkg
|
||||
+ wget ftp://alice:hunter2@example.org/file
|
||||
- curl -u alice https://example.org/api
|
||||
- curl https://example.org/api
|
||||
- git clone https://example.org/repo.git
|
||||
- git clone git@example.org:alice/repo.git
|
||||
- git clone ssh://git@example.org:2222/alice/repo.git
|
||||
- psql postgres://app@db.example.org/shop
|
||||
- scp file.txt alice@example.org:/srv/www/
|
||||
- rsync -av src/ alice@example.org:backup/
|
||||
- ssh alice@example.org
|
||||
- curl http://localhost:8080/health
|
||||
- curl "https://example.org/search?q=a:b@c"
|
||||
- skopeo copy docker://alpine:latest dir:out
|
||||
- curl http://[::1]:8080/health
|
||||
- curl http://localhost:80
|
||||
- psql postgres://app
|
||||
+ psql postgres://app:hunter2
|
||||
+ git clone https://alice:hunt
|
||||
|
||||
# -- headers, fields and queries
|
||||
+ curl -H "Authorization: Bearer abc123def456" https://example.org
|
||||
+ curl -H 'Authorization: Basic YWxpY2U6aHVudGVyMg==' https://example.org
|
||||
+ curl -H "authorization: token abc123" https://example.org
|
||||
+ curl -H "X-Api-Key: abc123" https://example.org
|
||||
+ curl -H "X-Api-Key:abc123" https://example.org
|
||||
+ curl -H "X-Auth-Token: abc123" https://example.org
|
||||
+ http example.org "Authorization:Bearer abc123def456"
|
||||
+ curl -d '{"password": "hunter2"}' https://example.org/login
|
||||
+ curl -d '{"user":"alice","password":"hunter2"}' https://example.org/login
|
||||
+ curl -d "username=alice&password=hunter2" https://example.org/login
|
||||
+ curl "https://example.org/api?access_token=abc123"
|
||||
+ curl "https://example.org/api?api_key=abc123&q=x"
|
||||
+ echo "token: abc123" >> config.yaml
|
||||
+ websocat "wss://example.org/socket" -H "Sec-Token: abc123"
|
||||
- curl -H "Authorization: Bearer $TOKEN" https://example.org
|
||||
- curl -H "Accept: application/json" https://example.org
|
||||
- curl -H "Content-Type: application/json" -d '{"q":"x"}' https://example.org
|
||||
- curl -H "X-Api-Key: $API_KEY" https://example.org
|
||||
- curl -d "username=alice" https://example.org/login
|
||||
- echo "the bearer of news"
|
||||
- echo "basic usage: run make"
|
||||
- docker pull registry.example.org/token-service:latest
|
||||
- scp notes.txt tokenhost:/tmp/
|
||||
- kubectl logs deploy/auth-service
|
||||
- systemctl status auth.service
|
||||
|
||||
# -- keys by their well-known beginning
|
||||
+ export OPENAI=sk-abcdefghijklmnopqrstuvwx
|
||||
+ echo sk-proj-abcdefghijklmnopqrstuvwx
|
||||
+ echo sk-proj-ab
|
||||
+ tool login sk-ant-x
|
||||
+ tool login ghp_abcdefgh
|
||||
+ tool login glpat-a
|
||||
+ git remote set-url origin https://ghp_abcdefghij0123456789@example.org/a/b
|
||||
+ gh api -H x: ghp_abcdefghij0123456789
|
||||
+ echo github_pat_abcdefghij0123456789
|
||||
+ curl --header "PRIVATE-TOKEN: glpat-abcdefghij012345" https://example.org
|
||||
+ slack-cli send xoxb-not-a-real-one "hello"
|
||||
+ aws configure set aws_access_key_id AKIAEXAMPLEEXAMPLE00
|
||||
+ echo "-----BEGIN OPENSSH PRIVATE KEY-----" > key
|
||||
+ printf '%s' '-----BEGIN RSA PRIVATE KEY-----'
|
||||
- task-runner --list
|
||||
- pip install scikit-learn
|
||||
- echo sk-short
|
||||
- echo ghp_abc
|
||||
- brew install ask-cli
|
||||
- ls disk-usage-report-2024-final-version.txt
|
||||
- echo "-----BEGIN CERTIFICATE-----"
|
||||
- echo "-----BEGIN PGP PUBLIC KEY BLOCK-----"
|
||||
- git checkout ghp-pages
|
||||
|
||||
# -- a long word that looks random
|
||||
+ deploy --with Zx9Qv7Lm2Tp4Rk8Wn3Hs6Yd1Bc5Fg0JeXAMPLEab
|
||||
+ echo eyJhbGciOiJub25lIn0.eyJzdWIiOiJub2JvZHkiLCJ4IjoxMjM0NX0.c2lnbmF0dXJl
|
||||
+ curl https://example.org/hook/T0aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV
|
||||
- git checkout 3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4c3d2e1f0a
|
||||
- git show 1026152aa3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4
|
||||
- docker pull nginx@sha256:3f2a9c1b7d4e8f6a5b0c9d8e7f6a5b4c3d2e1f0a3f2a9c1b7d4e8f6a5b0c9d8e
|
||||
- uuidgen; echo 123e4567-e89b-12d3-a456-426614174000
|
||||
- cd /home/alice/Projects/MyApp2/build/release/x86_64
|
||||
- cat ~/Documents/Reports/Annual-Report-2024/Summary.md
|
||||
- kubectl logs my-service-7d9f8b6c5d-x2k4j --tail=100
|
||||
- java -cp build/libs/MyApplication-1.0-SNAPSHOT.jar com.example.Main
|
||||
- cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr ..
|
||||
- ./configure --prefix=/usr --enable-shared --with-openssl
|
||||
- npm install --save-dev @types/node typescript eslint prettier
|
||||
- wget https://example.org/downloads/Package-Installer-v2.14.3-linux-x86_64.tar.gz
|
||||
|
||||
# -- ordinary commands, of the kind typed all day
|
||||
- ls -la
|
||||
- cd ..
|
||||
- git status
|
||||
- git add -p
|
||||
- git commit -m "fix the key handling in the token parser"
|
||||
- git push origin main
|
||||
- git log --oneline -20
|
||||
- git diff HEAD~1 -- src/auth.rs
|
||||
- git rebase -i HEAD~3
|
||||
- git stash pop
|
||||
- cargo build --release
|
||||
- cargo test -p llembas-line
|
||||
- npm run build
|
||||
- npm test -- --watch
|
||||
- make -j8 test
|
||||
- python3 -m venv .venv
|
||||
- python manage.py migrate
|
||||
- pip install -r requirements.txt
|
||||
- docker ps -a
|
||||
- docker compose up -d
|
||||
- docker exec -it app bash
|
||||
- docker build -t app:latest .
|
||||
- kubectl get pods -n prod
|
||||
- kubectl apply -f deploy.yaml
|
||||
- ssh example.org
|
||||
- ssh-add ~/.ssh/id_ed25519
|
||||
- scp a.txt example.org:
|
||||
- rsync -av --delete src/ dst/
|
||||
- tar -czf backup.tar.gz src/
|
||||
- find . -name '*.rs' -newer Cargo.toml
|
||||
- grep -rn "TODO" src/
|
||||
- sed -i 's/foo/bar/g' file.txt
|
||||
- awk -F: '{print $1}' /etc/passwd
|
||||
- sudo apt update && sudo apt upgrade -y
|
||||
- sudo systemctl restart nginx
|
||||
- journalctl -u nginx -f
|
||||
- tail -f /var/log/syslog
|
||||
- ps aux | grep nginx
|
||||
- kill -9 12345
|
||||
- df -h
|
||||
- du -sh *
|
||||
- htop
|
||||
- vim src/main.rs
|
||||
- nvim +42 README.md
|
||||
- less /etc/hosts
|
||||
- cat package.json | jq .version
|
||||
- curl -fsSL https://example.org/install.sh -o install.sh
|
||||
- curl -X POST -d '{"name":"x"}' https://example.org/items
|
||||
- ping -c 3 example.org
|
||||
- dig +short example.org
|
||||
- openssl x509 -in cert.pem -noout -dates
|
||||
- openssl genrsa -out key.pem 4096
|
||||
- gpg --list-keys
|
||||
- chmod 600 ~/.ssh/authorized_keys
|
||||
- chown -R www-data:www-data /srv/www
|
||||
- ln -s ../shared/config config
|
||||
- echo "hello world" > out.txt
|
||||
- date +%Y-%m-%d
|
||||
- history | tail
|
||||
- which python3
|
||||
- man tar
|
||||
- for f in *.txt; do wc -l "$f"; done
|
||||
- xmodmap -e "keycode 66 = Escape"
|
||||
- setxkbmap -option caps:escape
|
||||
- lembas login
|
||||
- terraform plan -out=tfplan
|
||||
- ansible-playbook -i hosts site.yml --ask-vault-pass
|
||||
- psql -h db.example.org -U app shop
|
||||
- sqlite3 app.db "select count(*) from users"
|
||||
Reference in new issue
Block a user