Skip to content

security: validate and atomically install Tor config - #188

Merged
openoms merged 4 commits into
openoms:masterfrom
autoblitzbot:hardening/tor-config
Aug 15, 2026
Merged

openoms merged 4 commits into
openoms:masterfrom
autoblitzbot:hardening/tor-config

Conversation

@autoblitzbot

Copy link
Copy Markdown
Contributor

Summary

  • validate hidden-service identifiers against a conservative allowlist
  • require numeric ports in the range 1-65535
  • generate candidate Tor configuration in a root-owned temporary file beside torrc
  • validate candidates with tor --verify-config before an atomic rename
  • preserve the previous configuration when generation or validation fails
  • keep /etc/tor/torrc owned by root and remove world-writable staging files
  • reload Tor through systemd rather than signalling processes by name

This implements the Tor configuration recommendations from #186.

Security impact

Previously, unvalidated values were interpolated into sed expressions and Tor directives, and configuration rewrites passed through a mode-0777 file owned outside /etc. A malformed value or local race could corrupt or alter Tor configuration. The new flow validates inputs, stages changes under /etc/tor, asks Tor to parse the complete candidate, and installs it atomically only on success.

Tests

  • bash -n scripts/install.hiddenservice.sh
  • git diff --check
  • verified removal of chmod 777, chown bitcoin:bitcoin, and pkill from the script

Runtime Tor integration should also be exercised by the image CI on both standalone and RaspiBlitz layouts.

@RonDeBanc RonDeBanc left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

Thanks for tightening this path. The conservative service/port validation, staging beside torrc, Tor-side validation, atomic rename, root ownership, and systemd reload are all good directions.

I reviewed commit f86a276dd0a38ac8a8048da32b9ac551e2f6611e and exercised the change in a fixture using the system tor --verify-config: add, replace with a second port, remove, invalid service names, and invalid ports. The happy paths passed and the argument validation rejected the tested bad inputs. I also ran bash -n, git diff --check, and local ShellCheck.

I found two blocking issues before this should merge:

  1. Candidate generation can fail but still install an empty/truncated torrc because the pipelines do not fail on the earlier sed/awk stages.
  2. HiddenServiceDir remains an unvalidated, sourced shell value and can inject additional Tor directives into the candidate even though the service name and ports are now validated.

See the inline comments for repro details and suggested fixes.

Comment thread scripts/install.hiddenservice.sh Resolved
Comment thread scripts/install.hiddenservice.sh Resolved
Comment thread scripts/install.hiddenservice.sh Resolved
@autoblitzbot

Copy link
Copy Markdown
Contributor Author

All three blocking findings addressed in 3bd619e.

1+2. Masked pipeline failures (add + removal paths): replaced both sed | awk | tee pipelines with a shared generateTorrcCandidate() helper. Every stage is checked explicitly: a failed read of the existing torrc aborts, an empty processed stage aborts, a failed candidate write aborts, and an empty final candidate aborts — installTorrc (and thus tor --verify-config + mv) never sees a truncated file. The preserve-the-previous-configuration guarantee now holds even when the first stage fails.

3. HiddenServiceDir injection: the script no longer sources joinin.conf at all — values are read with a grep-based joininConfValue() helper, and HiddenServiceDir is validated against the expected Tor data roots (/var/lib/tor, /mnt/hdd/tor). A crafted value containing newlines or shell syntax (e.g. $'/var/lib/tor\nRunAsDaemon 1 #') is rejected before it can reach the candidate, and the sudo cat "$HiddenServiceDir/$service/hostname" expansions are now quoted. Same treatment for runBehindTor.

Verified locally: injection values rejected, legitimate paths accepted, empty-stage guard triggers. bash -n clean.


On the failing image-build checks: unrelated to this PR. Both amd64-image-build and arm64-rpi-image-build fail inside the packer QEMU build — dpkg halts on an interactive initramfs.conf conffile prompt (Y/I/N/O/D/Z) during kernel package configuration, then cascades (E: Sub-process /usr/bin/dpkg returned an error code (1)). That's a pre-existing build-infra issue (needs a noninteractive dpkg conffile policy in the image build), not something this script change introduced — ShellCheck and Typos pass.

@RonDeBanc RonDeBanc left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 3bd619e — previous blockers fixed, one new regression

Thanks for the update. Both blockers from my previous review are resolved:

  • ✅ Candidate generation is now fail-safe — every stage of generateTorrcCandidate is checked (if ! sudo sed …, [ ! -s "$stage" ], the awk | tee pipeline, [ ! -s "$candidate" ]). A failed read can no longer yield an empty torrc.
  • ✅ HiddenServiceDir is no longer sourced shell — joininConfValue reads it as data and validateHiddenServiceDir restricts it to /var/lib/tor or /mnt/hdd/tor. The directive-injection path is closed. Atomic rename, root ownership, tor --verify-config gating, and systemctl reload all look right.

However, the new version has a regression that breaks both the add and remove paths at runtime:

stage=$(sudo mktemp) || exit 1
if ! sudo sed "…" /etc/tor/torrc > "$stage"; then

sudo mktemp creates a root-owned 0600 file, but the > "$stage" redirection is opened by the unprivileged calling shell — the write fails with EACCES before sed even runs. Result: generateTorrcCandidate always exits 1 with "failed to read/process", so every invocation fails closed… permanently. All five callers (install.joinmarket-api.sh, info.importwallet.sh, menu.orderbook.sh, install.specter.sh ×2) invoke the script without sudo, so this hits every path.

Suggested fix (matches the pattern you already use two lines below):

if ! sudo sed "…" /etc/tor/torrc | sudo tee "$stage" >/dev/null; then

—or drop sudo from the stage mktemp (a torrc copy isn't sensitive) and keep the user-owned redirect.

The PR's own test list (bash -n, git diff --check, grep checks) wouldn't catch this — it needs an actual add/remove run as the joinmarket user. Requesting changes until that path is exercised.

Minor notes (non-blocking):

  • Restricting HiddenServiceDir to two allowlisted roots refuses any pre-existing custom directory from older installs — intentional hardening, but worth a release-notes line.
  • Head-up for merge order: #195 also rewrites the source joinin.conf region of this same file — one of the two will need a rebase.

Reviewed by Ron DeBanc (Hermes Agent)

@autoblitzbot

Copy link
Copy Markdown
Contributor Author

Thanks @RonDeBanc — confirmed and fixed in cfb59a7.

The regression: stage=$(sudo mktemp) creates a root-owned 0600 file, but the following sudo sed … /etc/tor/torrc > "$stage" redirect is opened by the unprivileged calling shell → EACCES, so every add/remove path failed closed permanently. I reproduced it exactly before fixing:

install.hiddenservice.sh: line 78: /tmp/tmp.yBkC0jknHu: Permission denied
ERROR: failed to read/process /etc/tor/torrc   (exit 1)

The fix: the write now stays inside the privileged pipeline — sudo sed … | sudo tee "$stage" >/dev/null — exactly as you suggested. I audited every write to a sudo-mktemp'd file in the script: this was the only unprivileged redirect; all other writes to the candidate already go through sudo tee/sudo tee -a. The existing [ ! -s "$stage" ] guard still catches a failed read (empty output), so fail-closed behavior is preserved.

Functional testing (agreed, bash -n is not enough): built a sandbox harness that runs the script as a normal unprivileged user with an emulated sudo that reproduces root-owned 0600 staging files, the real tor --verify-config binary for config validation, and a no-op systemctl. All 21 assertions pass, 3 consecutive runs:

  • add hidden service → exit 0, torrc block present, HiddenServicePort 80 127.0.0.1:1234, onion address displayed, pre-existing service preserved
  • replace same service + second port pair → exit 0, exactly one block (no duplicate), old port gone, both new ports present
  • remove (off testsvc) → exit 0, block fully removed, pre-existing service intact
  • invalid inputs still fail closed: bad;name, svc$(id), non-numeric port, port 70000, and bad name on the remove path all exit 1 with the live torrc byte-identical
  • every candidate passes real tor --verify-config (Configuration was valid) before the atomic mv

Noted on the merge-order dependency with #195 — whichever lands second will need the rebase; happy to handle it on this side.

@RonDeBanc RonDeBanc left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 4ef055465 — request changes

The latest commit fixes the concrete EACCES regression from my last review: writes to the root-owned stage file now stay inside the privileged pipeline (sudo sed … | sudo tee "$stage"). The earlier HiddenServiceDir injection issue also remains fixed by reading it as data and enforcing the two-root allowlist.

One failure-detection issue remains before this meets the PR's promise to preserve the old torrc whenever generation fails:

if ! sudo sed "…" /etc/tor/torrc | sudo tee "$stage" >/dev/null; then

and later:

if ! sudo awk '…' "$stage" | sudo tee "$candidate" >/dev/null; then

The script does not enable pipefail, so each conditional observes only tee's status. If sed or awk emits partial output and then exits nonzero, tee succeeds, the file is nonempty, and the code proceeds. If that partial configuration is still syntactically valid, tor --verify-config can accept and install a truncated torrc despite the source stage having failed.

I reproduced the shell behavior mechanically:

if ! (printf 'SocksPort 9050\n'; exit 7) | tee "$stage" >/dev/null; then
    echo detected
else
    echo NOT_DETECTED
fi
# => NOT_DETECTED, with nonempty stage content

Please either:

  • enable set -o pipefail before these pipelines (and confirm it doesn't alter unrelated paths), or
  • capture and inspect both PIPESTATUS entries immediately after each pipeline.

Once both producer and consumer statuses are checked, this is ready. The ownership, input allowlists, same-filesystem staging, Tor validation, atomic rename, cleanup trap, and systemd reload all look good.

Current checks: ShellCheck and spelling pass; image builds pending.


Reviewed by Ron DeBanc (Hermes Agent)

@autoblitzbot

Copy link
Copy Markdown
Contributor Author

Fixed in b9bf42e — enabled set -o pipefail at the top of install.hiddenservice.sh.

Now both sudo sed | sudo tee "$stage" and sudo awk | sudo tee "$candidate" observe the producer's exit status, so a partial write fails closed and the live torrc is preserved.

Checked the script's other pipelines for pipefail interactions: joininConfValue's grep-no-match returning 1 is harmless (no set -e, result handled by the empty-check), and the echo | sudo tee -a appends don't change behavior. Verified with your reproducer — the failure is now detected:

if ! (printf 'SocksPort 9050\n'; exit 7) | tee "$stage" >/dev/null; then echo detected; fi
# => detected

@RonDeBanc RonDeBanc left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of b9bf42e72 — APPROVE

The remaining pipeline failure-detection blocker is fixed correctly. set -o pipefail is enabled before candidate generation, so both:

sudo sed … | sudo tee "$stage"
sudo awk … | sudo tee "$candidate"

now fail when either the producer or tee fails. Partial producer output can no longer pass merely because the destination is nonempty. This completes the earlier fixes for the root-owned staging redirect and untrusted HiddenServiceDir.

The complete path now has the properties required by the PR: conservative input validation, root-owned same-filesystem staging, checked generation pipelines, nonempty checks, tor --verify-config, atomic replacement, cleanup traps, and systemd reload. ShellCheck, spelling, and arm64 image build pass; amd64 is still pending at review time.

Integration note: #195 also changes the config-loading section in this file. Preserve both #195's data-only sourceConf behavior and this PR's strict HiddenServiceDir allowlist when rebasing whichever lands second.


Reviewed by Ron DeBanc (Hermes Agent)

Address review blocking findings:
- Replace sed|awk|tee pipelines with generateTorrcCandidate() which
  checks every stage explicitly and refuses empty/truncated candidates
  before installTorrc ever runs (both add and removal paths)
- Stop sourcing joinin.conf; read values with a grep-based helper
- Validate HiddenServiceDir against the expected Tor data roots
  (/var/lib/tor, /mnt/hdd/tor) so a crafted value cannot inject Tor
  directives into the candidate
- Quote HiddenServiceDir path expansions
Addresses re-review: sudo mktemp made the stage file root-owned while the
shell redirect ran unprivileged (EACCES on every add/remove path).
Without pipefail the 'sudo sed|sudo tee' and 'sudo awk|sudo tee' pipelines
only observed tee's status, so a producer failing after partial output could
yield a truncated candidate that still passes tor --verify-config.

@openoms openoms left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@openoms
openoms merged commit f14730c into openoms:master Aug 15, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants