From 17eba139bbc7195b6a4521b2e99f9ce19eb83e44 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:31:59 +0330 Subject: [PATCH] init --- .editorconfig | 8 + .env.example | 36 ++ .github/ISSUE_TEMPLATE/bug_report.md | 23 ++ .github/PULL_REQUEST_TEMPLATE.md | 9 + .github/workflows/checks.yml | 16 + .gitignore | 29 ++ AGENTS.md | 80 +++++ CHANGELOG.md | 31 ++ CONTRIBUTING.md | 21 ++ LICENSE | 21 ++ Makefile | 23 ++ README.md | 74 ++++ SECURITY.md | 28 ++ THIRD_PARTY_NOTICES.md | 15 + cmd/routershelf/config.go | 109 ++++++ cmd/routershelf/config_test.go | 45 +++ cmd/routershelf/main.go | 338 ++++++++++++++++++ cmd/routershelf/main_test.go | 73 ++++ cmd/routershelf/static_test.go | 83 +++++ deploy/padavan/README.md | 7 + deploy/padavan/supervisor.example.sh | 116 ++++++ docs/architecture.md | 30 ++ docs/configuration.md | 70 ++++ docs/deployment-history.md | 80 +++++ docs/examples/status-dashboard.md | 289 +++++++++++++++ docs/getting-started.md | 153 ++++++++ docs/network-and-storage.md | 101 ++++++ docs/operations.md | 123 +++++++ docs/static-pages.md | 27 ++ examples/status-dashboard/README.md | 5 + examples/status-dashboard/config.example.sh | 8 + .../scripts/status-response.sh | 42 +++ .../scripts/status-service.sh | 28 ++ go.mod | 10 + go.sum | 6 + internal/theme/assets.go | 8 + internal/theme/nais/LICENSE | 21 ++ internal/theme/nais/autoindex.css | 197 ++++++++++ internal/theme/nais/autoindex.js | 153 ++++++++ internal/theme/nais/favicon.ico | Bin 0 -> 51478 bytes internal/theme/nais/favicon.png | Bin 0 -> 1840 bytes project.json | 32 ++ scripts/nat-plan.sh | 15 + 43 files changed, 2583 insertions(+) create mode 100644 .editorconfig create mode 100644 .env.example create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/checks.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 cmd/routershelf/config.go create mode 100644 cmd/routershelf/config_test.go create mode 100644 cmd/routershelf/main.go create mode 100644 cmd/routershelf/main_test.go create mode 100644 cmd/routershelf/static_test.go create mode 100644 deploy/padavan/README.md create mode 100644 deploy/padavan/supervisor.example.sh create mode 100644 docs/architecture.md create mode 100644 docs/configuration.md create mode 100644 docs/deployment-history.md create mode 100644 docs/examples/status-dashboard.md create mode 100644 docs/getting-started.md create mode 100644 docs/network-and-storage.md create mode 100644 docs/operations.md create mode 100644 docs/static-pages.md create mode 100644 examples/status-dashboard/README.md create mode 100644 examples/status-dashboard/config.example.sh create mode 100755 examples/status-dashboard/scripts/status-response.sh create mode 100755 examples/status-dashboard/scripts/status-service.sh create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/theme/assets.go create mode 100644 internal/theme/nais/LICENSE create mode 100644 internal/theme/nais/autoindex.css create mode 100644 internal/theme/nais/autoindex.js create mode 100644 internal/theme/nais/favicon.ico create mode 100644 internal/theme/nais/favicon.png create mode 100644 project.json create mode 100644 scripts/nat-plan.sh diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a4b824b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8b50ba8 --- /dev/null +++ b/.env.example @@ -0,0 +1,36 @@ +# Copy to .env and edit privately. The supervisor sources this as trusted shell code. +# Keep simple KEY=value assignments; no commands. Never commit your real .env. +RS_DOMAIN=files.example.com +RS_LAN_IP=192.168.50.1 +RS_LAN_SUBNET=192.168.50.0/24 +RS_LAN_INTERFACE=br0 +RS_USB_MOUNT=/media/DISK_ID +RS_PUBLIC_SUBDIR=public-storage +RS_SERVICE_SUBDIR=.public-share-service +RS_HTTP_PORT=10080 +RS_HTTPS_PORT=10443 +# false restricts the service to LAN sources; true admits forwarded public traffic. +RS_PUBLIC_ACCESS=false +RS_DROP_PRIVILEGES=true +RS_MEMORY_LIMIT=32MiB +RS_CPU_LIMIT=2 +RS_CHECK_INTERVAL=10 +RS_MIN_YEAR=2026 +RS_NTP_SERVER1=time.cloudflare.com +RS_NTP_SERVER2=pool.ntp.org +RS_SUPERVISOR_PATH=/etc/storage/public-share-service.sh +RS_RUNTIME_DIR=/tmp +# Optional absolute overrides; normally derive these from USB mount/subdirectories. +# RS_ROOT=/media/DISK_ID/public-storage +# RS_BINARY=/media/DISK_ID/.public-share-service/public-directory +# RS_CERT_CACHE=/media/DISK_ID/.public-share-service/certificates +# RS_CA_BUNDLE=/media/DISK_ID/.public-share-service/ca-certificates.pem +# Gateway values are for the NAT plan only; the supervisor does not change MikroTik. +RS_GATEWAY_LAN_IP=192.168.50.2 +RS_GATEWAY_PUBLIC_IP=203.0.113.10 +RS_GATEWAY_LAN_INTERFACE=ether1 +RS_GATEWAY_WAN_INTERFACE=pppoe-out1 +RS_PUBLIC_HTTP_PORT=80 +RS_PUBLIC_HTTPS_PORT=443 +RS_PUBLIC_SSH_PORT=222 +RS_SSH_TARGET_PORT=22 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..b3dae78 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,23 @@ +--- +name: Bug report +about: Report a reproducible RouterShelf issue using sanitized details +title: '' +labels: bug +assignees: '' +--- + +## Expected and actual behavior + +## Steps to reproduce + +## Target environment + +Router model, firmware/kernel, CPU architecture, Go version, and affected component. + +## Checks performed + +State whether the failure is on LAN, remote access, build, startup, or certificate renewal. + +## Sanitized diagnostics + +Do not include keys, certificate caches, passwords, real deployment addresses, full router exports, or private filenames/data. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7394bd5 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +## Problem and resulting behavior + +## Validation + +List checks actually performed and any target-hardware checks still outstanding. + +## Deployment impact + +Mention configuration changes, path changes, and rollback instructions when relevant. diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..23d983f --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,16 @@ +name: Checks +on: + push: + pull_request: +permissions: + contents: read +jobs: + test-and-cross-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.26.x' + - run: make test + - run: make build-mipsle diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..832d8d5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Private deployment settings, keys and operational data +config.sh +supervisor.private.sh +.env +.env.* +!/.env.example +*.key +*.pem +*.ovpn +certificates/ +*.rsc +*.backup +*.pcap +*.tar +*.tar.gz +*.zip +# IDE, runtime, builds, local results +.idea/ +.DS_Store +work/ +outputs/ +*.log +*.pid +*.before-* +dist/ +/public-directory* +/routershelf +/deploy/padavan/supervisor.private.sh +**/config.sh diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..95287a8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,80 @@ +# RouterShelf agent guide + +These instructions apply to the entire repository. Read any more specific `AGENTS.md` in a directory before changing files there. Follow the user's current request and existing session authorization when deciding the scope of work. + +## Project and entry points + +RouterShelf is a read-only Go HTTP/HTTPS server for USB storage on constrained Linux routers. It provides NAIS directory listings and static pages from the **same shared root**. The original deployment used Padavan-derived firmware and a MikroTik gateway; this is not universal firmware support. + +Read the relevant guide before changing a component: + +- `README.md` and `docs/architecture.md`: project overview and responsibilities. +- `docs/configuration.md`: environment configuration, precedence and reload. +- `docs/static-pages.md`: index precedence, inline assets and download behavior. +- `docs/getting-started.md` and `docs/operations.md`: installation, updates, rollback and removal. +- `SECURITY.md`: public access and filesystem boundaries. +- `docs/deployment-history.md`: observed results and outstanding hardware checks. + +## Repository layout + +- `cmd/routershelf/`: application, environment/flag parsing, handler and configuration tests. +- `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`. +- `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle. +- `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway. +- `.env.example`: tracked configuration template; `.env` is private and ignored. +- `examples/status-dashboard/`: independent historical BusyBox/Netcat example, with its guide in `docs/examples/`. Do not expose it using the public server's NAT rules. +- `docs/`, `.github/`, `Makefile`, `project.json`: documentation, CI, local commands and metadata. + +Keep changes in the appropriate layer. The Go server must not provision DHCP, change router NAT or configure FTP accounts. Preserve the upstream NAIS license and document local theme adaptations. + +## Configuration contract + +Network-specific domains, IPs, subnets, interfaces, ports, USB paths and runtime options belong in `RS_*` environment settings, not per-installation source edits. Use public placeholders in `.env.example` and documentation. Defaults should be generic and safe; the standalone Go listener defaults to loopback. + +The supervisor sources a trusted administrator-owned env file, normally `/etc/storage/routershelf.env`; `ROUTERSHELF_ENV_FILE` overrides its location. It exports values and passes application flags. The Go binary reads exported environment values but does **not** load or execute `.env` itself. CLI flags override environment defaults. Keep these representations consistent. + +When adding or changing a setting, update its parsing/validation, `.env.example`, the supervisor or NAT-plan consumer when applicable, and `docs/configuration.md`. Test precedence, derived paths and invalid input. Private configuration must never enter Git, public ZIPs, fixtures or diagnostic output. + +Editing env does not reload running processes. Config changes require transferring the private file and restarting the verified supervisor; they do not require rebuilding. Code and embedded-theme changes require a rebuild. Gateway changes are applied separately, guided by the NAT plan. + +## Behavior and security contracts + +Preserve these unless the user explicitly requests a change: + +- A directory with a readable regular `index.html` renders it before the NAIS listing. Without an index, the listing remains available. Directory slash redirects allow relative asset links. +- Direct HTML and recognized web assets are served inline with explicit MIME types. Other files remain attachment downloads. Listing links must not force HTML downloads. +- Static pages may run browser-side JavaScript and load assets; PHP/CGI/server-side code is never executed. Do not apply the listing's restrictive CSP to static pages in a way that breaks the documented behavior. +- Only GET/HEAD are allowed; retain HEAD and byte ranges. Public sharing has no authentication, and HTTPS alone does not make content private. +- Use `os.OpenRoot` confinement. Reject hidden paths, traversal, escaping symlinks and nonregular file responses. Keep names escaped and reserve `/_nais/` for bundled assets. +- Keep certificate keys/cache, CA bundle, binary, env and backups outside the shared root. exFAT mode bits do not isolate these from broadly authorized disk accounts. +- Keep domain whitelisting, outbound TLS validation, privilege dropping, connection bounds and timeouts. Do not treat `GOMEMLIMIT` as a hard memory quota. +- Modify only service-owned firewall rules. Preserve unrelated Internet NAT, SSH and firmware rules. Reconcile changes without opening the service unintentionally, and inspect fail-closed temporary blocks if commands fail. + +## Local development and verification + +Run from the repository root using Go 1.26 or a newer toolchain verified against the target kernel: + +```sh +make test # shell syntax, example config validation, Go tests +make check-shell # syntax only; does not execute deployment +make check-config # side-effect-free validation using .env.example +make build-mipsle # dist/routershelf-linux-mipsle, static Linux/MIPS LE soft-float +``` + +For a private configuration check, use `ROUTERSHELF_ENV_FILE=/absolute/path/to/.env sh deploy/padavan/supervisor.example.sh --check-config`. The env file is sourced shell code: do not load an untrusted one. `make nat-plan` reads private `.env` and prints deployment addresses; do not run it just to produce public diagnostics. + +There is no frontend build. Format Go with `gofmt`; use `.editorconfig` for other text. Keep deployment scripts compatible with the observed `/bin/sh` and BusyBox features. + +Use `testing` and `net/http/httptest` for meaningful behavior checks. For handler changes cover the affected filesystem boundaries, methods, headers, index precedence, inline MIME/disposition, fallback listing and byte ranges. For config changes cover env/flag precedence and validation. For shell-only changes run syntax and dry config checks; never start NTP or alter a live firewall merely to check formatting. Documentation-only edits normally need link/accuracy checks, not a cross-build or deployment. + +A successful cross-build is not a kernel-compatibility, reboot, renewal or load test. Record actual checks and unresolved limits. Future certificate renewal and full reboot claims require observed target results. + +## Live deployment and repository hygiene + +A repository edit does not automatically synchronize the router. Deploy only when requested or authorized by the session. Follow `docs/operations.md`: upload a new filename, preserve a known-good private backup, rename into place and restart the appropriate process. Verify PID command lines before signaling; wait for supervisor cleanup before starting another instance. Retain the certificate cache and shared data. + +Installed names such as `public-directory`, `public-share-service.sh` and `/tmp/public-share-*` are compatibility paths. Do not rename them just to match the repository name without a complete migration. USB binary updates do not require a flash save; changed `/etc/storage` env/scripts/hooks do on the observed firmware. Avoid unnecessary flash writes. + +Keep diffs focused and update user-facing documentation/metadata when behavior changes. Preserve user edits. Do not assume a remote, version, release or successful publication. Commit or publish only within the requested scope. Follow `.github/PULL_REQUEST_TEMPLATE.md` for descriptions: problem, resulting behavior, actual validation and deployment/rollback impact. + +Before publishing or refreshing a public archive, exclude private env, keys, cache, router exports, USB data, logs, screenshots and build output. Include `.env.example`. `.gitignore` does not protect secrets already tracked: inspect the export/staged files. Never claim the public sample supervisor was tested unchanged on every supported device. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e2433c4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +## Unreleased + +### Static pages + +- Render directory `index.html` and direct HTML requests from the existing shared root. +- Serve recognized web assets inline while retaining attachment downloads for other files. +- Keep read-only, path confinement, HTTPS and NAIS fallback behavior. + +### Environment configuration + +- Added a private `.env` and tracked `.env.example` for network, domain, USB, port, time, and runtime values. +- Go flags override environment defaults; the supervisor loads the same private configuration. +- Added side-effect-free config checks and a manually applied gateway NAT plan. +- Removed the public-mode marker dependency and reconciled owned firewall rules from configuration. + +### Repository organization + +- Named the project RouterShelf and moved the Go module to the repository root. +- Separated the application, embedded theme, Padavan deployment example, and legacy status dashboard. +- Added project metadata, architecture documentation, contribution guidance, third-party notices, local build commands, and CI templates. + +### Included implementation + +- Read-only USB directory listing and downloads, with constrained filesystem access. +- Automatic HTTPS certificate management, HTTP redirect/challenge handling, and persistent cache support. +- NAIS theme, copied links, DPL playlists, and clipboard feedback. +- Example USB supervisor, firewall hooks, and network/storage operations guides. + +These entries describe repository content; they do not announce a published release or new changes to the live router. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3675de9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,21 @@ +# Contributing to RouterShelf + +## Development + +Use Go 1.26 or a newer toolchain verified against the target kernel. From the repository root, run `make test` and `make build-mipsle`. Keep changes focused and describe user-visible behavior and validation. A desktop cross-build proves compilation, not target-kernel compatibility or successful boot persistence. + +Application changes belong in `cmd/routershelf`. Theme changes belong in `internal/theme/nais`; retain the upstream license and document local adaptations. Padavan-specific lifecycle rules belong in `deploy/padavan`. Keep the legacy status dashboard independent under `examples/status-dashboard`. + +Run `--check-config` against a private env to validate without touching firewall, processes, or the disk. Do not run deployment scripts on a device merely to test formatting. Inspect the real mount, firewall, interface names, and firmware hooks before any target installation. The example supervisor is administrator-controlled shell code, not an untrusted input format. + +## Verification + +For file-serving changes, check scope confinement, filename escaping, GET/HEAD, rejected write methods, and byte-range behavior. For TLS changes, verify trusted hostname validation, redirects, certificate-cache retention, and challenge routing. For UI changes, verify folder navigation, download, copied links, playlists, and mobile layout. + +Record which checks actually ran. Do not claim a reboot or certificate renewal passed unless it was observed. Include a rollback plan for changes that alter installed paths, supervision, or firewall rules. + +## Public data hygiene + +Never attach private keys, certificate caches, full router exports, USB files, usernames/passwords, public-IP deployment values, or unredacted logs/screenshots. Use the example subnet, documentation IP range, and `files.example.com` in public issues. A sanitized minimal configuration is more useful than a full device dump. + +Before the first publication, review staged files and metadata, configure the actual Git remote, and replace publication placeholders where needed. There is no automatic deploy or publish action in this project. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4b0c7cb --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RouterShelf contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6db7212 --- /dev/null +++ b/Makefile @@ -0,0 +1,23 @@ +GO ?= go +BINARY := dist/routershelf-linux-mipsle + +.PHONY: test build-mipsle check-shell check-config nat-plan + +test: check-shell check-config + $(GO) test ./... + +check-shell: + sh -n deploy/padavan/supervisor.example.sh + sh -n scripts/nat-plan.sh + sh -n examples/status-dashboard/scripts/status-service.sh + sh -n examples/status-dashboard/scripts/status-response.sh + +build-mipsle: + mkdir -p dist + GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o $(BINARY) ./cmd/routershelf + +check-config: + ROUTERSHELF_ENV_FILE="$(CURDIR)/.env.example" sh deploy/padavan/supervisor.example.sh --check-config + +nat-plan: + sh scripts/nat-plan.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..37b3e0c --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# RouterShelf + +**Read-only HTTPS file sharing from USB storage on a small Linux router.** + +RouterShelf serves a chosen directory with a dark [NAIS](https://github.com/meghdadfadaee/nais) listing, file downloads, copied links, and DPL playlists. It uses a small Go executable, automatic Let's Encrypt certificates, and an optional Padavan-style supervisor. A MikroTik gateway provides public port forwarding and LAN hairpin access. + +This repository includes the implementation and the practical guide for configuring, operating, backing up, and removing it. It also preserves an earlier LAN status-dashboard experiment as a standalone example. + +## Capabilities + +- Directory navigation and file downloads, with HEAD and byte-range support. +- Static pages from the same root: automatic `index.html` and inline HTML/CSS/JavaScript/assets. +- Automatic HTTPS for one configured hostname; HTTP challenge handling and HTTPS redirects. +- Embedded theme assets; no nginx, PHP runtime, database, or frontend build required. +- GET/HEAD only, hidden-path filtering, escaped filenames, and filesystem root confinement. +- Optional USB-aware restart supervision and dedicated IPv4/IPv6 firewall rules on the tested firmware. + +The public file service has **no authentication**. HTTPS protects transport; every file placed in the shared directory is available to anyone who can reach the service. Read [security boundaries](SECURITY.md) before deploying. + +## Get started + +1. Read the [network and storage guide](docs/network-and-storage.md) to identify the gateway, service host, USB mount, and access accounts. +2. Follow [installation and HTTPS setup](docs/getting-started.md), replacing every example value with private deployment settings. +3. Use the [operations guide](docs/operations.md) for health checks, backups, updates, rollback, and removal. + +Build and test from the repository root: + +```sh +make test +make build-mipsle +``` + +The cross-build writes `dist/routershelf-linux-mipsle`. The deployment guide explains its installed filename and router paths. Configure deployment without editing source or supervisor code: + +```sh +cp .env.example .env +# Edit .env privately, then validate it and print the gateway plan. +ROUTERSHELF_ENV_FILE="$PWD/.env" sh deploy/padavan/supervisor.example.sh --check-config +make nat-plan +``` + +Read [environment configuration](docs/configuration.md) for available values, precedence, installation, and reloading. `.env` is ignored by Git; `.env.example` is tracked. Gateway changes are still applied manually from the printed plan. + +See [static-page behavior](docs/static-pages.md) for index precedence and supported assets. + +## Repository layout + +```text +cmd/routershelf/ HTTP/HTTPS application and behavior tests +internal/theme/nais/ Licensed NAIS assets embedded in the executable +internal/theme/assets.go Asset embedding boundary +deploy/padavan/ Environment-driven firmware supervisor +examples/status-dashboard/ Separate legacy BusyBox/Netcat dashboard +docs/ Setup, operations, architecture, and deployment history +.github/ CI and issue/pull-request templates +scripts/nat-plan.sh Gateway plan derived from private environment +.env.example Public configuration template +Makefile Local checks and MIPS little-endian build +project.json Project identity and compatibility metadata +``` + +See [architecture](docs/architecture.md) for the separation between application, theme, firmware, and gateway responsibilities. The [deployment history](docs/deployment-history.md) records work completed on the original hardware and what remains unverified. The [status dashboard tutorial](docs/examples/status-dashboard.md) describes the earlier LAN-only example; it is not the public HTTPS server. + +## Compatibility and validation + +The original deployment used a Neterbit NW-651D with Padavan-derived firmware, Linux 3.4.113, BusyBox 1.24.2, about 128 MiB RAM, and a MIPS little-endian CPU. Its gateway was a MikroTik LHG5 running RouterOS 6.49.22. The tested compiler was Go 1.26.5. Other router firmware, CPU architectures, and newer toolchains require target testing. + +On the original device, HTTPS issuance, trusted downloads, HTTP redirects, read-only access checks, theme rendering, and a playlist download were checked. Full reboot, future certificate renewal, sustained load, and authenticated FTP transfer were not verified. The environment-driven supervisor is validated separately; hardware validation is recorded in the deployment history. + +## Contributing and publishing + +Read [CONTRIBUTING.md](CONTRIBUTING.md). Keep deployment configuration, certificate caches, keys, router exports, USB data, logs, and generated binaries out of Git. All tracked deployment examples use placeholder values. This local repository has no configured remote and has not been published. + +Project code is [MIT licensed](LICENSE). NAIS retains its [upstream MIT license](internal/theme/nais/LICENSE). Dependency and theme attribution is collected in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b41ca46 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,28 @@ +# RouterShelf security boundaries + +## Original LAN status dashboard + +The BusyBox/Netcat example has no authentication or TLS and runs with the SSH account's privileges. It is suitable only for a trusted, firewall-restricted LAN. Its paths are fixed and never evaluated as shell input, but serial Netcat handling and per-line reads can be monopolized by a hostile client. Do not expose it through WAN forwarding or a public tunnel. This dashboard was removed from the original router. + +Configuration is administrator-controlled shell code. Confirm command lines before trusting PID files. Firewall changes are not transactional; verify them after updates and never flush unrelated rules. + +## Public directory server + +Public access is intentionally unauthenticated and read-only. HTTPS encrypts transport; it does not restrict who may download the files. All current and future content in the selected root, including filenames and directory structure, is public. + +- Only GET/HEAD are accepted. HTML and recognized web assets are served inline with MIME sniffing disabled; other files remain attachment downloads. This is not an upload API or a server-side application runtime. +- `os.OpenRoot` constrains file access; dot-prefixed paths, traversal components, escaping symlinks, and nonregular files are rejected/omitted. Hidden files are not a substitute for storing secrets outside the root. +- The application drops privileges to UID/GID 65534. The custom `/_nais/` namespace serves only administrator-embedded theme assets; user files never become executable theme scripts. +- The HTTP fallback redirects to a fixed domain. ACME certificate issuance is limited to the configured domain. TLS validation remains enabled for outbound CA access. +- Timeouts, connection bounds, a listing cap, and a Go memory target reduce resource consumption but are not a complete denial-of-service defense or hard quota. Large traffic can overwhelm a small router or home uplink. +- The private ACME cache, backups, configuration, and binary live outside the public root. On the observed exFAT mount, Unix permission bits do not isolate them from broad FTP/SFTP disk access. Restrict accounts or change storage design for stronger isolation. +- Plain FTP exposes credentials/data to network observers. Prefer SFTP for remote authenticated transfer. A WAN SSH forward expands administrative reachability; keep key authentication and account policy under review. +- IPv6 publication is not implemented. Do not add AAAA records or remove IPv6 protections without a tested design. + +The original firmware/kernel are old. This project does not make an unsupported router safe for arbitrary Internet workloads. Keep software and keys maintained, back up privately, and limit publication to intentional public data. + +## Before publishing this repository + +Use example-only addresses and hostnames. Exclude private config, keys/certificates, cache directories, firmware exports, logs, disk data, screenshots, build outputs, and IDE state. Review staged files. Never paste full router dumps into an issue; provide sanitized diagnostic excerpts. + +See [operations](docs/operations.md) for backup, rollback, and removal instructions, and [deployment history](docs/deployment-history.md) for validation limits. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..b6271ec --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,15 @@ +# Third-party notices + +## NAIS + +Theme CSS, JavaScript, and favicons under `internal/theme/nais` derive from [NAIS](https://github.com/meghdadfadaee/nais). Copyright (c) 2026 Meghdad; MIT license retained in that directory. + +Local integration changes add explicit file markers, clipboard completion/error feedback, row alignment, mobile heading wrapping, and a read-only footer. These adaptations do not modify the user's original NAIS checkout. + +## Go modules + +The application uses `golang.org/x/crypto/acme/autocert` and its Go module dependencies. Versions and checksums are recorded in `go.mod` and `go.sum`. These modules carry their own licenses, commonly the Go project's BSD-style license; consult the license files supplied with each pinned module when distributing binaries. + +## Operational downloads + +The CA root bundle is obtained separately during deployment. It is not committed to this repository. Review its source and license separately when redistributing it. Runtime certificates and account keys are private deployment material, not source assets. diff --git a/cmd/routershelf/config.go b/cmd/routershelf/config.go new file mode 100644 index 0000000..657ef45 --- /dev/null +++ b/cmd/routershelf/config.go @@ -0,0 +1,109 @@ +package main + +import ( + "flag" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" +) + +type config struct { + root, listen, domain, httpListen, certCache string + drop bool +} + +func envDefault(key, fallback string) string { + if value := os.Getenv(key); value != "" { + return value + } + return fallback +} + +// Flags override the environment. The launcher loads the private .env file; +// the binary itself does not execute shell configuration files. +func parseConfig(args []string) (config, error) { + c := config{} + mount := os.Getenv("RS_USB_MOUNT") + root := os.Getenv("RS_ROOT") + cache := os.Getenv("RS_CERT_CACHE") + if mount != "" { + if root == "" { + root = filepath.Join(mount, envDefault("RS_PUBLIC_SUBDIR", "public-storage")) + } + if cache == "" { + cache = filepath.Join(mount, envDefault("RS_SERVICE_SUBDIR", ".public-share-service"), "certificates") + } + } + drop := false + if raw := os.Getenv("RS_DROP_PRIVILEGES"); raw != "" { + var err error + drop, err = strconv.ParseBool(raw) + if err != nil { + return c, fmt.Errorf("RS_DROP_PRIVILEGES must be a boolean") + } + } + ip := envDefault("RS_LAN_IP", "127.0.0.1") + httpsPort := envDefault("RS_HTTPS_PORT", "8888") + httpPort := envDefault("RS_HTTP_PORT", "10080") + fs := flag.NewFlagSet("routershelf", flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.StringVar(&c.root, "root", root, "Shared directory (RS_ROOT or RS_USB_MOUNT)") + fs.StringVar(&c.listen, "listen", net.JoinHostPort(ip, httpsPort), "Listener (RS_LAN_IP, RS_HTTPS_PORT)") + fs.StringVar(&c.domain, "domain", os.Getenv("RS_DOMAIN"), "HTTPS domain (RS_DOMAIN)") + fs.StringVar(&c.httpListen, "http-listen", net.JoinHostPort(ip, httpPort), "ACME HTTP listener (RS_HTTP_PORT)") + fs.StringVar(&c.certCache, "cert-cache", cache, "Persistent private cache (RS_CERT_CACHE)") + fs.BoolVar(&c.drop, "drop-privileges", drop, "Drop to uid/gid 65534 (RS_DROP_PRIVILEGES)") + if err := fs.Parse(args); err != nil { + return c, err + } + if len(fs.Args()) != 0 { + return c, fmt.Errorf("unexpected positional arguments") + } + if c.root == "" { + return c, fmt.Errorf("set RS_ROOT / RS_USB_MOUNT or -root") + } + for _, addr := range []string{c.listen, c.httpListen} { + host, port, err := net.SplitHostPort(addr) + if err != nil || net.ParseIP(host) == nil { + return c, fmt.Errorf("listeners must use numeric IP:port") + } + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 { + return c, fmt.Errorf("invalid listener port") + } + if c.drop && n < 1024 { + return c, fmt.Errorf("privilege drop requires internal ports >=1024") + } + } + if c.domain != "" { + if c.certCache == "" { + return c, fmt.Errorf("HTTPS requires RS_CERT_CACHE / RS_USB_MOUNT or -cert-cache") + } + if c.listen == c.httpListen { + return c, fmt.Errorf("HTTP and HTTPS listeners must differ") + } + if strings.ContainsAny(c.domain, "/: \t\r\n") { + return c, fmt.Errorf("domain must be a hostname without scheme or port") + } + r, err := filepath.Abs(c.root) + if err != nil { + return c, err + } + p, err := filepath.Abs(c.certCache) + if err != nil { + return c, err + } + rel, err := filepath.Rel(r, p) + if err != nil { + return c, err + } + if rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))) { + return c, fmt.Errorf("certificate cache must be outside shared root") + } + } + return c, nil +} diff --git a/cmd/routershelf/config_test.go b/cmd/routershelf/config_test.go new file mode 100644 index 0000000..1457381 --- /dev/null +++ b/cmd/routershelf/config_test.go @@ -0,0 +1,45 @@ +package main + +import "testing" + +func clearConfigEnv(t *testing.T) { + t.Helper() + for _, key := range []string{"RS_USB_MOUNT", "RS_ROOT", "RS_CERT_CACHE", "RS_PUBLIC_SUBDIR", "RS_SERVICE_SUBDIR", "RS_DROP_PRIVILEGES", "RS_LAN_IP", "RS_HTTPS_PORT", "RS_HTTP_PORT", "RS_DOMAIN"} { + t.Setenv(key, "") + } +} +func TestEnvConfigurationAndOverrides(t *testing.T) { + clearConfigEnv(t) + t.Setenv("RS_USB_MOUNT", "/media/example") + t.Setenv("RS_DOMAIN", "files.example.com") + t.Setenv("RS_LAN_IP", "192.0.2.1") + t.Setenv("RS_HTTPS_PORT", "10443") + t.Setenv("RS_HTTP_PORT", "10080") + t.Setenv("RS_DROP_PRIVILEGES", "true") + c, err := parseConfig(nil) + if err != nil { + t.Fatal(err) + } + if c.root != "/media/example/public-storage" || c.certCache != "/media/example/.public-share-service/certificates" || c.listen != "192.0.2.1:10443" || !c.drop { + t.Fatalf("incorrect derived configuration: %+v", c) + } + c, err = parseConfig([]string{"-listen", "127.0.0.1:9443", "-domain", "other.example.com"}) + if err != nil || c.listen != "127.0.0.1:9443" || c.domain != "other.example.com" { + t.Fatalf("flags did not override env: %+v %v", c, err) + } +} +func TestRejectUnsafeConfiguration(t *testing.T) { + for _, tc := range []struct{ key, value string }{ + {"RS_HTTPS_PORT", "0"}, {"RS_DROP_PRIVILEGES", "perhaps"}, {"RS_DOMAIN", "https://files.example.com"}, {"RS_CERT_CACHE", "/media/example/public-storage/keys"}, + } { + t.Run(tc.key, func(t *testing.T) { + clearConfigEnv(t) + t.Setenv("RS_USB_MOUNT", "/media/example") + t.Setenv("RS_DOMAIN", "files.example.com") + t.Setenv(tc.key, tc.value) + if _, err := parseConfig(nil); err == nil { + t.Fatal("unsafe config accepted") + } + }) + } +} diff --git a/cmd/routershelf/main.go b/cmd/routershelf/main.go new file mode 100644 index 0000000..f9a6849 --- /dev/null +++ b/cmd/routershelf/main.go @@ -0,0 +1,338 @@ +package main + +import ( + "bytes" + "crypto/tls" + "fmt" + "html/template" + "io" + "log" + "mime" + "net" + "net/http" + "net/url" + "os" + "path" + "sort" + "strings" + "sync" + "syscall" + "time" + + "golang.org/x/crypto/acme/autocert" + + "routershelf/internal/theme" +) + +type entry struct { + Name, Size, Modified string + Link template.URL + Dir bool + Inline bool +} +type page struct { + Path string + Parent template.URL + Entries []entry + Truncated bool +} + +var listing = template.Must(template.New("listing").Parse(`Index of {{.Path}}

Index of {{.Path}}

{{if .Parent}}../
+{{end}}{{range .Entries}}{{.Name}}{{if .Dir}}/{{end}}  {{.Modified}}  {{.Size}}
+{{else}}This folder is empty.
+{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
+{{end}}
`)) + +func escapedPath(p string) template.URL { + parts := strings.Split(p, "/") + for i := range parts { + parts[i] = url.PathEscape(parts[i]) + } + return template.URL(strings.Join(parts, "/")) +} +func sizeLabel(n int64) string { + if n < 1024 { + return fmt.Sprintf("%d B", n) + } + for _, u := range []struct { + n int64 + s string + }{{1 << 30, "GiB"}, {1 << 20, "MiB"}, {1 << 10, "KiB"}} { + if n >= u.n { + return fmt.Sprintf("%.1f %s", float64(n)/float64(u.n), u.s) + } + } + return "" +} +func handler(rootPath string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'") + w.Header().Set("Referrer-Policy", "no-referrer") + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "Read-only service", 405) + return + } + if strings.HasPrefix(r.URL.Path, "/_nais/") { + name := strings.TrimPrefix(r.URL.Path, "/_nais/") + types := map[string]string{"autoindex.css": "text/css; charset=utf-8", "autoindex.js": "text/javascript; charset=utf-8", "favicon.ico": "image/x-icon", "favicon.png": "image/png"} + contentType, ok := types[name] + if !ok { + http.NotFound(w, r) + return + } + data, err := theme.Files.ReadFile("nais/" + name) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", contentType) + w.Header().Set("Cache-Control", "no-cache") + http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(data)) + return + } + p := r.URL.Path + if strings.ContainsAny(p, "\\\x00\r\n") { + http.Error(w, "Invalid path", 400) + return + } + for _, part := range strings.Split(p, "/") { + if strings.HasPrefix(part, ".") { + http.NotFound(w, r) + return + } + } + name := strings.TrimPrefix(p, "/") + if name == "" { + name = "." + } + root, err := os.OpenRoot(rootPath) + if err != nil { + http.Error(w, "Storage unavailable", 503) + return + } + defer root.Close() + f, err := root.Open(name) + if err != nil { + http.NotFound(w, r) + return + } + defer f.Close() + info, err := f.Stat() + if err != nil { + http.NotFound(w, r) + return + } + if info.IsDir() { + if !strings.HasSuffix(p, "/") { + http.Redirect(w, r, string(escapedPath(p+"/")), 301) + return + } + index, indexErr := root.Open(path.Join(name, "index.html")) + if indexErr == nil { + defer index.Close() + indexInfo, statErr := index.Stat() + if statErr == nil && indexInfo.Mode().IsRegular() { + serveFile(w, r, "index.html", indexInfo, index) + return + } + } + rows, err := f.ReadDir(5000) + if err != nil && err != io.EOF { + http.Error(w, "Cannot list folder", 500) + return + } + pg := page{Path: p, Truncated: len(rows) == 5000} + if p != "/" { + parent := path.Dir(strings.TrimSuffix(p, "/")) + if parent != "/" { + parent += "/" + } + pg.Parent = escapedPath(parent) + } + for _, row := range rows { + if strings.HasPrefix(row.Name(), ".") { + continue + } + st, err := root.Stat(path.Join(name, row.Name())) + if err != nil || (!st.IsDir() && !st.Mode().IsRegular()) { + continue + } + link := p + row.Name() + label := sizeLabel(st.Size()) + if st.IsDir() { + link += "/" + label = "—" + } + pg.Entries = append(pg.Entries, entry{Name: row.Name(), Size: label, Modified: st.ModTime().UTC().Format("2006-01-02 15:04 UTC"), Link: escapedPath(link), Dir: st.IsDir(), Inline: inlineType(row.Name()) != ""}) + } + sort.Slice(pg.Entries, func(i, j int) bool { + if pg.Entries[i].Dir != pg.Entries[j].Dir { + return pg.Entries[i].Dir + } + return pg.Entries[i].Name < pg.Entries[j].Name + }) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + if r.Method == http.MethodGet { + if err := listing.Execute(w, pg); err != nil { + log.Print("listing response interrupted") + } + } + return + } + if !info.Mode().IsRegular() { + http.NotFound(w, r) + return + } + serveFile(w, r, name, info, f) + }) +} + +type boundedListener struct { + net.Listener + slots chan struct{} +} +type boundedConn struct { + net.Conn + release func() + once sync.Once +} + +func (c *boundedConn) Close() error { err := c.Conn.Close(); c.once.Do(c.release); return err } +func (l *boundedListener) Accept() (net.Conn, error) { + l.slots <- struct{}{} + c, e := l.Listener.Accept() + if e != nil { + <-l.slots + return nil, e + } + return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil +} +func main() { + cfg, err := parseConfig(os.Args[1:]) + if err != nil { + log.Fatal(err) + } + root, addr, domain, httpAddr, cache, drop := &cfg.root, &cfg.listen, &cfg.domain, &cfg.httpListen, &cfg.certCache, &cfg.drop + r, e := os.OpenRoot(*root) + if e != nil { + log.Fatal("public directory unavailable") + } + r.Close() + if *drop { + if e = syscall.Setgroups([]int{}); e != nil { + log.Fatal(e) + } + if e = syscall.Setgid(65534); e != nil { + log.Fatal(e) + } + if e = syscall.Setuid(65534); e != nil { + log.Fatal(e) + } + } + l, e := net.Listen("tcp4", *addr) + if e != nil { + log.Fatal(e) + } + contentHandler := handler(*root) + var manager *autocert.Manager + if *domain != "" { + if *cache == "" { + log.Fatal("-cert-cache is required for HTTPS") + } + manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(*domain), Cache: autocert.DirCache(*cache)} + redirect := redirectHandler(*domain) + hl, err := net.Listen("tcp4", *httpAddr) + if err != nil { + log.Fatal(err) + } + hs := &http.Server{Handler: manager.HTTPHandler(redirect), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024} + go func() { log.Fatal(hs.Serve(&boundedListener{hl, make(chan struct{}, 16)})) }() + } + s := &http.Server{Handler: contentHandler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Minute, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024} + log.Printf("Read-only public directory listening on %s (domain=%s)", *addr, *domain) + if manager != nil { + s.TLSConfig = manager.TLSConfig() + s.TLSConfig.MinVersion = tls.VersionTLS12 + // HTTP/1.1 plus ACME ALPN; bound connections remain effective for all clients. + s.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"} + log.Fatal(s.ServeTLS(&boundedListener{l, make(chan struct{}, 32)}, "", "")) + } + log.Fatal(s.Serve(&boundedListener{l, make(chan struct{}, 32)})) +} + +func redirectHandler(domain string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + host := r.Host + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + if !strings.EqualFold(host, domain) { + http.Error(w, "Unknown host", http.StatusMisdirectedRequest) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", "GET, HEAD") + http.Error(w, "Read-only service", 405) + return + } + target := url.URL{Scheme: "https", Host: domain, Path: r.URL.Path, RawPath: r.URL.RawPath, RawQuery: r.URL.RawQuery} + http.Redirect(w, r, target.String(), http.StatusPermanentRedirect) + }) +} + +// Static assets are identified explicitly; unrecognized files remain downloads. +func inlineType(name string) string { + switch strings.ToLower(path.Ext(name)) { + case ".html", ".htm": + return "text/html; charset=utf-8" + case ".css": + return "text/css; charset=utf-8" + case ".js", ".mjs": + return "text/javascript; charset=utf-8" + case ".json", ".map": + return "application/json" + case ".png": + return "image/png" + case ".jpg", ".jpeg": + return "image/jpeg" + case ".gif": + return "image/gif" + case ".webp": + return "image/webp" + case ".avif": + return "image/avif" + case ".svg": + return "image/svg+xml" + case ".ico": + return "image/x-icon" + case ".woff": + return "font/woff" + case ".woff2": + return "font/woff2" + case ".ttf": + return "font/ttf" + case ".otf": + return "font/otf" + case ".wasm": + return "application/wasm" + default: + return "" + } +} +func serveFile(w http.ResponseWriter, r *http.Request, name string, info os.FileInfo, f io.ReadSeeker) { + contentType := inlineType(name) + if contentType == "" { + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": info.Name()})) + } else { + w.Header().Set("Content-Type", contentType) + w.Header().Del("Content-Disposition") + // Published static pages may use inline scripts/styles and external assets. + // Directory listings retain their stricter policy; no server-side code runs. + w.Header().Set("Content-Security-Policy", "object-src 'none'; frame-ancestors 'none'; base-uri 'self'") + } + http.ServeContent(w, r, info.Name(), info.ModTime(), f) +} diff --git a/cmd/routershelf/main_test.go b/cmd/routershelf/main_test.go new file mode 100644 index 0000000..1edf6b0 --- /dev/null +++ b/cmd/routershelf/main_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFileScopeAndMethods(t *testing.T) { + root := t.TempDir() + os.WriteFile(filepath.Join(root, "test.txt"), []byte("test"), 0600) + os.WriteFile(filepath.Join(root, ".secret"), []byte("secret"), 0600) + outside := filepath.Join(t.TempDir(), "outside") + os.WriteFile(outside, []byte("private"), 0600) + os.Symlink(outside, filepath.Join(root, "escape.txt")) + os.Mkdir(filepath.Join(root, "sub"), 0700) + os.WriteFile(filepath.Join(root, "<&.txt"), []byte("safe"), 0600) + h := handler(root) + for _, tc := range []struct { + method, url string + code int + body string + }{{"GET", "/", 200, "test.txt"}, {"GET", "/test.txt", 200, "test"}, {"HEAD", "/test.txt", 200, ""}, {"GET", "/.secret", 404, ""}, {"GET", "/../outside", 404, ""}, {"GET", "/%2e%2e/outside", 404, ""}, {"GET", "/escape.txt", 404, ""}, {"GET", "/sub/", 200, "This folder is empty"}, {"PUT", "/new.txt", 405, ""}, {"POST", "/", 405, ""}, {"DELETE", "/test.txt", 405, ""}} { + w := httptest.NewRecorder() + r := httptest.NewRequest(tc.method, tc.url, nil) + h.ServeHTTP(w, r) + if w.Code != tc.code { + t.Fatalf("%s %s: %d", tc.method, tc.url, w.Code) + } + if tc.body != "" && !strings.Contains(w.Body.String(), tc.body) { + t.Fatalf("unexpected response %s", tc.url) + } + if tc.method == "HEAD" && w.Body.Len() != 0 { + t.Fatal("HEAD body") + } + } + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) + if strings.Contains(w.Body.String(), ".secret") || strings.Contains(w.Body.String(), "escape.txt") { + t.Fatal("private entry listed") + } + if !strings.Contains(w.Body.String(), "<&.txt") { + t.Fatal("filename not escaped") + } + r := httptest.NewRequest("GET", "/test.txt", nil) + r.Header.Set("Range", "bytes=1-2") + w = httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != 206 || w.Body.String() != "es" { + t.Fatal("range download failed") + } +} + +func TestHTTPSRedirect(t *testing.T) { + h := redirectHandler("files.example.com") + for _, tc := range []struct { + target, method string + status int + location string + }{ + {"http://files.example.com/folder/a%20b.txt?q=1", "GET", 308, "https://files.example.com/folder/a%20b.txt?q=1"}, + {"http://other.example/", "GET", 421, ""}, + {"http://files.example.com/", "POST", 405, ""}, + } { + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(tc.method, tc.target, nil)) + if w.Code != tc.status || w.Header().Get("Location") != tc.location { + t.Errorf("%s: status=%d location=%q", tc.target, w.Code, w.Header().Get("Location")) + } + } +} diff --git a/cmd/routershelf/static_test.go b/cmd/routershelf/static_test.go new file mode 100644 index 0000000..217bd12 --- /dev/null +++ b/cmd/routershelf/static_test.go @@ -0,0 +1,83 @@ +package main + +import ( + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestStaticPagesAndAssets(t *testing.T) { + root := t.TempDir() + os.Mkdir(filepath.Join(root, "site"), 0700) + files := map[string]string{"site/index.html": "

Home

", "page.HTML": "

Direct

", "site/app.js": "console.log('ok')", "site/style.css": "h1{color:red}", "archive.zip": "archive", "script.php": "Home", 200, false}, + {"/site/index.html", "text/html; charset=utf-8", "

Home

", 200, false}, + {"/page.HTML", "text/html; charset=utf-8", "

Direct

", 200, false}, + {"/site/app.js", "text/javascript; charset=utf-8", "console.log('ok')", 200, false}, + {"/site/style.css", "text/css; charset=utf-8", "h1{color:red}", 200, false}, + {"/archive.zip", "application/octet-stream", "archive", 200, true}, + {"/script.php", "application/octet-stream", "Root index"), 0600) + w = httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) + if w.Body.String() != "

Root index

" { + t.Fatal("root index not served") + } +} diff --git a/deploy/padavan/README.md b/deploy/padavan/README.md new file mode 100644 index 0000000..cf14139 --- /dev/null +++ b/deploy/padavan/README.md @@ -0,0 +1,7 @@ +# Padavan deployment + +The supervisor loads the private `/etc/storage/routershelf.env` file. Use the unchanged script and configure `.env`, not a per-network copy of shell source. + +Copy `.env.example` to `.env` in the repository root. Run `--check-config` with `ROUTERSHELF_ENV_FILE` pointing to that file before installation. See [environment configuration](../../docs/configuration.md), [installation](../../docs/getting-started.md), and [operations](../../docs/operations.md). + +The script targets the observed firmware hooks and firewall commands. No project edit automatically changes a running router. diff --git a/deploy/padavan/supervisor.example.sh b/deploy/padavan/supervisor.example.sh new file mode 100644 index 0000000..7ffc728 --- /dev/null +++ b/deploy/padavan/supervisor.example.sh @@ -0,0 +1,116 @@ +#!/bin/sh +# RouterShelf Padavan supervisor. Only load administrator-owned configuration. +set -eu +ENV_FILE=${ROUTERSHELF_ENV_FILE:-/etc/storage/routershelf.env} +[ -r "$ENV_FILE" ] || { echo "RouterShelf env file missing: $ENV_FILE" >&2; exit 1; } +set -a +. "$ENV_FILE" +set +a +: "${RS_DOMAIN:?RS_DOMAIN is required}" "${RS_LAN_IP:?RS_LAN_IP is required}" "${RS_USB_MOUNT:?RS_USB_MOUNT is required}" +: "${RS_LAN_SUBNET:?RS_LAN_SUBNET is required}" "${RS_LAN_INTERFACE:?RS_LAN_INTERFACE is required}" +RS_PUBLIC_SUBDIR=${RS_PUBLIC_SUBDIR:-public-storage} +RS_SERVICE_SUBDIR=${RS_SERVICE_SUBDIR:-.public-share-service} +RS_ROOT=${RS_ROOT:-$RS_USB_MOUNT/$RS_PUBLIC_SUBDIR} +RS_BINARY=${RS_BINARY:-$RS_USB_MOUNT/$RS_SERVICE_SUBDIR/public-directory} +RS_CERT_CACHE=${RS_CERT_CACHE:-$RS_USB_MOUNT/$RS_SERVICE_SUBDIR/certificates} +RS_CA_BUNDLE=${RS_CA_BUNDLE:-$RS_USB_MOUNT/$RS_SERVICE_SUBDIR/ca-certificates.pem} +RS_HTTP_PORT=${RS_HTTP_PORT:-10080} +RS_HTTPS_PORT=${RS_HTTPS_PORT:-10443} +RS_PUBLIC_ACCESS=${RS_PUBLIC_ACCESS:-false} +RS_DROP_PRIVILEGES=${RS_DROP_PRIVILEGES:-true} +RS_CHECK_INTERVAL=${RS_CHECK_INTERVAL:-10} +RS_MIN_YEAR=${RS_MIN_YEAR:-2026} +RS_MEMORY_LIMIT=${RS_MEMORY_LIMIT:-32MiB} +RS_CPU_LIMIT=${RS_CPU_LIMIT:-2} +RS_NTP_SERVER1=${RS_NTP_SERVER1:-time.cloudflare.com} +RS_NTP_SERVER2=${RS_NTP_SERVER2:-pool.ntp.org} +RS_SUPERVISOR_PATH=${RS_SUPERVISOR_PATH:-/etc/storage/public-share-service.sh} +RS_RUNTIME_DIR=${RS_RUNTIME_DIR:-/tmp} +SUP_PID=$RS_RUNTIME_DIR/public-share-supervisor.pid +CHILD_PID=$RS_RUNTIME_DIR/public-share-child.pid +LOG=$RS_RUNTIME_DIR/public-share.log +fail() { echo "RouterShelf: $*" >&2; exit 1; } +for port in "$RS_HTTP_PORT" "$RS_HTTPS_PORT"; do + case "$port" in ''|*[!0-9]*) fail 'Ports must be integers';; esac + [ "$port" -ge 1024 ] && [ "$port" -le 65535 ] || fail 'Internal ports must be 1024..65535' +done +[ "$RS_HTTP_PORT" != "$RS_HTTPS_PORT" ] || fail 'HTTP and HTTPS ports must differ' +case "$RS_PUBLIC_ACCESS" in true|false) ;; *) fail 'RS_PUBLIC_ACCESS must be true or false';; esac +case "$RS_DROP_PRIVILEGES" in true|false) ;; *) fail 'RS_DROP_PRIVILEGES must be true or false';; esac +for number in "$RS_CHECK_INTERVAL" "$RS_MIN_YEAR" "$RS_CPU_LIMIT"; do + case "$number" in ''|*[!0-9]*) fail 'Interval, year and CPU count must be integers';; esac + [ "$number" -gt 0 ] || fail 'Interval, year and CPU count must be positive' +done +for dir in "$RS_USB_MOUNT" "$RS_ROOT" "$RS_CERT_CACHE" "$RS_BINARY" "$RS_CA_BUNDLE" "$RS_SUPERVISOR_PATH" "$RS_RUNTIME_DIR"; do + case "$dir" in /*) ;; *) fail 'Deployment paths must be absolute';; esac + case "$dir" in *' '*|*'..'* ) fail 'Deployment paths must not contain spaces or ..';; esac +done +case "$RS_CERT_CACHE/" in "$RS_ROOT/"*) fail 'Certificate cache must be outside shared root';; esac +export ROUTERSHELF_ENV_FILE="$ENV_FILE" +export RS_ROOT RS_CERT_CACHE RS_DROP_PRIVILEGES +rules() { + # Block service ports during chain replacement; leave blocks in place on failure. + old_ports=$(iptables -S INPUT | awk '/-j NB_PUBLIC$/ {for(i=1;i<=NF;i++) if($i=="--dport") print $(i+1)}') || return 1 + ports=$(printf '%s\n%s\n%s\n' "$old_ports" "$RS_HTTP_PORT" "$RS_HTTPS_PORT" | sort -u) + for port in $ports; do + [ -n "$port" ] || continue + iptables -I INPUT 1 -p tcp --dport "$port" -j DROP || return 1 + done + if ! iptables -S NB_PUBLIC >/dev/null 2>&1; then iptables -N NB_PUBLIC || return 1; fi + iptables -F NB_PUBLIC || return 1 + if [ "$RS_PUBLIC_ACCESS" = true ]; then + iptables -A NB_PUBLIC -i "$RS_LAN_INTERFACE" -d "$RS_LAN_IP" -j ACCEPT || return 1 + else + iptables -A NB_PUBLIC -i "$RS_LAN_INTERFACE" -s "$RS_LAN_SUBNET" -d "$RS_LAN_IP" -j ACCEPT || return 1 + fi + iptables -A NB_PUBLIC -j DROP || return 1 + for port in $old_ports; do + iptables -D INPUT -p tcp --dport "$port" -j NB_PUBLIC || return 1 + done + for port in "$RS_HTTP_PORT" "$RS_HTTPS_PORT"; do + iptables -I INPUT 1 -p tcp --dport "$port" -j NB_PUBLIC || return 1 + ip6tables -S INPUT | grep -q -- "--dport $port -j DROP" || ip6tables -I INPUT 1 -p tcp --dport "$port" -j DROP || return 1 + done + for port in $ports; do + [ -n "$port" ] || continue + iptables -D INPUT -p tcp --dport "$port" -j DROP || return 1 + done +} +case "${1:-}" in + --check-config) echo 'RouterShelf configuration valid'; exit 0 ;; + --firewall) rules; exit $? ;; + --run) + child= + cleanup() { [ -z "$child" ] || kill "$child" 2>/dev/null || :; rm -f "$CHILD_PID" "$SUP_PID"; } + trap cleanup EXIT + trap 'exit 0' TERM INT + while :; do + if awk -v mount="$RS_USB_MOUNT" '$2==mount {found=1} END{exit !found}' /proc/mounts && [ -d "$RS_ROOT" ] && [ -x "$RS_BINARY" ]; then + if [ -z "$child" ] || ! kill -0 "$child" 2>/dev/null; then + [ "$(date +%Y)" -ge "$RS_MIN_YEAR" ] || { sleep "$RS_CHECK_INTERVAL"; continue; } + rules || { sleep "$RS_CHECK_INTERVAL"; continue; } + SSL_CERT_FILE="$RS_CA_BUNDLE" GOMEMLIMIT="$RS_MEMORY_LIMIT" GOMAXPROCS="$RS_CPU_LIMIT" "$RS_BINARY" \ + -root "$RS_ROOT" -listen "$RS_LAN_IP:$RS_HTTPS_PORT" -http-listen "$RS_LAN_IP:$RS_HTTP_PORT" \ + -domain "$RS_DOMAIN" -cert-cache "$RS_CERT_CACHE" -drop-privileges="$RS_DROP_PRIVILEGES" & + child=$!; echo "$child" > "$CHILD_PID" + fi + elif [ -n "$child" ]; then + kill "$child" 2>/dev/null || :; child=; rm -f "$CHILD_PID" + fi + sleep "$RS_CHECK_INTERVAL" + done ;; + *) + if ! pidof ntpd >/dev/null; then + ln -sf /bin/busybox "$RS_RUNTIME_DIR/ntpd" + "$RS_RUNTIME_DIR/ntpd" -p "$RS_NTP_SERVER1" -p "$RS_NTP_SERVER2" + fi + rules || exit 1 + if [ -f "$SUP_PID" ]; then + pid=$(cat "$SUP_PID") + case "$pid" in ''|*[!0-9]*) ;; *) + if [ -r "/proc/$pid/cmdline" ] && tr '\000' ' ' < "/proc/$pid/cmdline" | grep -F "$RS_SUPERVISOR_PATH --run" >/dev/null; then exit 0; fi ;; + esac + fi + nohup "$RS_SUPERVISOR_PATH" --run "$LOG" 2>&1 & + echo $! > "$SUP_PID" ;; +esac diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..7489355 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,30 @@ +# Architecture + +RouterShelf has four operational layers: + +| Layer | Responsibility | Repository location | +| --- | --- | --- | +| Go application | Safe directory reads, HTTP responses, TLS and ACME, connection limits, privilege drop | `cmd/routershelf` | +| Embedded theme | NAIS styling, favicon, copied links, playlist generation | `internal/theme` | +| Router lifecycle | USB checks, process restart, time startup, host firewall hooks, flash persistence | `deploy/padavan` | +| Network gateway | Public DNS destination, destination NAT, LAN hairpin reply routing | Configuration documented in `docs/getting-started.md` | + +```text +Browser -> gateway TCP 80/443 -> storage host TCP 10080/10443 + | + RouterShelf + / \ + shared directory private ACME cache + | + USB filesystem +``` + +The gateway plan is generated from `.env` by `scripts/nat-plan.sh`, rather than auto-applied: changing a gateway requires matching its actual interfaces, existing NAT/filter rules, and public address. The Go application does not change routing, configure DHCP, or provision FTP accounts. + +The `deploy/padavan` script loads a private environment file for one firmware family. Its installed names remain `public-share-service.sh`, `public-directory`, and `/tmp/public-share-*` for compatibility with the existing deployed system and instructions. Renaming the repository is not a live-router migration. + +The legacy dashboard is a separate Netcat/shell example, with its own configuration and security assumptions. Its code remains in `examples/status-dashboard` and its guide in `docs/examples/status-dashboard.md`. It was removed from the original router and must never inherit the public server's port-forwarding policy. + +The Go module path is currently `routershelf`, a local standalone module identity. If a real repository remote is established later, change the module path and the `routershelf/internal/theme` import together if a hosted module path is desired. No remote namespace is assumed. + +Read [setup](getting-started.md), [operations](operations.md), and [security](../SECURITY.md) for configuration and maintenance boundaries. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..a2d057c --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,70 @@ +# Environment configuration + +Network-specific settings live in a private `.env` file. The public `.env.example` contains only illustrative values. Changing a domain, subnet, USB mount, or port does not require editing Go or shell source and does not require rebuilding the application. + +## Loading and precedence + +The Padavan supervisor loads `/etc/storage/routershelf.env` by default. Override the path with `ROUTERSHELF_ENV_FILE=/absolute/path/to/config`. It exports the settings to the child application and supplies matching command-line values. Run `--check-config` to validate without starting NTP, changing firewall, or launching a process. + +The supervisor **sources** the file as trusted shell configuration. Keep it administrator-owned, restrict its mode, and use simple `RS_KEY=value` assignments. A dotenv file from an untrusted person can execute commands when sourced. This format is not an arbitrary web input or a general dotenv parser; shell quoting rules apply. + +The Go binary reads exported `RS_*` values; it does not automatically read or execute `.env`. Its flags take precedence over environment defaults. For local use: + +```sh +set -a +. ./.env +set +a +go run ./cmd/routershelf +``` + +With no configured IP, the standalone binary defaults to loopback. `RS_DOMAIN` enables HTTPS; without it, the standalone binary can serve plain HTTP for development. The deployment supervisor requires a domain and distinct unprivileged internal ports. + +## Settings + +| Variables | Purpose | +| --- | --- | +| `RS_DOMAIN` | Single HTTPS certificate hostname, without scheme or port | +| `RS_LAN_IP`, `RS_LAN_SUBNET`, `RS_LAN_INTERFACE` | Bind address and modem firewall scope | +| `RS_USB_MOUNT` | Exact expected USB mount point | +| `RS_PUBLIC_SUBDIR`, `RS_SERVICE_SUBDIR` | Subdirectory names used to derive share/service paths | +| `RS_ROOT`, `RS_BINARY`, `RS_CERT_CACHE`, `RS_CA_BUNDLE` | Optional absolute path overrides | +| `RS_HTTP_PORT`, `RS_HTTPS_PORT` | Internal listener/firewall ports; default 10080 and 10443 | +| `RS_PUBLIC_ACCESS` | `false`: LAN-only sources; `true`: also allow forwarded public sources | +| `RS_DROP_PRIVILEGES` | Run application as UID/GID 65534; normally `true` | +| `RS_MEMORY_LIMIT`, `RS_CPU_LIMIT` | Go GC memory target and GOMAXPROCS | +| `RS_CHECK_INTERVAL`, `RS_MIN_YEAR` | Supervisor poll interval and coarse reset-clock guard | +| `RS_NTP_SERVER1`, `RS_NTP_SERVER2` | NTP startup peers | +| `RS_SUPERVISOR_PATH`, `RS_RUNTIME_DIR` | Installed script and runtime PID/log directory | +| `RS_GATEWAY_*` | Public/LAN gateway addresses and interfaces, used by the NAT plan | +| `RS_PUBLIC_HTTP_PORT`, `RS_PUBLIC_HTTPS_PORT` | Public standard ports: 80 and 443 | +| `RS_PUBLIC_SSH_PORT`, `RS_SSH_TARGET_PORT` | Independent SSH mapping in the NAT plan | + +The standard public 80/443 configuration is intended for ACME validation and normal redirects. Changing public HTTPS away from 443 requires redirect handling changes too; the current redirect targets the standard HTTPS hostname. These plan values do not change application redirects or DNS automatically. + +Do not place the binary, trust bundle, or certificate cache inside the public root. Deployment paths are absolute and may not contain spaces or `..` in the supervisor. Private keys stay on USB outside the root; a filesystem/account policy must protect them from broad FTP/SFTP access. + +## Installing your configuration + +```sh +cp .env.example .env +# Edit values in .env; set RS_PUBLIC_ACCESS=true only if public sharing is intended. +ROUTERSHELF_ENV_FILE="$PWD/.env" sh deploy/padavan/supervisor.example.sh --check-config +make nat-plan +ssh router 'cat > /etc/storage/routershelf.env; chmod 600 /etc/storage/routershelf.env' < .env +``` + +Install the matching supervisor from `deploy/padavan/supervisor.example.sh`, validate it on the target, and keep the startup/firewall hooks pointing to its installed path. `mtd_storage.sh save` persists the private environment alongside the hooks on the observed firmware. Back it up privately; it is not a public example. + +The obsolete `/etc/storage/public-share-public` marker is no longer used. `RS_PUBLIC_ACCESS` is the source of truth. Keeping an old marker does not grant access with this version. + +## Applying changes + +Editing the file alone does not reload a running supervisor or application's environment. Stop the verified supervisor, wait for its child and PID cleanup, then start one supervisor again. Save the edited env to flash. This can briefly interrupt downloads. + +For domain/IP/port changes, review the printed gateway plan and update DNS/NAT manually as needed. For shared root or USB changes, verify mount and read permissions. Keep the existing certificate cache when the domain is unchanged. Rebuilding is required only for code/theme changes, not configuration changes. + +The firewall reconciles its own IPv4 rules, including previous internal ports, while blocking traffic during replacement. IPv6 blocks on old ports are retained; review them during cleanup. A failure can leave temporary IPv4 DROP rules to keep the service closed. Inspect and resolve the failure before removing these blocks. Do not run simultaneous firewall managers. + +## Git and archives + +`.env` and private variants are ignored; `.env.example` is explicitly included. Public ZIPs must include only the example. `.gitignore` does not remove already committed secrets: check staged content before publication and rotate any exposed credentials. diff --git a/docs/deployment-history.md b/docs/deployment-history.md new file mode 100644 index 0000000..7d73f17 --- /dev/null +++ b/docs/deployment-history.md @@ -0,0 +1,80 @@ +# Deployment history and verification + +This is a sanitized account of the work completed on the original home network. Example addresses are used throughout. It records the final behavior and the limits of validation, rather than implying that every suggested test was performed. + +## 1. Network inspection and correction + +The LHG5 was the Internet gateway. The NW-651D supplied Wi-Fi and additional LAN ports, with the gateway connected to a **LAN** port. Internet already worked on the user's computer. The empty modem WAN port explained the panel's disconnected-WAN indication. + +We installed and saved the storage host's default route through the LHG5 on `br0`, metric 1. DHCP remained enabled on the NW-651D; clients were configured to use the LHG5 as their gateway and public DNS servers. Existing static leases and ARP bindings were retained. Bounded Internet and DNS-related reachability checks succeeded. Moving the cable to WAN was not necessary for this topology. + +## 2. SSH discovery and temporary status dashboard + +Authorized SSH access revealed BusyBox, OpenSSH/SFTP, vsftpd, curl, cron, and iperf3. A shell/Netcat dashboard was built on port 8080 to show uptime, approximate RAM use, load, and bounded connectivity probes. LAN firewall rules, IPv6 blocking, startup/firewall hooks, and flash saving were added. HTTP responses and browser rendering were checked. + +At the user's request, this dashboard was completely removed from the router: scripts, hooks, dedicated firewall rules, runtime files, and installation backups were cleaned up, and flash was saved. The public documentation project and dashboard teaching templates were retained on the computer. + +## 3. USB storage and transfer services + +A roughly 1 TB USB disk was mounted read/write as exFAT. A temporary local file was written, read back, and removed successfully. FTP configuration allowed authenticated local users and writes, disabled anonymous access, and selected passive ports 50000–50100. An anonymous FTP attempt returned 530. + +**An authenticated FTP upload/download was not completed**, because credentials were not provided for that test. Configured write support and successful local disk I/O do not prove authenticated FTP permissions. SFTP login through the existing SSH key was verified; an SFTP file-transfer test was not completed at that stage. + +## 4. Gateway port forwarding cleanup + +A WAN TCP 222 rule was created to forward SSH to the NW-651D's TCP 22. Eight old destination-NAT forwarding rules were removed at the user's request. The Internet source-NAT rule was preserved. This SSH forwarding rule remains separate from file sharing. + +## 5. Public USB directory on port 8888 + +A Go directory server was compiled for Linux/MIPS little-endian and deployed from a hidden service directory outside `public-storage`. It listed folders and forced regular-file downloads. GET/HEAD were allowed; upload and deletion methods were rejected. Hidden paths, traversal, and escaping symlinks were blocked. A child supervisor, USB mount checks, bounded connections, firewall hooks, and flash persistence were installed. + +A WAN TCP 8888 forward was created after explicit approval for unauthenticated public access. Listing and download of a small test file succeeded locally; its checksum matched. PUT returned 405 without creating a file; traversal returned 404. Initial resident memory was approximately 3 MiB. External download was not independently verified at this stage. + +## 6. HTTPS and standard ports + +DNS was confirmed to point to the LHG5's public IPv4 address. The router clock was corrected. NTP server settings and a BusyBox NTP startup command were added. A current CA root bundle was installed outside the public directory so the Go ACME client could validate its outbound TLS connection. + +The Go server gained `autocert`, with a whitelist for one domain and a persistent certificate/account cache on USB. It listens internally on TCP 10443 for HTTPS and TCP 10080 for ACME HTTP challenges and redirects. A trusted Let's Encrypt certificate was issued. Automatic renewal support is enabled; a future renewal has not yet been observed. + +The gateway forwards public TCP 443 to internal 10443 and TCP 80 to internal 10080. The rules match the deployment's public IPv4 address. A scoped LAN source-NAT rule enables hairpin access so the same domain works from inside the home. The old WAN 8888 rule was disabled; no server listens on 8888. + +Validated: certificate hostname/issuer/expiry, trusted HTTPS without disabling validation, HTTP 308 redirect, listing, file download and byte equality, PUT 405, hidden-path 404, and browser rendering at the real domain. Certificate authority validation demonstrated inbound challenge reachability. A separate mobile-data or remote-client download remains an additional verification step. Resident memory after TLS was approximately 9 MiB. The server runs as UID/GID 65534 after dropping privileges. + +NTP replies were observed during setup. A later documentation-time check did not return an NTP PID, although the clock remained correct. Do not assume that NTP remains running: verify it after firmware events and reboot, as described in the operations guide. + +## 7. NAIS styling + +NAIS CSS, JavaScript, and favicon assets were copied from the user's local clone and embedded in the Go binary. No nginx installation was needed. The HTML uses an autoindex-like heading and preformatted file rows. Theme assets are served from a reserved `/_nais/` namespace. + +Small integration changes: fixed row alignment, mobile header wrapping, a read-only footer, explicit file markers so extensionless files enter copied links/playlists, and copy success/failure feedback. The original NAIS checkout was not edited. + +The dark theme rendered in the browser. HTTPS file download stayed intact. A downloaded DPL playlist contained the correct HTTPS file URL. The Copy Links button reported `Copied!`; the automation clipboard readback did not independently confirm the OS clipboard content, so manually paste the result when checking a new browser. + +## Current service inventory + +| Component | State | +| --- | --- | +| LAN status dashboard, TCP 8080 | Removed from router; teaching source retained | +| FTP | Configured for authenticated read/write; end-to-end authenticated transfer still requires verification | +| SFTP/SSH | Key login checked; WAN TCP 222 forward retained | +| Public HTTP, TCP 8888 | Old gateway rule disabled; listener replaced | +| HTTP, public TCP 80 | ACME challenge responses and redirect to HTTPS | +| HTTPS, public TCP 443 | Read-only directory server with NAIS | +| Certificate renewal | Enabled in code; future renewal not yet exercised | +| Boot persistence | Hooks and flash save checked; full reboot test outstanding | + +Future checks should be recorded with dates and outcomes. Avoid promoting a configured feature to a tested guarantee. + +## 8. Environment-based configuration + +Network and installation values were moved into an ignored private `.env` on the computer and `/etc/storage/routershelf.env` on the router. A tracked `.env.example` supplies public placeholders. The same supervisor source now loads the configuration; the Go binary reads exported settings with CLI overrides. + +The live router was migrated with the same domain, addresses, paths, and listener ports. The existing certificate cache was retained and a pre-migration script/binary backup kept privately. The old public-access marker no longer controls permissions; `RS_PUBLIC_ACCESS` does. Owned IPv4 firewall rules were rebuilt from the configuration, removing the unused 8888 jump. + +Validated: example and live config checks, invalid-port rejection, Go environment/override and unsafe-config tests, MIPS build, live trusted HTTPS/download, HTTP redirect, PUT 405, private env path 404, live chain scope, dropped UID/GID, and flash save. The full reboot and future renewal checks remain outstanding. The NAT-plan utility prints configuration guidance without changing the gateway. + +## 9. Static pages in the same shared root + +The application now renders a directory's readable regular `index.html` before listing it, and serves direct HTML requests inline. Recognized CSS/JavaScript/image/font assets have explicit MIME types. Other files retain attachment downloads. No separate root or URL prefix, new env settings, or gateway rules were added. + +The binary was deployed with the previous version kept for rollback. Tests covered folder/root index precedence, direct HTML and assets, HEAD, preserved downloads, listing link attributes, and an escaping index symlink. A temporary live page rendered over HTTPS with CSS and JavaScript; its direct HTML link rendered too. HEAD confirmed HTML without attachment disposition, a normal text file still had attachment disposition, and PUT remained 405. Temporary probe files were removed after testing. Static pages intentionally permit browser-side active content; no PHP/CGI/server-side execution was added. diff --git a/docs/examples/status-dashboard.md b/docs/examples/status-dashboard.md new file mode 100644 index 0000000..1fbc2f1 --- /dev/null +++ b/docs/examples/status-dashboard.md @@ -0,0 +1,289 @@ +# Build a Small LAN Web Service on a Linux Router + +> Historical example: this LAN dashboard was removed from the original router. For the current public HTTPS/NAIS service, read [getting-started.md](../getting-started.md) and [operations.md](../operations.md). The two services have different access and security models. + +This guide explains how to build, install, and maintain a service like the included router dashboard. It assumes you own or administer the router and have an authorized SSH account. The example is deliberately small enough to run without installing a language runtime. + +## 1. Understand the architecture + +```text +LAN browser -> router TCP port 8080 -> Netcat -> shell request handler + | + +-> /proc status files + +-> bounded ICMP probes + +-> HTTP headers + HTML response +``` + +The router's management panel remains on its existing port. The new service does not change DHCP, routing, Wi-Fi settings, credentials, or the panel. Being in a directory opened by PhpStorm does not mean the router runs PHP. + +The browser requests `/` or `/status`. The handler reads a fixed request path, gathers metrics, sends a response, and exits. Netcat waits for the next client. With no browser open, no periodic probe runs. + +## 2. Inspect your target before designing the service + +Use your own SSH alias. In the examples, `router` is an illustrative alias, not a credential bundled with this repository. + +```sh +ssh router +uname -a +busybox +nc --help +cat /proc/meminfo +cat /proc/mtd +mount +df -h +netstat -lnt +iptables -S INPUT +ip6tables -S INPUT +``` + +Check these requirements: + +- Linux exposes `/proc/uptime`, `/proc/meminfo`, and `/proc/loadavg`. +- The installed shell supports `read -r -t`; this is an extension, not portable POSIX `sh` behavior. +- Netcat supports persistent `-ll` listening with `-e PROGRAM`. Other Netcat implementations have different options. +- `awk`, `ping -c ... -W ...`, `nohup`, `grep`, `iptables`, and `ip6tables` exist. +- The chosen TCP port is unused. +- You know the LAN bridge interface, LAN address, client subnet, and upstream gateway. +- The firmware provides a writable configuration directory and an understood mechanism to save it across power cycles. + +The original router had about 128 MiB RAM, a read-only SquashFS root, and a 512 KiB persistent Storage partition. Its runtime `/etc/storage` directory was backed by RAM. `df` alone does not reveal the persistent flash capacity: inspect `/proc/mtd` too. Do not fill flash or assume that a writable runtime file survives reboot. + +Read the device's own help first. BusyBox builds can omit applets or features even when the same version is reported. If a suitable HTTP daemon is already installed, consider using it instead of Netcat; do not repurpose the management panel daemon without documentation. + +## 3. Write a fixed, read-only request handler + +See [`../../examples/status-dashboard/scripts/status-response.sh`](../../examples/status-dashboard/scripts/status-response.sh). + +The script accepts only `GET /` and `GET /status`, returning 404 for other requests. It consumes the request headers before sending the page. Request text is never executed, passed to `eval`, or used as a filesystem path. + +A minimal HTTP response needs a status line, headers, a blank line, and a body. Lines in the header section use CRLF: + +```sh +printf 'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n' +``` + +The example does not send Content-Length for successful responses. Instead, it sends `Connection: close`; completion of the handler closes the response stream. Its empty 404 response includes `Content-Length: 0`. + +The included headers disable browser caching, prevent MIME sniffing, block framing, and permit only the inline CSS used by the page. There are no cookies, external fonts, scripts, or analytics. + +### Metrics and interpretation + +| Metric | Source | Interpretation | +| --- | --- | --- | +| Uptime | `/proc/uptime` | Converted to days, hours, and minutes | +| Memory | `/proc/meminfo` | Total minus free, buffers, and cached memory; approximate, not MemAvailable | +| Load averages | `/proc/loadavg` | Workload averages over 1, 5, and 15 minutes; not CPU percentages | +| Gateway reachability | `ping -c 1 -W 1` | One bounded ICMP probe | +| Internet probe | `ping -c 1 -W 2` | One bounded probe to a chosen public IP | + +A failed probe can mean blocked ICMP rather than an outage. The IP probe does not test DNS, HTTPS, or every website. Successful Internet access from the router also does not prove that every client has the correct DHCP lease. + +The page refreshes through ``. Every open tab generates its own requests. This is a live snapshot, not historical monitoring. + +## 4. Prepare configuration on your computer + +From the repository root, enter the standalone example directory first: + +```sh +cd examples/status-dashboard +``` + +```sh +cp config.example.sh config.sh +``` + +Edit `config.sh` to match your router. The example subnet is illustrative: + +```sh +LAN_INTERFACE=br0 +LAN_IP=192.168.50.1 +LAN_SUBNET=192.168.50.0/24 +GATEWAY_IP=192.168.50.2 +PROBE_IP=1.1.1.1 +PORT=8080 +``` + +Use numeric IP addresses, a valid CIDR subnet, and an unused unprivileged TCP port. The configuration is sourced as shell code and must be treated as administrator-controlled code. Do not generate it from HTTP input. Do not commit the real configuration. + +Before upload, check syntax: + +```sh +sh -n scripts/status-response.sh +sh -n scripts/status-service.sh +sh -n config.sh +``` + +Syntax checks on a desktop do not prove support for BusyBox extensions. Repeat them on the router, then exercise the requests there. + +## 5. Upload the files + +The following commands assume the reviewed Padavan-style `/etc/storage` layout. Adapt them for other firmware; do not invent persistence paths. + +```sh +ssh router 'mkdir -p /etc/storage/router-status; chmod 700 /etc/storage/router-status' +ssh router 'cat > /etc/storage/router-status/config.sh' < config.sh +ssh router 'cat > /etc/storage/router-status/status-response.sh' < scripts/status-response.sh +ssh router 'cat > /etc/storage/router-status/status-service.sh' < scripts/status-service.sh +ssh router 'chmod 600 /etc/storage/router-status/config.sh; chmod 700 /etc/storage/router-status/status-response.sh /etc/storage/router-status/status-service.sh' +``` + +Using SSH input redirection avoids depending on an SFTP subsystem. Do not replace unrelated files or upload an entire router backup into the repository. + +Check syntax and file ownership on the router: + +```sh +ssh router 'sh -n /etc/storage/router-status/status-response.sh; sh -n /etc/storage/router-status/status-service.sh; ls -l /etc/storage/router-status' +``` + +## 6. Restrict access before starting the listener + +See [`../../examples/status-dashboard/scripts/status-service.sh`](../../examples/status-dashboard/scripts/status-service.sh). The service manager applies its firewall rules before starting Netcat. It uses a dedicated IPv4 chain, `RS_STATUS`, reached from INPUT for the configured port. + +The only allow rule requires all three: + +1. Arrival on the configured LAN interface. +2. Source address in the configured client subnet. +3. Destination address equal to the configured router LAN IP. + +All other IPv4 traffic to the service is dropped. IPv6 traffic to its port is also dropped. The stock Netcat listener may bind all addresses, including an IPv6 wildcard socket; firewall enforcement is therefore essential. + +Run and inspect the rules first: + +```sh +ssh router '/etc/storage/router-status/status-service.sh --firewall' +ssh router 'iptables -S INPUT; iptables -S RS_STATUS; ip6tables -S INPUT' +``` + +Do not continue if commands fail or the expected rules are missing. Some embedded firewall builds behave unexpectedly with `iptables -C`; this example checks listed rules instead. It requires `iptables -S` support. + +The example does not automatically change an existing chain to new LAN settings. If configuration changes, stop the listener, remove the service's old rules using its old configuration, then apply the new settings. Do not flush the router's overall firewall. + +There is no authentication. Any permitted LAN client can read the dashboard. See [the security model](../../SECURITY.md) for limitations. Keep it off public and untrusted guest networks. + +## 7. Start and verify the service + +```sh +ssh router '/etc/storage/router-status/status-service.sh' +``` + +The manager launches: + +```sh +nohup nc -ll -p "$PORT" -e "$SERVICE_DIR/status-response.sh" \ + /tmp/router-status.log 2>&1 & +``` + +The PID goes into `/tmp/router-status.pid`. Logs and PID files are temporary; the executable scripts and configuration belong in persistent storage. + +From a permitted LAN client, substitute your router's address and configured port: + +```sh +curl --max-time 10 -i http://192.168.50.1:8080/ +curl --max-time 10 -i http://192.168.50.1:8080/status +curl --max-time 10 -i http://192.168.50.1:8080/missing +``` + +Expect 200 and an HTML page for the first two, and 404 for the third. Open the page in a browser and check layout, metrics, and refresh behavior. If available, try from a guest/VLAN client outside the allow rule; it should not connect. Verify IPv6 is blocked too. + +A request from the router itself may fail because it arrives on loopback rather than the permitted LAN interface. Test from a LAN client; do not weaken the access rule just to make a loopback test succeed. + +To diagnose startup: + +```sh +ssh router 'cat /tmp/router-status.log; netstat -lnt; cat /tmp/router-status.pid' +``` + +A running PID is not sufficient evidence that the listener is healthy. Check its command line and make an actual HTTP request. + +## 8. Configure persistence without overwriting existing hooks + +On the reviewed firmware, `/etc/storage/started_script.sh` runs after startup when networking is ready. `/etc/storage/post_iptables_script.sh` runs after firmware firewall rebuilds. Inspect both files before editing them. Back them up privately on the router or your own computer. + +Add these lines once to `started_script.sh`, before any unconditional exit: + +```sh +# Router status service +/etc/storage/router-status/status-service.sh +``` + +Add these lines once to `post_iptables_script.sh`, also before any unconditional exit: + +```sh +# Router status service firewall +/etc/storage/router-status/status-service.sh --firewall +``` + +Preserve all existing custom behavior. Do not replace the whole hook or append duplicates during repeated installation. Keep hook permissions unchanged. + +On this firmware, save the edited storage files with: + +```sh +ssh router 'mtd_storage.sh save' +``` + +Check the success result. This writes the firmware's Storage partition; it is not a command to format or overwrite the firmware. Do not run it repeatedly for every page request or log update. + +Reboot only during a suitable maintenance window. After reboot, verify HTTP access, firewall rules, and the PID. Until that test is done, describe persistence as configured, not reboot-tested. + +## 9. Extend the example into another service + +Keep the transport and handler responsibilities separate. For a new read-only page: + +1. Decide exactly which information should be exposed. +2. Collect only those values with bounded, predictable commands. +3. Add a fixed route and render the result. +4. Escape any text inserted into HTML. Numeric `/proc` values used here are controlled; arbitrary hostnames or log messages are not. +5. Return the correct Content-Type. For JSON, correctly encode strings and escape control characters; do not interpolate arbitrary text into JSON. +6. Test malformed paths, unsupported methods, missing data, timeouts, and access restrictions. + +Do not add buttons that execute arbitrary commands. A service that changes router settings needs authentication, CSRF protection, authorization, and a more capable HTTP stack. Large applications, many clients, TLS, uploads, or public access should use a maintained server and an appropriate host. + +## 10. Stop and remove the service + +Use the actual port from the installed configuration. Before killing a PID, inspect its command line; a stale PID may belong to another process: + +```sh +ssh router +pid=$(cat /tmp/router-status.pid) +tr '\000' ' ' < "/proc/$pid/cmdline" +``` + +Only after confirming it is this service's Netcat listener: + +```sh +kill "$pid" +rm -f /tmp/router-status.pid +``` + +Remove the two service calls from the startup and firewall hooks. Preserve unrelated edits made since installation rather than blindly restoring an old backup. + +With the old configuration still present: + +```sh +. /etc/storage/router-status/config.sh +iptables -D INPUT -p tcp --dport "$PORT" -j RS_STATUS +iptables -F RS_STATUS +iptables -X RS_STATUS +ip6tables -D INPUT -p tcp --dport "$PORT" -j DROP +``` + +These are service-owned rules; if a matching IPv6 DROP rule existed before installation, preserve it. Inspect rules and remove duplicate service-owned jumps individually if necessary. Do not use `iptables -F INPUT`. + +Remove only this project's directory after reviewing its contents, then save storage with the firmware's tool. Verify the port no longer answers and the management panel still works. + +## 11. Prepare a public repository + +- Keep real configuration, keys, backups, log output, packet captures, and private screenshots out of Git. +- Use placeholders in documentation; never include a real SSH password or private key. +- Review `git status` and `git diff --cached` before committing. +- `.gitignore` does not remove files already tracked. If a secret was committed, remove it from history as appropriate and rotate the exposed credential before publishing. +- State compatibility and testing limits honestly. A sample based on one router is not universal support. +- Choose a license. This project includes MIT; review that choice before publication. + +For repository-wide contribution and publication guidance, return to the repository root and read [CONTRIBUTING.md](../../CONTRIBUTING.md). Keep this example under `examples/status-dashboard`; do not initialize a nested Git repository or publish private deployment configuration. + +## References + +- [BusyBox official applet documentation](https://busybox.net/downloads/BusyBox.html): builds vary; installed `--help` output is the authority for the target. +- [Netfilter / iptables project](https://www.netfilter.org/projects/iptables/index.html): firewall tooling and upstream documentation. +- Device-local firmware scripts and help output were used to establish the observed storage and startup behavior. The hook paths and save command are firmware-specific. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..46fbdc6 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,153 @@ +# Deploy the public HTTPS directory service + +## Architecture and paths + +```text +Internet or LAN browser -> files.example.com + public TCP 80 -> gateway DNAT -> storage host TCP 10080 (ACME/redirect) + public TCP 443 -> gateway DNAT -> storage host TCP 10443 (HTTPS listing/download) +``` + +The service shares only `/media/DISK_ID/public-storage`. Installation layout: + +```text +/media/DISK_ID/public-storage/ Published files +/media/DISK_ID/.public-share-service/public-directory Executable +/media/DISK_ID/.public-share-service/ca-certificates.pem +/media/DISK_ID/.public-share-service/certificates/ Private ACME account/key cache +/etc/storage/public-share-service.sh Supervisor/firewall script +/etc/storage/routershelf.env Private configuration +/tmp/public-share-supervisor.pid Runtime parent PID +/tmp/public-share-child.pid Runtime child PID +/tmp/public-share.log Runtime log +``` + +The certificates directory is private administrative material, despite its location on the same disk. Never put it inside `public-storage`, include it in public backups, or symlink it into the shared root. The server reserves `/_nais/` for embedded theme assets; use a different name for a real directory that must be shared. + +## 1. Prepare source and example configuration + +Build on a computer with Go, not on the router. The tested build used Go 1.26.5 and pinned dependencies in `go.mod`/`go.sum`. Confirm the current toolchain's compatibility with the target's old kernel before upgrading. The program uses `os.OpenRoot` to enforce the shared-directory boundary. + +```sh +mkdir -p dist +go test ./... +GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 \ + go build -trimpath -ldflags='-s -w' -o dist/routershelf-linux-mipsle ./cmd/routershelf +``` + +Use `mipsle` only for the matching target CPU. The binary has no PHP, nginx, or dynamically linked runtime requirement. Preserve dependency checksums. Rebuild and test for other devices rather than downloading an arbitrary executable. + +Copy `.env.example` to `.env` and set the actual domain, USB mount, LAN IP/subnet/interface, and internal ports there. Set `RS_PUBLIC_ACCESS=true` only for intentional public sharing. The supervisor and Go binary derive paths from these settings; there is no per-network source edit or rebuild. See [configuration](configuration.md). + +```sh +cp .env.example .env +ROUTERSHELF_ENV_FILE="$PWD/.env" sh deploy/padavan/supervisor.example.sh --check-config +make nat-plan +``` + +The supervisor owns `NB_PUBLIC`. It reconciles this chain and its IPv4 INPUT jumps when settings change, temporarily blocking the affected ports while rebuilding. If a firewall operation fails, temporary blocks may remain; inspect rather than bypass them. Old IPv6 DROP rules are retained for safety and can be reviewed separately. The former 8888 IPv4 jump is removed during reconciliation. + +## 2. Prepare clock and outbound trust + +A correct clock is required for TLS and certificate operations. Configure the firmware's NTP servers, for example `time.cloudflare.com` and `pool.ntp.org`, and check actual replies. If the clock is badly wrong, set it once from an accurate trusted computer, then verify NTP synchronization. + +The original supervisor creates `/tmp/ntpd` as a symlink to `/bin/busybox` and launches that path. This lets `pidof ntpd` find the process; starting `busybox ntpd` can leave the process named `busybox` and cause duplicate launches. Firmware events can still stop NTP, so monitor it separately. The service supervisor does not continuously restart NTP. + +Install a trusted CA bundle from an authenticated source. The original used the [curl CA bundle](https://curl.se/docs/caextract.html), with certificate verification enabled for its download: + +```sh +curl --fail --show-error --silent https://curl.se/ca/cacert.pem -o ca-certificates.pem +ssh router 'mkdir -p /media/DISK_ID/.public-share-service' +ssh router 'cat > /media/DISK_ID/.public-share-service/ca-certificates.pem' < ca-certificates.pem +``` + +The supervisor passes its path as `SSL_CERT_FILE`. This fixes outbound trust; it is different from the server certificate issued for your domain. Do not bypass TLS validation with `-k` or insecure Go settings. + +## 3. Install and start + +Upload to a new filename first: + +```sh +ssh router 'cat > /media/DISK_ID/.public-share-service/public-directory.new; chmod 755 /media/DISK_ID/.public-share-service/public-directory.new' < dist/routershelf-linux-mipsle +ssh router 'mv /media/DISK_ID/.public-share-service/public-directory.new /media/DISK_ID/.public-share-service/public-directory' +ssh router 'cat > /etc/storage/routershelf.env; chmod 600 /etc/storage/routershelf.env' < .env +ssh router 'cat > /etc/storage/public-share-service.sh; chmod 755 /etc/storage/public-share-service.sh' < deploy/padavan/supervisor.example.sh +ssh router '/etc/storage/public-share-service.sh --check-config' +``` + +Do not overwrite a running binary in place; see the update procedure in the operations guide. These commands assume the intended shared directory already exists and that the paths match the mounted disk. + +The supervisor checks for the exact mounted USB path every 10 seconds, stops the child when the mount disappears, and restarts it when available. It sets `GOMEMLIMIT=32MiB` and `GOMAXPROCS=2`; the memory limit is a Go garbage-collection target, **not** a hard process limit. The program then drops supplementary groups and runs as UID/GID 65534. Directory traversal permissions must allow that user to read the shared data and use its cache. + +Enable public mode only when publishing all current and future shared-directory content is intended: + +```sh +# Set RS_PUBLIC_ACCESS=true in the private env for intentional public access. +ssh router '/etc/storage/public-share-service.sh' +``` + +The modem firewall uses `NB_PUBLIC` on INPUT for the internal service ports. Public mode accepts packets arriving on `br0` destined for the host address, including forwarded packets with Internet source addresses. A LAN-source-only allow rule would reject those DNAT connections. The final chain rule drops other traffic. IPv6 access is blocked; no IPv6 publication was implemented. + +## 4. Save firmware hooks + +Append each command **once**, retaining the existing script contents: + +```sh +# /etc/storage/started_script.sh, after network startup +/etc/storage/public-share-service.sh + +# /etc/storage/post_iptables_script.sh, after firewall rebuild +/etc/storage/public-share-service.sh --firewall +``` + +Back up these scripts privately before editing. The firmware's `/etc/storage` is a RAM-backed working directory. Persist changes with its supported helper: + +```sh +mtd_storage.sh save +``` + +Use this command on the matching firmware only. It saves the small configuration hooks to flash; the binary, CA bundle, and ACME cache remain on USB. Avoid saving to flash for routine traffic, logs, or certificate renewal. A successful save is not a reboot test. + +## 5. Configure DNS and gateway NAT + +Point the public DNS A record for `files.example.com` to the gateway's public IPv4 address. Do not advertise AAAA unless you deliberately implement and test IPv6. Check `dig +short files.example.com A` and `dig +short files.example.com AAAA`. + +Create the following RouterOS NAT rules through WebFig or an authorized RouterOS administrator session. Preserve the existing Internet source-NAT rule and separate SSH forward. + +| Purpose | Chain and match | Action | +| --- | --- | --- | +| HTTPS | `dstnat`, destination `203.0.113.10`, TCP destination port 443 | `dst-nat` to `192.168.50.1:10443` | +| HTTP/ACME | `dstnat`, destination `203.0.113.10`, TCP destination port 80 | `dst-nat` to `192.168.50.1:10080` | +| LAN hairpin reply | `srcnat`, source `192.168.50.0/24`, destination `192.168.50.1`, TCP destination ports `10080,10443`, output `ether1` | `src-nat` to `192.168.50.2` | +| Separate SSH | `dstnat`, input `pppoe-out1`, TCP destination port 222 | `dst-nat` to `192.168.50.1:22` | + +The HTTPS/HTTP rules deliberately match the public address without a WAN-only input restriction, so LAN clients using the same public DNS answer can hit them too. Hairpin source NAT routes replies back through the gateway rather than directly to the LAN client. Restrict it to these service ports. Review filter rules as well: NAT alone does not authorize a packet that a forward-chain filter drops. + +If the public IP changes, update both DNS and these two destination-address matches. Dynamic DNS alone does not update the hardcoded NAT rules. A private ISP address or CGNAT requires a different connectivity solution; port forwarding on the home router cannot bypass an upstream NAT you do not control. + +## 6. Obtain and verify HTTPS + +`autocert.Manager` whitelists the configured domain, accepts the CA terms in code, obtains a certificate on demand, stores its account/certificate cache on USB, and schedules renewal while running. Review the CA terms before enabling this configuration. Public certificates are recorded in certificate transparency logs. + +The HTTP handler serves ACME challenges and redirects ordinary GET/HEAD requests to the fixed HTTPS domain with HTTP 308. Unknown HTTP hosts are rejected; redirects do not trust arbitrary Host headers. TLS uses a minimum of TLS 1.2. The application limits connections and header sizes and uses request timeouts. + +Issue the first request at `https://files.example.com/`. Initial issuance may exceed the short handshake timeout and fail once; inspect logs and the cache, then retry after issuance completes. Do not repeatedly delete the cache or loop certificate requests, as CA rate limits apply. + +```sh +curl --fail --show-error https://files.example.com/ +curl -I http://files.example.com/ +curl --fail --show-error https://files.example.com/your-test-file.txt -o downloaded-test.txt +openssl s_client -connect files.example.com:443 -servername files.example.com /dev/null | openssl x509 -noout -subject -issuer -dates +``` + +Compare the download with its source. Use normal trusted certificate validation. Test once from outside the LAN, such as mobile data with Wi-Fi disabled. A LAN success verifies hairpin behavior; a successful CA challenge verifies a challenge route, not every external client's full download path. + +## 7. How NAIS is integrated + +The Go executable embeds the theme files under `internal/theme/nais`: `autoindex.css`, `autoindex.js`, and favicons. The listing references them under `/_nais/`. This reproduces the theme without nginx's `sub_filter` or its installer. Folder links remain navigable; regular files carry `data-file="true"` and download attributes. The script uses that marker for copied links and DPL playlists, including extensionless files. + +The bundled integration adjusts row width and the mobile heading, changes the footer to read-only storage, and adds copy feedback/fallback handling. The HTML template escapes names. Assets have explicit MIME types; HTML and recognized CSS/JavaScript/image/font assets are served inline with explicit MIME types; other files use `application/octet-stream` and attachment disposition. A directory with a readable regular `index.html` displays that page instead of its listing. PHP/CGI are not executed. The listing retains its strict CSP; static pages permit inline scripts/styles and external assets, with object embedding and framing blocked. + +To update the style, review upstream changes, copy the intended assets to this source tree, retain the NAIS license, preserve the integration changes, rebuild, and deploy using the rollback procedure. Do not publish the upstream landing page as the directory listing. + +References: [Go autocert](https://pkg.go.dev/golang.org/x/crypto/acme/autocert), [Let's Encrypt challenges](https://letsencrypt.org/docs/challenge-types/), [NAIS](https://github.com/meghdadfadaee/nais). diff --git a/docs/network-and-storage.md b/docs/network-and-storage.md new file mode 100644 index 0000000..009cd31 --- /dev/null +++ b/docs/network-and-storage.md @@ -0,0 +1,101 @@ +# Network and USB transfer configuration + +## Network roles + +```text +Internet / PPPoE + | +MikroTik LHG5: 192.168.50.2 (gateway) + | LAN cable +NW-651D LAN port: 192.168.50.1 (Wi-Fi, LAN switch, USB services) + | +Home computers and phones +``` + +Use a LAN-to-LAN connection for this arrangement. Using the NW-651D WAN port would require a different routing design and can create a second NAT layer. The gateway handles Internet/PPPoE; the NW-651D is also a service host, not just a passive switch. + +Keep both management addresses outside the DHCP pool. In the original configuration the storage host ran DHCP, rather than the gateway. Run only one intended DHCP server on a shared broadcast domain. + +| Storage-host setting | Example | +| --- | --- | +| LAN address / mask | `192.168.50.1/24` | +| Its default route | `0.0.0.0/0` via `192.168.50.2`, metric 1, `br0` | +| DHCP pool | `192.168.50.100`–`192.168.50.244` | +| DHCP default gateway | `192.168.50.2` | +| DHCP DNS | `1.1.1.1`, `8.8.8.8` | +| Gateway LAN address | `192.168.50.2/24` | +| Gateway Internet interface | `pppoe-out1` | +| Gateway LAN interface | `ether1` | + +Save the static route and DHCP settings through the firmware's supported configuration mechanism. Renew client leases to receive changed DHCP options. A `route add` command alone normally does not survive reboot. Retain existing leases/ARP bindings unless deliberately changing them. + +On the storage host, inspect `route -n`, the active dnsmasq configuration, and `ping -c 1 -W 2 192.168.50.2`. Check a known HTTPS website from both the host and a client. A panel may still report WAN disconnected because the WAN port is unused; do not change an otherwise working topology solely to change that badge. + +## SSH and SFTP + +Configure a private SSH alias on your computer, for example in `~/.ssh/config`: + +```sshconfig +Host router + HostName 192.168.50.1 + Port 22 + User admin + IdentityFile ~/.ssh/your_private_key +``` + +Never commit the private key or a real SSH configuration to the repository. Verify the router's host key before first use. The observed firmware provided `/usr/libexec/sftp-server`. + +```sh +ssh router +sftp router +``` + +A separate gateway forward can map WAN TCP 222 to the storage host's TCP 22. Scope that rule to `pppoe-out1`, use key authentication, and inspect the existing SSH configuration before exposing it. This mapping does not configure SSH authentication by itself. An external SFTP client then uses the public hostname, port 222, and the authorized SSH account. Do not assume port 22 on the public address reaches the storage host. + +SFTP encrypts credentials and transferred data. Plain FTP does not. For public or untrusted-network transfers, use SFTP rather than exposing the plain FTP service. + +## Inspect USB storage + +```sh +mount +cat /proc/mounts +df -h /media/DISK_ID +ls -ld /media/DISK_ID /media/DISK_ID/public-storage +``` + +The original disk was exFAT, mounted read/write. The mount used `fmask=0000,dmask=0000`: Unix permission bits and `chmod 600` are not reliable isolation on this filesystem. Account restrictions and service path boundaries matter. An authenticated storage account that can read the whole disk may also read the service's private keys outside the public directory. Restrict account scope or use a filesystem with enforced permissions when stronger local isolation is needed. + +Use a unique disposable probe, not an existing filename: + +```sh +probe_dir=/media/DISK_ID/usb-probe-CHOOSE_A_UNIQUE_SUFFIX +mkdir "$probe_dir" || exit 1 +printf 'USB read/write probe\n' > "$probe_dir/probe.txt" +cat "$probe_dir/probe.txt" +rm "$probe_dir/probe.txt" +rmdir "$probe_dir" +``` + +Only remove files created for the test. If the disk is read-only, inspect mount flags and firmware logs before retrying. Back up valuable data and perform filesystem repair while unmounted, preferably on a computer with appropriate exFAT tools. + +## FTP settings and a real transfer test + +The observed vsftpd settings were: + +```ini +local_enable=YES +anonymous_enable=NO +write_enable=YES +pasv_min_port=50000 +pasv_max_port=50100 +``` + +These flags permit the feature; they do not establish every user's effective directory permission. Firmware-generated configuration can overwrite direct edits, so use the panel's supported FTP and account settings. Anonymous login should fail. Do not turn it on to work around account problems. + +For a LAN test, connect a client such as FileZilla to `192.168.50.1`, port 21, with an authorized FTP account. Use passive mode. Upload a unique small text file into a permitted test directory, list the directory, download it under a different local name, compare the bytes or checksum, then remove only the probe. A successful login alone is not a read/write test. + +On the LAN, passive data ports must pass the host firewall. Publishing FTP would also require control/data-port forwarding and correct advertised passive addresses; this was **not configured** in the original work. Prefer SFTP for remote transfer. + +To verify SFTP, use its interactive `put`, `ls`, `get`, and `rm` commands on a uniquely named probe, then compare the downloaded file locally. Resolve server filesystem/account permissions if writes fail; do not make the entire disk publicly writable. + +Keep a test record stating which account, protocol, read, write, and cleanup operations succeeded. Omit passwords and private keys from that record. diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..49c1514 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,123 @@ +# Maintenance and recovery + +## Routine care + +| Frequency / event | Check | +| --- | --- | +| After installation, reboot, or power loss | USB mounted at the expected path; accurate time; NTP replies; supervisor and child running; firewall rules reapplied; HTTPS download works | +| Weekly | Disk free space, router memory, repeated errors/restarts, ordinary listing/download, account access | +| Monthly and before expiry | Certificate expiry, renewal errors, DNS/public-IP match, router/toolchain/dependency security updates | +| After changing ISP/public IP | Update DNS A record **and** the two public-IP destination NAT rules; test on mobile data and LAN | +| After changing the disk or USB port | Verify mount ID, update supervisor paths if needed, restore private cache and executable, test restart | +| After adding public files | Check the listing and encoded filenames; ensure that the entire file and its name are intended for publication | +| Before firmware upgrade | Back up private configuration, verify hook compatibility and binary/kernel support, arrange a rollback path | + +Do not interpret a successful HTTP request as proof of disk health, NTP synchronization, or renewal. The current implementation does not provide monitoring alerts, filesystem snapshots, or a hard resource quota. + +## Read-only health checks + +On the router: + +```sh +date -u +pidof ntpd +cat /tmp/public-share-supervisor.pid +cat /tmp/public-share-child.pid +cat /tmp/public-share.log +cat /proc/mounts +df -h /media/DISK_ID +iptables -S NB_PUBLIC +iptables -S INPUT +ip6tables -S INPUT +``` + +Before acting on a PID, inspect `/proc/PID/cmdline` and confirm it belongs to this service. PID files can be stale or reused. Read `/proc/PID/status` for UID/GID and `VmRSS`; do not treat the large virtual address size reported by `ps` as resident RAM use. The observed HTTPS process used around 9 MiB RSS, but traffic and file sizes affect resource use. + +Check NTP replies as well as process existence. If `pidof ntpd` is empty, inspect the firmware behavior and start the configured `/tmp/ntpd` command deliberately. The current startup hook starts NTP once; it does not continuously supervise it. The daemon was observed absent during a later check, so reboot and firmware reconnect behavior require special attention. Correct any inaccurate clock before requesting new certificates. + +From a client: + +```sh +curl -I http://files.example.com/ +curl --fail --show-error https://files.example.com/ -o listing.html +curl --fail --show-error https://files.example.com/your-test-file.txt -o probe-download.txt +``` + +Expected: HTTP redirects to the fixed HTTPS hostname, HTTPS succeeds with normal validation, file bytes match, and navigation works. Also verify that a PUT to a unique nonexistent path returns 405 without creating a file, and a hidden path returns 404. Never use an existing filename for mutation probes. + +Check Copy Links by pasting into a local text editor. Check the DPL file contains the expected HTTPS URLs. The browser must allow clipboard access or the fallback may fail; the button shows success/failure. Long listings are truncated at 5,000 entries. The server supports HEAD and byte-range downloads for regular files. + +## Certificates and CA trust + +The persistent cache contains both the ACME account key and certificate private keys. Leave it intact across restarts and updates. Losing the cache can force new issuance and consume CA rate limits. Automatic renewal needs accurate time, DNS reaching the same public gateway, inbound challenge access, outbound HTTPS to the CA, a writable cache, and a running service. USB removal stops the service and prevents renewal. + +Inspect expiry with the `openssl s_client` command in the deployment guide. Renewals run inside `autocert`; there is no separate cron job to edit. The original certificate had roughly a three-month validity, but always inspect the actual expiry instead of assuming a duration. A future automatic renewal has not yet been verified on hardware. + +Refresh the CA root bundle periodically from a trusted source. Upload it to a temporary filename and rename it, then restart the child to make a running Go process load the new trust pool. Never solve trust failures by disabling certificate checks. + +## Backups + +Maintain two separate backup categories: + +- **Public source:** this repository, example config, build notes, pinned dependencies, and licensed theme assets. Safe to publish after review. +- **Private operational backup:** actual configuration/hooks, firmware version/settings export, router host-key information, SSH configuration, USB data, and the certificate/account cache. Encrypt it and restrict who can read it. + +Copy `/etc/storage` configuration privately and use the firmware's supported settings export. Store the USB backup on another disk, not only alongside the original data. Test restoration to a private location. Exclude all private operational backups from Git and public ZIPs. Avoid backing up a live-changing file halfway through a transfer. + +Never place backup archives in `public-storage` unless every byte is intended for public download. exFAT permission masks do not enforce meaningful Unix mode-based protection for the cache; review FTP/SFTP account scope. + +## Updating the binary safely + +1. Build and test on the computer. Keep the known-good source/toolchain version. +2. Upload a new executable outside the shared root, using a `.new` filename. +3. Check upload checksum/size and executable mode. Preserve a known-good installed binary under a private backup name. +4. Rename the new binary into place. Replacing a pathname by rename leaves the old running process intact until stopped. +5. Verify the child PID's command line, then terminate that child with TERM. The existing supervisor restarts it within its next 10-second check. Expect a brief interruption. +6. Verify log startup, valid HTTPS, downloads, methods, navigation, theme assets, and certificate cache retention. Record the result. + +Do not launch a second supervisor. If the supervisor itself needs replacement, stop it, wait until its trap has removed PID files and stopped the child, then start the new script. Starting immediately while the old parent still exits can cause PID detection/cleanup races. Inspect running commands rather than blindly deleting PID files. + +The hooks call the installed script path after future startup/firewall rebuilds. Save changed hook/supervisor/env files with `mtd_storage.sh save`; a binary-only update on USB does not require a flash write. + +## Rollback + +For a binary regression, rename the known-good binary back into place, verify and terminate only the current child, and let the supervisor restart it. Keep the certificate cache. For a script regression, restore the saved script/hooks, reconcile only this service's firewall rules, restart one supervisor, and save flash. + +If public access is malfunctioning or unintended, disable the service's TCP 80/443 gateway rules first; keep ordinary Internet NAT and unrelated SSH rules intact. Restore locally and test before re-enabling. Do not re-enable the old HTTP 8888 forward as an automatic rollback from TLS unless plaintext publication is intentionally acceptable. + +## Troubleshooting + +| Symptom | Likely cause and next check | +| --- | --- | +| Modem panel says no Internet but clients work | Unused WAN port in LAN topology; verify actual default route and client gateway | +| HTTPS connection refused | Child not running, wrong target ports, USB absent, or restart interval; read log and mount status | +| HTTPS timeout from Internet | Incorrect DNS/NAT, forward filter, modem INPUT rule, ISP port filtering, or CGNAT | +| Domain works outside but fails at home | Hairpin DNAT/source-NAT match or LAN routing; test the domain rather than the numeric TLS address | +| Works at home but not on mobile data | LAN success is not external proof; inspect WAN rule counters and actual public-IP ownership | +| Certificate issuance fails | Clock, CA roots, outbound HTTPS, domain whitelist, DNS A/AAAA, challenge reachability, or cache permissions | +| First TLS request fails, next succeeds | Initial issuance exceeded handshake timeout; check for a newly cached certificate before retrying | +| Renewal fails | Service downtime, USB/cache unavailable, inaccurate time, old DNS/NAT address, blocked challenge, or CA rate limit | +| Folder/file missing | Wrong root/mount, dot-prefixed name, outside symlink, nonregular file, read permission, or 5,000-entry truncation | +| FTP login works but upload fails | Account path/write permissions, read-only disk, or passive data ports; perform a real upload/download test | +| Style missing | Failed `/_nais/` asset request, MIME/CSP issue, stale browser cache, or binary built without intended assets | +| Copy button reports failure | Browser clipboard permission/support; test paste manually and try a supported secure browser | +| Service returns after stopping child | Expected supervisor restart; stop the parent to stop the whole service | +| NTP PID missing | Firmware stopped it or wrong process naming; inspect, restart deliberately, and verify replies | + +Debug one layer at a time: DNS, gateway rule, forward filter, host firewall, listener, storage, and application. Keep logs private; they can contain addresses and errors identifying the installation. + +## Removal without losing shared data + +1. Disable/remove only this service's gateway 80/443 rules and scoped hairpin rule. The previously disabled 8888 rule can be removed too. Keep the Internet source-NAT and independent SSH rule unless separately removing them. +2. Verify the supervisor PID and command, terminate it, and wait for its exit trap. Verify that its child stopped and the internal ports are no longer listening. +3. Remove only the two inserted public-share calls/comments from `started_script.sh` and `post_iptables_script.sh`, preserving other firmware/user commands. +4. Delete this service's INPUT jumps for 10080, 10443, and any retained 8888 hook. Remove the dedicated `NB_PUBLIC` chain only after all references are removed. Remove only the matching IPv6 DROP rules for these ports if they belong solely to this installation. Never flush entire tables. +5. Remove the installed supervisor, private environment file, this installation's PID/log files, and private service directory/backups when no longer needed. Preserve `public-storage` and unrelated USB files. Decide separately whether to retain or securely retire the ACME key/cache. +6. NTP is useful to the router beyond file sharing; leave it unless deliberately undoing its configuration. Revert only settings introduced for this deployment if a complete rollback is intended. +7. Save the edited configuration to flash, check the panel/network/SSH still work, and perform a controlled reboot test when convenient. + +For removal of the earlier status dashboard, use the separate original guide. That dashboard is already absent on the original router. Removing a service from the device does not remove its teaching source from this repository. + +## Environment changes + +Use [configuration.md](configuration.md) for configuration precedence and reload steps. The live environment lives at `/etc/storage/routershelf.env`, not in hardcoded source or the old public-access marker. Include this file in encrypted private backups. On config changes, restart the verified supervisor, not just the child, so new values are loaded. Code-only changes still require rebuilding; domain/path/IP changes do not. diff --git a/docs/static-pages.md b/docs/static-pages.md new file mode 100644 index 0000000..fdbcba5 --- /dev/null +++ b/docs/static-pages.md @@ -0,0 +1,27 @@ +# Static pages in the shared directory + +No separate site directory or URL prefix is required. The existing `RS_ROOT` serves both directory listings and static pages. + +- A directory request ending in `/` serves its regular, readable `index.html` when present. Otherwise, the NAIS listing appears. +- Requests without a directory trailing slash redirect before rendering, so relative asset links work. +- Direct `.html` and `.htm` requests render in the browser, including case-insensitive extensions. +- CSS, JS/MJS, JSON/source maps, common images, web fonts and WASM use explicit inline MIME types. Other extensions remain attachment downloads. +- HEAD and byte ranges are supported. PHP, CGI and other server-side code are never executed. + +Example layout inside your existing share: + +```text +public-storage/ + test.txt + brochure.html + demo/ + index.html + style.css + app.js +``` + +`/brochure.html` renders directly. `/demo/` renders its index and can use relative `style.css` and `app.js` references. Placing `index.html` at the share root makes `/` show that page; removing/renaming it restores the directory listing. + +Publishing HTML intentionally permits browser-side code under this domain. Static pages can use inline scripts/styles and external assets. Only trusted administrators should place active content in the share. The listing retains its more restrictive content policy. No authentication or server-side execution was added; hidden paths, traversal, escaping symlinks and write methods remain blocked. + +Deploy the new binary once using the normal update procedure. Afterwards, changing pages and assets on USB requires no rebuild or service restart; the next request reads the current files. No new env settings, gateway rules or TLS certificates are needed. diff --git a/examples/status-dashboard/README.md b/examples/status-dashboard/README.md new file mode 100644 index 0000000..bb4a5ff --- /dev/null +++ b/examples/status-dashboard/README.md @@ -0,0 +1,5 @@ +# Legacy LAN status dashboard + +This independent BusyBox/Netcat example reports basic router status. It has no HTTPS or authentication and is restricted to a trusted LAN. It was removed from the original router. + +Read the [standalone tutorial](../../docs/examples/status-dashboard.md) before using it. Copy `config.example.sh` to a private `config.sh` in this directory. Do not expose this service with RouterShelf's public gateway rules. diff --git a/examples/status-dashboard/config.example.sh b/examples/status-dashboard/config.example.sh new file mode 100644 index 0000000..63bfe2b --- /dev/null +++ b/examples/status-dashboard/config.example.sh @@ -0,0 +1,8 @@ +# Copy to config.sh and edit locally. Trusted shell configuration, not user input. +# These are illustrative addresses, not a working configuration for every router. +LAN_INTERFACE=br0 +LAN_IP=192.168.50.1 +LAN_SUBNET=192.168.50.0/24 +GATEWAY_IP=192.168.50.2 +PROBE_IP=1.1.1.1 +PORT=8080 diff --git a/examples/status-dashboard/scripts/status-response.sh b/examples/status-dashboard/scripts/status-response.sh new file mode 100755 index 0000000..39fbed6 --- /dev/null +++ b/examples/status-dashboard/scripts/status-response.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Fixed read-only response. No request content is executed. +SERVICE_DIR=${SERVICE_DIR:-/etc/storage/router-status} +. "$SERVICE_DIR/config.sh" +IFS= read -r -t 5 request || exit 0 +case "$request" in + 'GET / HTTP/'*|'GET /status HTTP/'*) ;; + *) printf 'HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'; exit 0 ;; +esac +while IFS= read -r -t 2 header; do + [ "$header" = "$(printf '\r')" ] || [ -z "$header" ] && break +done +up=$(awk '{d=int($1/86400);h=int($1%86400/3600);m=int($1%3600/60);printf "%dd %dh %dm",d,h,m}' /proc/uptime) +mem=$(awk '/MemTotal:/{t=$2}/MemFree:/{f=$2}/Buffers:/{b=$2}/^Cached:/{c=$2}END{printf "%.1f / %.1f MB (%.0f%%)",(t-f-b-c)/1024,t/1024,100*(t-f-b-c)/t}' /proc/meminfo) +load=$(awk '{print $1 " / " $2 " / " $3}' /proc/loadavg) +radio='No response'; ping -c 1 -W 1 "$GATEWAY_IP" >/dev/null 2>&1 && radio='Responding' +internet='No response'; ping -c 1 -W 2 "$PROBE_IP" >/dev/null 2>&1 && internet='Probe succeeded' +printf 'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nContent-Security-Policy: default-src '\''none'\''; style-src '\''unsafe-inline'\''; frame-ancestors '\''none'\''\r\nConnection: close\r\n\r\n' +cat < + + + + +Router status +
+

Router status

+

Local network dashboard. Refreshes every 30 seconds.

+
Uptime$up
+
Memory used, excluding cache$mem
+
Load average: 1 / 5 / 15 minutes$load
+
Gateway probe$radio
+
Internet IP probe$internet
+
Probes run on the router when this page is requested. A failed ICMP probe does not prove that Internet access is down. Load average is not CPU utilization.
+
+EOF diff --git a/examples/status-dashboard/scripts/status-service.sh b/examples/status-dashboard/scripts/status-service.sh new file mode 100755 index 0000000..a8c9b04 --- /dev/null +++ b/examples/status-dashboard/scripts/status-service.sh @@ -0,0 +1,28 @@ +#!/bin/sh +set -e +SERVICE_DIR=${SERVICE_DIR:-/etc/storage/router-status} +. "$SERVICE_DIR/config.sh" +rules() { + if ! iptables -S RS_STATUS >/dev/null 2>&1; then + iptables -N RS_STATUS + iptables -A RS_STATUS -j DROP + iptables -I RS_STATUS 1 -i "$LAN_INTERFACE" -s "$LAN_SUBNET" -d "$LAN_IP" -j ACCEPT + fi + # Refuse to silently reuse a chain configured for another LAN. + iptables -S RS_STATUS | grep -F -- "-s $LAN_SUBNET -d $LAN_IP/32 -i $LAN_INTERFACE -j ACCEPT" >/dev/null || { + echo "Review RS_STATUS: expected LAN allow rule not found" >&2 + return 1 + } + iptables -S RS_STATUS | grep -q -- '-A RS_STATUS -j DROP' || return 1 + ip6tables -S INPUT | grep -q -- "--dport $PORT -j DROP" || ip6tables -I INPUT 1 -p tcp --dport "$PORT" -j DROP + iptables -S INPUT | grep -q -- "--dport $PORT -j RS_STATUS" || iptables -I INPUT 1 -p tcp --dport "$PORT" -j RS_STATUS +} +rules +[ "$1" = '--firewall' ] && exit 0 +if [ -f /tmp/router-status.pid ]; then + pid=$(cat /tmp/router-status.pid) + case "$pid" in ''|*[!0-9]*) ;; *) kill -0 "$pid" 2>/dev/null && exit 0 ;; esac +fi +export SERVICE_DIR +nohup nc -ll -p "$PORT" -e "$SERVICE_DIR/status-response.sh" /tmp/router-status.log 2>&1 & +echo $! >/tmp/router-status.pid diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e0bfe79 --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module routershelf + +go 1.26.0 + +require golang.org/x/crypto v0.57.0 + +require ( + golang.org/x/net v0.58.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ff68b3a --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= diff --git a/internal/theme/assets.go b/internal/theme/assets.go new file mode 100644 index 0000000..a9a38c2 --- /dev/null +++ b/internal/theme/assets.go @@ -0,0 +1,8 @@ +package theme + +import "embed" + +// Files contains the licensed NAIS theme assets bundled into the executable. +// +//go:embed nais/autoindex.css nais/autoindex.js nais/favicon.ico nais/favicon.png +var Files embed.FS diff --git a/internal/theme/nais/LICENSE b/internal/theme/nais/LICENSE new file mode 100644 index 0000000..0f2d2fb --- /dev/null +++ b/internal/theme/nais/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Meghdad + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/internal/theme/nais/autoindex.css b/internal/theme/nais/autoindex.css new file mode 100644 index 0000000..537253e --- /dev/null +++ b/internal/theme/nais/autoindex.css @@ -0,0 +1,197 @@ +/* ========================= + Nginx AutoIndex Theme + ========================= */ + +:root { + --bg: #0f111a; + --bg-soft: #151926; + --row-hover: #1f2440; + --text: #e6e6eb; + --muted: #8b93a7; + --accent: #7aa2f7; + --folder: #9ece6a; + --parent: #f7768e; + --border: #2a2f4a; +} + +* { + box-sizing: border-box; +} + +html, body { + margin: 0; + padding: 0; + background: linear-gradient(135deg, #0f111a, #121626); + color: var(--text); + font-family: system-ui, -apple-system, BlinkMacSystemFont, + "Segoe UI", Roboto, Ubuntu, Cantarell, "Helvetica Neue", + Arial, sans-serif; + font-size: 14px; +} + +/* Title */ +h1 { + margin: 0; + padding: 18px 24px; + font-size: 18px; + font-weight: 600; + background: var(--bg-soft); + border-bottom: 1px solid var(--border); +} + +/* Listing container */ +pre { + margin: 0; + padding: 12px 0 24px; + white-space: pre; + overflow-x: auto; + line-height: 1.6; +} + +/* Make links feel like rows */ +pre a { + display: inline-block; + padding: 8px 24px 8px 44px; + position: relative; + + color: var(--accent); + text-decoration: none; + + transition: background 0.15s ease, color 0.15s ease; +} + +/* Hover & focus = full-row highlight */ +pre a:hover, +pre a:focus-visible { + background: var(--row-hover); + color: #ffffff; + outline: none; +} + +/* Parent directory */ +pre a[href="../"] { + color: var(--parent); + font-weight: 600; +} + +/* Folders */ +pre a[href$="/"] { + color: var(--folder); + font-weight: 600; +} + +/* === Icons (pure CSS, no emoji) === */ +pre a::before { + content: ""; + position: absolute; + left: 20px; + top: 50%; + width: 10px; + height: 10px; + transform: translateY(-50%); + border-radius: 2px; + background: var(--accent); + opacity: 0.85; +} + +/* Folder icon */ +pre a[href$="/"]::before { + background: var(--folder); +} + +/* Parent directory icon */ +pre a[href="../"]::before { + background: var(--parent); +} + +/* Footer note */ +pre::after { + content: "— Public storage · read-only —"; + display: block; + margin: 24px 24px 0; + color: var(--muted); + font-size: 12px; +} + +/* Scrollbar (WebKit only, safe) */ +pre::-webkit-scrollbar { + height: 8px; +} + +pre::-webkit-scrollbar-thumb { + background: var(--border); + border-radius: 4px; +} + +/* Mobile improvements */ +@media (max-width: 600px) { + h1 { + font-size: 16px; + padding: 14px 16px; + } + + pre a { + padding: 10px 16px 10px 40px; + font-size: 13px; + } + + pre a::before { + left: 16px; + } +} + +/* ===== Header actions ===== */ + +h1 { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} + +/* Button container */ +.autoindex-actions { + display: flex; + gap: 8px; +} + +/* Buttons */ +.ai-btn { + appearance: none; + border: 1px solid var(--border); + background: transparent; + color: var(--text); + font-size: 12px; + padding: 6px 10px; + border-radius: 6px; + cursor: pointer; + text-decoration: none; + line-height: 1; + + transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease; +} + +/* Hover */ +.ai-btn:hover { + background: var(--row-hover); + border-color: var(--accent); + color: #fff; +} + +/* Active */ +.ai-btn:active { + transform: translateY(1px); +} + +/* Mobile */ +@media (max-width: 600px) { + .ai-btn { + padding: 6px 8px; + font-size: 11px; + } +} + +/* Integration: keep names aligned without changing the NAIS theme. */ +pre a { width: clamp(220px, 45vw, 600px); overflow: hidden; text-overflow: ellipsis; vertical-align: middle; } +h1 > span { min-width: 0; overflow-wrap: anywhere; } +@media (max-width: 600px) { h1 { flex-wrap: wrap; } .autoindex-actions { flex-wrap: wrap; } } diff --git a/internal/theme/nais/autoindex.js b/internal/theme/nais/autoindex.js new file mode 100644 index 0000000..5f93474 --- /dev/null +++ b/internal/theme/nais/autoindex.js @@ -0,0 +1,153 @@ + +/** + * Check if a URL points to a file by extension + */ +function isFileLink(url) { + const fileExtensions = [ + 'pdf','zip','rar','7z', + 'mp3','mp4','mkv','avi', + 'jpg','jpeg','png','gif','webp', + 'doc','docx','xls','xlsx','ppt','pptx', + 'csv','txt','json' + ]; + + const cleanUrl = url.split('?')[0].toLowerCase(); + return fileExtensions.some(ext => cleanUrl.endsWith('.' + ext)); +} + +/** + * Get all file links from the page + */ +function getFileLinks() { + const links = document.querySelectorAll('a'); + const result = []; + + links.forEach(a => { + if (!a.href) return; + if (a.dataset.file !== "true") return; + + result.push({ + text: a.innerText.trim(), + href: a.href + }); + }); + + return result; +} + +/** + * Converts a string to kebab-case. + */ +function toKebabCase(str) { + return str + .toLowerCase() + .trim() + .replace(/['’]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +/** + * Extracts the last directory or file name from the current page URL + */ +function getDirectoryName() { + const url = new URL(window.location.href); + const lastPart = url.pathname + .split('/') + .filter(Boolean) + .pop() || 'file-links'; + + return decodeURIComponent(lastPart); +} + +/** + * Download file links as Playlist + */ +function downloadPlaylist() { + const files = getFileLinks(); + let content = 'DAUMPLAYLIST\n'; + + files.forEach((item, index) => { + const text = item.text.replace(/"/g, '""'); + const href = item.href.replace(/"/g, '""'); + content += `${index+1}*file*${href}\n`; + }); + + const blob = new Blob([content], { type: 'application/octet-stream;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + + const a = document.createElement('a'); + a.href = url; + a.download = toKebabCase(getDirectoryName()) + '.dpl'; + a.style.display = 'none'; + + document.body.appendChild(a); + a.click(); + + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +/** + * Copy file links (one per line) + */ +async function copyAllLinks() { + const files = getFileLinks(); + const textToCopy = files.map(f => f.href).join('\n'); + + // Modern browsers + if (navigator.clipboard && window.isSecureContext) { + try { + await navigator.clipboard.writeText(textToCopy); + return true; + } catch (_) { + // Fall back to a selected textarea when clipboard access is denied. + } + } + + // Fallback (older browsers, some mobiles) + const textarea = document.createElement('textarea'); + textarea.value = textToCopy; + textarea.style.position = 'fixed'; + textarea.style.opacity = '0'; + + document.body.appendChild(textarea); + textarea.focus(); + textarea.select(); + + const copied = document.execCommand('copy'); + document.body.removeChild(textarea); + return copied; +} + +(function () { + const header = document.querySelector('h1'); + if (!header) return; + + // Wrapper for buttons + const actions = document.createElement('div'); + actions.className = 'autoindex-actions'; + + // Playlist button + const plb = document.createElement('button'); + plb.className = 'ai-btn'; + plb.textContent = 'Download Playlist'; + plb.onclick = downloadPlaylist; + + // Copy Links button + const clb = document.createElement('button'); + clb.className = 'ai-btn'; + clb.textContent = 'Copy Links'; + clb.onclick = async () => { + try { + clb.textContent = (await copyAllLinks()) ? 'Copied!' : 'Copy failed'; + } catch (_) { + clb.textContent = 'Copy failed'; + } + window.setTimeout(() => { clb.textContent = 'Copy Links'; }, 2500); + }; + + actions.appendChild(clb); + actions.appendChild(plb); + header.appendChild(actions); +})(); diff --git a/internal/theme/nais/favicon.ico b/internal/theme/nais/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..4f60535231ead90586ba91428ff11a921f8fe99e GIT binary patch literal 51478 zcmeHw2VjlY|NfD^2N5J85s}D1h7d85*n1~->@6gc5Q4-AD%DcDbkb#1Q6te3p{*{Z z6je2gPOH_L$vyw)IX5?Mrb}r1`~G`4dGGtaXME0i&-m;kL?vM(JUkq5H4#4>39(NI z;ozXXuUAQk_l$)I3>0{8A=cOlam+*@eZjqj5VNZ=z4m^rsSw_7LPSRL-b2)DCB##; zb@@HSnz}-4A0b4&dfNA6U4)2zLRTK%qnv$j2vNPd_WdGDAtr4V!pTW{pKT_@ja|C> zJj7VQ^4`ZN4=@8Hfof4N9wMZpExLeW^+Gyc;x;{9d%<7)L`)aCxw&{D)qf!+e<9)@ zAMww_1)nBG^7T$x=&bi3K6O!cR<*(h$zj>q*_jK?3m(KL;ufJGg=w=znTzl~Gjo~` zQka`(X9hCAc}ivi@53?|HffTbT_v$u=Dc{`XKzlek~yz>R+#R7UP|Jkkj#ayy8F$k zA@iDKW?HCw+i?|o)wLRg~y`^;*Y ziG}Yo=cLR_MfnBwr(|b^1ZHN=3rWdV@WwC7N=VJjTv#nTGam2@F%4};Ycn$wwLKCa z#s`bC=Y^#6wGiAMSCkmU8KmWQh1Bem%1=e?^c+%HdaOJG8lfv7`PYmBBZ=# zFJ-Q=8XkE{;W2d<7#lcfV9kuGTbrBB4jRx+clJX%U$XRj&qJ>4@BKK&&6+D z;JbSv9fKNo7}x58zxer(%Tq3W{~bTtYI%gWA9ohC#|ld!BNnL=bY2@A{05*A@$ zA&Ju#3b81xNfX?Q)YN&2)3R~Tba*~3DP)Op%ZW3GzF69(;k6XKS; z5ZCbCbFl{LV!GaM-7}`SWiNy#O`Dhf6o@z!k?R&ix|O>Y(=<*LHU$yr!C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E0(x83Xt^V-kGMw-kMF*0gL=a0}7mCIuJIzkN?a!mE|uS z$jaU+O19eW+t1TXi~W}y#?`B%Yf*dJEQcfI)+5^4_PS78BPQ?i$!&xBU<>`V$ z6S}i9v1vn@A;oE5;#Zv%qNk***qeS?iC-@dC1u?wf*q;*Yyh}vegM)EQum!YcEG&s zxQqS!2fBj<(uodVWHNXpWXYQI@Fgo#RabR1dke+QAh86?WUyH#gSzH8KASWq;_0dV zvv%OMq9|~%#CW(nA9v&dXjl(#(>#lc^uPUnaq=2lPm$~qwVSKrlB15W{d`<+MD-3> z0L?6N07!RM$aPYEgrHE!Zy24M6SN?40{{&G{B4*svbxFRdf&17841tnua+;qoRJz? zDVNFEkvIU{GoB##?q%Cw5>U{Z+4uAo3a=H?iy|A z6BIhc41`uBy#Qb*fWhMez;yt~G3s?=S)I{_Y+J1i1c09`V@&`!0RTzRh9s>`eoomg e?b0sLnEVTTXVvaI%Il8+0000&2; exit 1; } +. "$ENV_FILE" +: "${RS_GATEWAY_PUBLIC_IP:?}" "${RS_GATEWAY_LAN_IP:?}" "${RS_GATEWAY_LAN_INTERFACE:?}" "${RS_GATEWAY_WAN_INTERFACE:?}" +: "${RS_LAN_IP:?}" "${RS_LAN_SUBNET:?}" "${RS_HTTP_PORT:?}" "${RS_HTTPS_PORT:?}" +: "${RS_PUBLIC_HTTP_PORT:?}" "${RS_PUBLIC_HTTPS_PORT:?}" "${RS_PUBLIC_SSH_PORT:?}" "${RS_SSH_TARGET_PORT:?}" +printf 'RouterShelf gateway NAT plan (manual configuration)\n' +printf 'HTTPS: dstnat dst=%s TCP port=%s -> dst-nat %s:%s\n' "$RS_GATEWAY_PUBLIC_IP" "$RS_PUBLIC_HTTPS_PORT" "$RS_LAN_IP" "$RS_HTTPS_PORT" +printf 'HTTP: dstnat dst=%s TCP port=%s -> dst-nat %s:%s\n' "$RS_GATEWAY_PUBLIC_IP" "$RS_PUBLIC_HTTP_PORT" "$RS_LAN_IP" "$RS_HTTP_PORT" +printf 'LAN hairpin: srcnat src=%s dst=%s TCP ports=%s,%s out=%s -> src-nat %s\n' "$RS_LAN_SUBNET" "$RS_LAN_IP" "$RS_HTTP_PORT" "$RS_HTTPS_PORT" "$RS_GATEWAY_LAN_INTERFACE" "$RS_GATEWAY_LAN_IP" +printf 'SSH (separate): dstnat in=%s TCP port=%s -> dst-nat %s:%s\n' "$RS_GATEWAY_WAN_INTERFACE" "$RS_PUBLIC_SSH_PORT" "$RS_LAN_IP" "$RS_SSH_TARGET_PORT" +printf 'Preserve existing Internet NAT/filter policy. Public IPv4 changes require DNS and NAT updates.\n'