diff --git a/scripts/lib/sqlite-crlf.sh b/scripts/lib/sqlite-crlf.sh index 2502c51b7..81aea415a 100644 --- a/scripts/lib/sqlite-crlf.sh +++ b/scripts/lib/sqlite-crlf.sh @@ -52,3 +52,20 @@ agmsg_sqlite_mem() { return 0 fi } + +# Same as agmsg_sqlite_mem, but the statement is read from standard input +# instead of being an argument. An argument is readable by every process on the +# machine while the program runs; a statement that holds a secret (a data +# address, a device code, a team config that names one) must not be. Usage: +# printf '%s\n' "$sql" | agmsg_sqlite_mem_stdin +agmsg_sqlite_mem_stdin() { + [ -n "$_AGMSG_SQLITE_CRLF" ] || _agmsg_sqlite_crlf + if [ "$_AGMSG_SQLITE_CRLF" = 1 ]; then + sqlite3 :memory: | LC_ALL=C tr -d '\r' + else + local _agmsg_mem_rc=0 + sqlite3 :memory: || _agmsg_mem_rc=$? + if [ "$_agmsg_mem_rc" -ne 0 ] && [ -o pipefail ]; then return "$_agmsg_mem_rc"; fi + return 0 + fi +} diff --git a/scripts/remote.sh b/scripts/remote.sh index d347c0ffa..56e9bf5ea 100644 --- a/scripts/remote.sh +++ b/scripts/remote.sh @@ -96,7 +96,7 @@ _remote_local_roster_count() { local cfg="$1" escaped [ -f "$cfg" ] || { echo 0; return; } escaped=$(LC_ALL=C sed "s/'/''/g" "$cfg") - agmsg_sqlite_mem "SELECT COALESCE((SELECT count(*) FROM + _remote_sql "SELECT COALESCE((SELECT count(*) FROM json_each(json_extract('$escaped', '\$.agents'))), 0);" } @@ -117,11 +117,18 @@ _remote_sync_config_file() { # `resolve_team` for the same caveat, and PR #482 for the sibling-script fix # this mirrors — e.g. a remote_team_name containing an apostrophe, which # _remote_commit below stores as ordinary, unremarkable JSON text). +# _remote_sql : one in-memory sqlite statement, given on standard +# input so that nothing it contains (a document that names a secret) is ever an +# argument of the sqlite3 process. +_remote_sql() { agmsg_sqlite_mem_stdin <<< "$1"; } + _remote_read_config_field() { - local cfg="$1" path="$2" escaped + local cfg="$1" path="$2" [ -f "$cfg" ] || { echo "null"; return; } - escaped=$(LC_ALL=C sed "s/'/''/g" "$cfg") - agmsg_sqlite_mem "SELECT json_extract('$escaped', '$path');" + # The team config holds the server address, which is a capability for a + # device-approved team, so sqlite reads it from the file; it is never put in + # an argument. + _remote_sql "SELECT json_extract(CAST(readfile('$(agmsg_sql_readfile_path "$cfg")') AS TEXT), '$path');" } # Bootstrap a brand-new local team dir/config, mirroring join.sh's own @@ -779,7 +786,7 @@ _remote_server_lists_feature() { code="$(_remote_http_json_call GET "$origin/v1/health" - "$out" 2>/dev/null)" || code="000" if [ "$code" = "200" ]; then doc="$(LC_ALL=C sed "s/'/''/g" "$out")" - names="$(agmsg_sqlite_mem "SELECT CASE WHEN json_valid('$doc') AND json_type('$doc','\$.features')='array' + names="$(_remote_sql "SELECT CASE WHEN json_valid('$doc') AND json_type('$doc','\$.features')='array' THEN (SELECT coalesce(group_concat(value, ' '), '') FROM json_each('$doc','\$.features') WHERE typeof(value)='text' AND value NOT GLOB '*[^a-z0-9-]*' AND value <> '') ELSE '' END;" 2>/dev/null)" && _REMOTE_HEALTH_OK=1 @@ -801,7 +808,7 @@ _remote_server_lists_feature() { _remote_binding_lists_feature() { local cfg="$1" feature="$2" cfg_escaped found cfg_escaped="$(LC_ALL=C sed "s/'/''/g" "$cfg")" - found="$(agmsg_sqlite_mem "SELECT CASE + found="$(_remote_sql "SELECT CASE WHEN json_type('$cfg_escaped','\$.remote_binding.capabilities.features')='array' THEN (SELECT count(*) FROM json_each('$cfg_escaped','\$.remote_binding.capabilities.features') WHERE value='$(_agmsg_sqlesc "$feature")') @@ -942,7 +949,7 @@ _remote_escrow_register_device() { label="$(printf '%s' "$label" | LC_ALL=C tr -cd 'A-Za-z0-9._-' | cut -c1-64)" [ -n "$label" ] || label="machine" fi - label_json="$(agmsg_sqlite_mem "SELECT json_quote('$(_agmsg_sqlesc "$label")');")" + label_json="$(_remote_sql "SELECT json_quote('$(_agmsg_sqlesc "$label")');")" [ -n "$recipient" ] || { echo "agmsg: could not read this machine's device key" >&2; return 1; } secret="${address##*/t/}"; secret="${secret%%/*}" body="$(mktemp "${TMPDIR:-/tmp}/agmsg-escrow-body.XXXXXX")" @@ -1192,7 +1199,7 @@ _remote_device_approve() { machine="$(printf '%s' "$machine" | LC_ALL=C tr -cd 'A-Za-z0-9._-' | cut -c1-64)" [ -n "$machine" ] || machine="machine" fi - machine_json="$(agmsg_sqlite_mem "SELECT json_quote('$(_agmsg_sqlesc "$machine")');")" + machine_json="$(_remote_sql "SELECT json_quote('$(_agmsg_sqlesc "$machine")');")" body="$(mktemp "${TMPDIR:-/tmp}/agmsg-device-body.XXXXXX")" out="$(mktemp "${TMPDIR:-/tmp}/agmsg-device-out.XXXXXX")" # The ids of the environment markers that matched here, only to a server that @@ -1404,7 +1411,7 @@ _remote_archive_replaced_binding() { local cfg_escaped="$1" new_instance_sql new_team_sql pv="$4" stamp="$5" new_instance_sql="$(_agmsg_sqlesc "$2")" new_team_sql="$(_agmsg_sqlesc "$3")" - agmsg_sqlite_mem \ + _remote_sql \ "WITH cfg(doc) AS (SELECT '$cfg_escaped'), cur(b) AS (SELECT json_extract(doc, '\$.remote_binding') FROM cfg), kept(arr) AS (SELECT coalesce(( @@ -1451,7 +1458,7 @@ _remote_write_binding() { IFS= read -r remote_team_id IFS= read -r remote_team_name IFS= read -r protocol_version - } < <(agmsg_sqlite_mem \ + } < <(_remote_sql \ "SELECT json_extract('$resp_escaped', '\$.server_instance_id'); SELECT json_extract('$resp_escaped', '\$.team_id'); SELECT json_extract('$resp_escaped', '\$.team_name'); @@ -1485,7 +1492,7 @@ _remote_write_binding() { archived_doc="$(_remote_archive_replaced_binding "$cfg_escaped" \ "$server_instance_id" "$remote_team_id" "$protocol_version" "$connected_at")" cfg_escaped="$(printf '%s' "$archived_doc" | LC_ALL=C sed "s/'/''/g")" - updated=$(agmsg_sqlite_mem \ + updated=$(_remote_sql \ "SELECT json_set('$cfg_escaped', '\$.remote_binding', json_object( 'endpoint', '$(_agmsg_sqlesc "$endpoint")', 'server_instance_id', '$(_agmsg_sqlesc "$server_instance_id")', @@ -1546,7 +1553,7 @@ _remote_registration_in_journal() { [ -s "$journal" ] && [ -n "$server_instance" ] || return 1 journal_sql="$(agmsg_sql_readfile_path "$journal")" members_sql="$(agmsg_sql_readfile_path "$members_file")" - verdict="$(agmsg_sqlite_mem " + verdict="$(_remote_sql " WITH j(doc) AS ( SELECT '[' || replace(rtrim(CAST(readfile('$journal_sql') AS TEXT), char(10)), char(10), ',') || ']' ), events AS ( @@ -1589,12 +1596,12 @@ _remote_roster_drift_report() { # unreadable journal is said, and the comparison is still printed. if [ -e "$journal" ]; then journal_doc="(SELECT '[' || replace(rtrim(CAST(readfile('$(agmsg_sql_readfile_path "$journal")') AS TEXT), char(10)), char(10), ',') || ']')" - [ -r "$journal" ] && [ "$(agmsg_sqlite_mem "SELECT json_valid($journal_doc);" 2>/dev/null)" = 1 ] || { + [ -r "$journal" ] && [ "$(_remote_sql "SELECT json_valid($journal_doc);" 2>/dev/null)" = 1 ] || { journal_ok=0 journal_doc="'[]'" } fi - counts="$(agmsg_sqlite_mem " + counts="$(_remote_sql " WITH events AS ( SELECT value AS e FROM json_each($journal_doc) ), here AS ( @@ -1704,11 +1711,11 @@ _remote_adopt_registration() { fi cfg_escaped="$(LC_ALL=C sed "s/'/''/g" "$cfg")" members_escaped="$(LC_ALL=C sed "s/'/''/g" "$members_file")" - local_ids="$(agmsg_sqlite_mem \ + local_ids="$(_remote_sql \ "SELECT coalesce(group_concat(mid, ','), '') FROM (SELECT json_extract(value, '\$.member_id') AS mid FROM json_each(json_extract('$cfg_escaped', '\$.agents')) ORDER BY mid);")" - remote_ids="$(agmsg_sqlite_mem \ + remote_ids="$(_remote_sql \ "SELECT coalesce(group_concat(mid, ','), '') FROM (SELECT json_extract(value, '\$.member_id') AS mid FROM json_each(json_extract('$members_escaped', '\$.members')) ORDER BY mid);")" @@ -1824,7 +1831,7 @@ _remote_local_disconnect() { escaped=$(LC_ALL=C sed "s/'/''/g" "$cfg") # is spliced as a genuine SQL string literal, NOT bound via # `.param set` (same tokenizer caveat as `_remote_read_config_field` above). - updated=$(agmsg_sqlite_mem \ + updated=$(_remote_sql \ "SELECT json_set('$escaped', '\$.remote_binding.disconnected_at', '$(_agmsg_sqlesc "$disconnected_at")', '\$.remote_binding.binding_revision', @@ -1853,17 +1860,25 @@ _remote_local_disconnect() { # reader above cannot be used: this document is the engine's stdout, and # writing it out just to read it back would put a team snapshot on disk for no # reason. -_remote_json_field() { - local doc="$1" path="$2" escaped - escaped=$(printf '%s' "$doc" | LC_ALL=C sed "s/'/''/g") - agmsg_sqlite_mem "SELECT COALESCE(json_extract('$escaped', '$path'), '');" +# _remote_json_field / _remote_json_array_length +# The document can carry a secret (a data address, a device code), and an +# argument is readable by every process on the machine, so it never goes in one: +# it is written to a private (0600) temporary file that sqlite reads, and only +# the file's name and the (public) path are in the statement. +_remote_json_query() { + local doc="$1" before="$2" after="$3" path="$4" file rc + file="$(mktemp "${TMPDIR:-/tmp}/agmsg-json.XXXXXX")" || return 1 + chmod 600 "$file" 2>/dev/null || true + printf '%s' "$doc" > "$file" + _remote_sql "SELECT ${before}json_extract(CAST(readfile('$(agmsg_sql_readfile_path "$file")') AS TEXT), '$path')${after};" + rc=$? + rm -f "$file" + return "$rc" } -_remote_json_array_length() { - local doc="$1" path="$2" escaped - escaped=$(printf '%s' "$doc" | LC_ALL=C sed "s/'/''/g") - agmsg_sqlite_mem "SELECT COALESCE(json_array_length(json_extract('$escaped', '$path')), 0);" -} +_remote_json_field() { _remote_json_query "$1" "COALESCE(" ", '')" "$2"; } + +_remote_json_array_length() { _remote_json_query "$1" "COALESCE(json_array_length(" "), 0)" "$2"; } # Writes the local team for a pull. Unlike _remote_ensure_team this does NOT # mint a team_id: the id came from the server and is recorded as it arrived. @@ -1942,7 +1957,7 @@ _remote_write_pulled_team() { return 1 fi else - initial=$(agmsg_sqlite_mem " + initial=$(_remote_sql " SELECT json_object('name','$(_agmsg_sqlesc "$team")', 'team_id','$(_agmsg_sqlesc "$team_id")', 'agents', json_object(), @@ -1995,7 +2010,7 @@ _remote_resolve_team_id() { [ -n "$result" ] || { echo "agmsg: the server did not answer the lookup for '$name'" >&2; return 1; } doc="$(printf '%s' "$result" | LC_ALL=C sed "s/'/''/g")" - count="$(agmsg_sqlite_mem "SELECT json_array_length(json_extract('$doc', '\$.teams'));")" + count="$(_remote_sql "SELECT json_array_length(json_extract('$doc', '\$.teams'));")" case "$count" in ''|*[!0-9]*) count=0 ;; esac if [ "$count" -eq 0 ]; then @@ -2003,13 +2018,13 @@ _remote_resolve_team_id() { return 1 fi if [ "$count" -eq 1 ]; then - agmsg_sqlite_mem "SELECT json_extract('$doc', '\$.teams[0].team_id');" + _remote_sql "SELECT json_extract('$doc', '\$.teams[0].team_id');" return 0 fi { echo "agmsg: $count teams are named '$name' on this server:" - agmsg_sqlite_mem " + _remote_sql " SELECT ' ' || json_extract(value, '\$.team_id') || ' registered ' || substr(json_extract(value, '\$.registered_at'), 1, 10) || ' ' || json_extract(value, '\$.current_seq') || ' messages' @@ -2203,7 +2218,7 @@ cmd_pull() { "$pulled_sid" "$pulled_id" "$pulled_protocol" "$bind_at")" escaped="$(printf '%s' "$archived_doc" | LC_ALL=C sed "s/'/''/g")" caps_escaped=$(printf '%s' "$pulled_caps" | LC_ALL=C sed "s/'/''/g") - updated=$(agmsg_sqlite_mem \ + updated=$(_remote_sql \ "SELECT json_set('$escaped', '\$.remote_binding', json_object( 'endpoint', '$(_agmsg_sqlesc "$endpoint")', 'server_instance_id', '$(_agmsg_sqlesc "$pulled_sid")', @@ -2858,7 +2873,7 @@ _remote_last_fatal_message() { # error message carrying a literal newline or other control character (a # stack-trace-shaped message, say) would otherwise break that (review, # #1487). - agmsg_sqlite_mem "SELECT json_extract('$escaped', '\$.message');" 2>/dev/null \ + _remote_sql "SELECT json_extract('$escaped', '\$.message');" 2>/dev/null \ | tr '\n\r\t\v\f' ' ' } @@ -3333,15 +3348,15 @@ _remote_mint_team_ids() { agmsg_lock_acquire "$TEAMS_DIR/$team" || return 1 cfg_json="$(cat "$cfg")" escaped="$(printf '%s' "$cfg_json" | LC_ALL=C sed "s/'/''/g")" - names="$(agmsg_sqlite_mem "SELECT key FROM json_each(json_extract('$escaped', '\$.agents'));")" - cfg_json="$(agmsg_sqlite_mem "SELECT json_set('$escaped', '\$.team_id', '$(compat_uuid7)');")" + names="$(_remote_sql "SELECT key FROM json_each(json_extract('$escaped', '\$.agents'));")" + cfg_json="$(_remote_sql "SELECT json_set('$escaped', '\$.team_id', '$(compat_uuid7)');")" while IFS= read -r name; do [ -n "$name" ] || continue mid="$(compat_uuid7)" escaped="$(printf '%s' "$cfg_json" | LC_ALL=C sed "s/'/''/g")" # A quoted path key ("name") lets a member name carry characters a bare # path token could not; the whole statement is a single-quoted SQL literal. - cfg_json="$(agmsg_sqlite_mem "SELECT json_set('$escaped', '\$.agents.\"$(printf '%s' "$name" | LC_ALL=C sed "s/'/''/g")\".member_id', '$mid');")" + cfg_json="$(_remote_sql "SELECT json_set('$escaped', '\$.agents.\"$(printf '%s' "$name" | LC_ALL=C sed "s/'/''/g")\".member_id', '$mid');")" done </dev/null || echo "") + top_type=$(_remote_sql "SELECT CASE WHEN json_valid('$escaped') THEN json_type('$escaped') ELSE 'invalid' END;" 2>/dev/null || echo "") [ "$top_type" = "object" ] } @@ -3988,16 +4003,16 @@ _remote_status_one() { local prev_row prev_endpoint prev_replaced prev_any=0 while IFS= read -r prev_row; do [ -n "$prev_row" ] || continue - prev_endpoint="$(agmsg_sqlite_mem \ + prev_endpoint="$(_remote_sql \ "SELECT json_extract('$(printf '%s' "$prev_row" | LC_ALL=C sed "s/'/''/g")', '\$.e');")" - prev_replaced="$(agmsg_sqlite_mem \ + prev_replaced="$(_remote_sql \ "SELECT json_extract('$(printf '%s' "$prev_row" | LC_ALL=C sed "s/'/''/g")', '\$.a');")" prev_endpoint="$(_remote_endpoint_display "$prev_endpoint")" prev_endpoint="${prev_endpoint//[[:cntrl:]]/}" prev_replaced="${prev_replaced//[[:cntrl:]]/}" prev_any=1 echo " previous: was bound to $prev_endpoint until $prev_replaced" - done < <(agmsg_sqlite_mem \ + done < <(_remote_sql \ "SELECT json_object('e', json_extract(value, '\$.endpoint'), 'a', coalesce(json_extract(value, '\$.replaced_at'), 'an unrecorded time')) FROM json_each(coalesce(json_extract('$(LC_ALL=C sed "s/'/''/g" "$cfg")', '\$.previous_bindings'), '[]'));") @@ -4769,7 +4784,7 @@ cmd_forget() { binding_revision_before="$(_remote_read_config_field "$cfg" '$.remote_binding.binding_revision')" if [ -z "$binding_revision_before" ] || [ "$binding_revision_before" = "null" ]; then escaped="$(LC_ALL=C sed "s/'/''/g" "$cfg")" - updated="$(agmsg_sqlite_mem \ + updated="$(_remote_sql \ "SELECT json_set('$escaped', '\$.remote_binding.binding_revision', 1);")" agmsg_write_atomic "$cfg" "$updated" binding_revision_before=1 @@ -4953,7 +4968,7 @@ _remote_snapshot_binding_for_update() { revision="$(_remote_read_config_field "$cfg" '$.remote_binding.binding_revision')" if [ -z "$revision" ] || [ "$revision" = "null" ]; then escaped="$(LC_ALL=C sed "s/'/''/g" "$cfg")" - updated="$(agmsg_sqlite_mem \ + updated="$(_remote_sql \ "SELECT json_set('$escaped', '\$.remote_binding.binding_revision', 1);")" agmsg_write_atomic "$cfg" "$updated" revision=1 diff --git a/tests/test_remote.bats b/tests/test_remote.bats index 935076b71..fccb43dd2 100644 --- a/tests/test_remote.bats +++ b/tests/test_remote.bats @@ -2797,6 +2797,7 @@ PY_BIND echo 'set -euo pipefail' echo 'SCRIPT_DIR="$1"; CONNECTION_ROOT="$2"; cfg="$3"' echo '. "$SCRIPT_DIR/lib/storage.sh"' + sed -n '/^_remote_sql() {/p' "$SCRIPTS/remote.sh" sed -n '/^_remote_read_config_field() {/,/^}/p' "$SCRIPTS/remote.sh" sed -n '/^_remote_holds_current_key() {/,/^}/p' "$SCRIPTS/remote.sh" echo '_remote_holds_current_key keyed "$cfg"' diff --git a/tests/test_remote_device.bats b/tests/test_remote_device.bats index be22725d1..dacd8ba55 100644 --- a/tests/test_remote_device.bats +++ b/tests/test_remote_device.bats @@ -450,6 +450,41 @@ marker_dir() { stop_engine cloned } +# Every external program the device flow starts, not only node: the approval's +# device code and the approved address are secrets, and an argument is readable +# by every process on the machine. The shell helpers that pick fields out of a +# server's answer used to put the whole answer in an sqlite3 argument. +spy_path() { + local spy="$BATS_TEST_TMPDIR/spy" tool real + mkdir -p "$spy" + for tool in sqlite3 node curl python3 sed grep cat tr cut head tail mktemp rm chmod age age-keygen; do + real="$(command -v "$tool")" || continue + printf '#!/bin/bash\nprintf "%%s\\n" "$*" >> %s/argv.log\nexec %s "$@"\n' "$BATS_TEST_TMPDIR" "$real" > "$spy/$tool" + chmod +x "$spy/$tool" + done + printf '%s' "$spy" +} + +@test "device connect: neither the device code nor the approved address is in any program's arguments" { + start_mock MOCK_FEATURES=device-approval + run env PATH="$(spy_path):$PATH" bash "$SCRIPTS/remote.sh" connect --endpoint "$ENDPOINT" testteam + [ "$status" -eq 0 ] + [ -s "$BATS_TEST_TMPDIR/argv.log" ] + if grep -q 'mocksecret' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi + if grep -q 'mockdevicecode' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi + stop_engine +} + +@test "device pull: neither the device code nor the approved address is in any program's arguments" { + start_mock MOCK_FEATURES=device-approval MOCK_TEAM_CIPHER_PROFILE=none + run env PATH="$(spy_path):$PATH" bash "$SCRIPTS/remote.sh" pull --endpoint "$ENDPOINT" --team-id "$PULL_TEAM_ID" cloned + [ "$status" -eq 0 ] + [ -s "$BATS_TEST_TMPDIR/argv.log" ] + if grep -q 'mocksecret' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi + if grep -q 'mockdevicecode' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi + stop_engine cloned +} + @test "remote.sh hands no endpoint to another program on its command line" { # The shell side of the same rule, which a node wrapper cannot see: a # remote-sync.sh call that names the endpoint in its arguments. The endpoint diff --git a/tests/test_remote_escrow.bats b/tests/test_remote_escrow.bats index 809edb85f..03e8c4dd7 100644 --- a/tests/test_remote_escrow.bats +++ b/tests/test_remote_escrow.bats @@ -467,6 +467,7 @@ path_without_age() { [ "$status" -eq 0 ] [ -s "$BATS_TEST_TMPDIR/argv.log" ] if grep -q 'AGE-SECRET-KEY-' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi + if grep -q 'mocksecret' "$BATS_TEST_TMPDIR/argv.log"; then return 1; fi } # Sends the epochs a server lacks, oldest first, and a run that stopped part way