This commit is contained in:
@@ -87,6 +87,31 @@ jobs:
|
||||
go build -ldflags="$LDFLAGS" -o dist/nadir-$VERSION-linux-arm64 ./cmd/server
|
||||
upx --best --lzma dist/nadir-$VERSION-linux-amd64 dist/nadir-$VERSION-linux-arm64
|
||||
|
||||
- name: Sign checksums
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
env:
|
||||
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
|
||||
MINISIGN_PASSWORD: ${{ secrets.MINISIGN_PASSWORD }}
|
||||
run: |
|
||||
set -ex
|
||||
# Install the minisign CLI (pure Go, ~2s).
|
||||
go install aead.dev/minisign/cmd/minisign@latest
|
||||
|
||||
# Generate sha256sums.txt from the built binaries.
|
||||
cd dist
|
||||
sha256sum nadir-* > sha256sums.txt
|
||||
cat sha256sums.txt
|
||||
|
||||
# Write the secret key to a temp file, sign, shred it.
|
||||
KEYFILE=$(mktemp)
|
||||
trap 'shred -u "$KEYFILE" 2>/dev/null || rm -f "$KEYFILE"' EXIT
|
||||
printf '%s\n' "$MINISIGN_SECRET_KEY" > "$KEYFILE"
|
||||
|
||||
# minisign -Sm signs the file, reading the key from -s and password
|
||||
# from stdin. The .minisig is written next to the input file.
|
||||
printf '%s' "$MINISIGN_PASSWORD" | minisign -Sm sha256sums.txt -s "$KEYFILE" -t "nadir release"
|
||||
ls -la sha256sums.txt sha256sums.txt.minisig
|
||||
|
||||
- name: Tag and release
|
||||
if: steps.ver.outputs.release == 'true'
|
||||
env:
|
||||
|
||||
+3
-1
@@ -11,4 +11,6 @@ config.yml
|
||||
# Editor
|
||||
*.swp
|
||||
|
||||
CLAUDE.md
|
||||
CLAUDE.md
|
||||
|
||||
minisign.key
|
||||
@@ -28,3 +28,14 @@ var InstallScriptTemplate string
|
||||
// go build -ldflags "-X nadir.Version=v1.2.3"
|
||||
// Local dev builds leave it as "dev".
|
||||
var Version = "dev"
|
||||
|
||||
// ReleasePublicKey is the minisign public key whose signature on a release's
|
||||
// sha256sums.txt is required by the auto-updater. Replacing the binary is the
|
||||
// most dangerous thing nadir does, so it gets the strongest verification: the
|
||||
// updater downloads sha256sums.txt + .minisig from the configured Gitea repo,
|
||||
// verifies the signature against this embedded key, then verifies the binary's
|
||||
// sha256 against the file. Rotation requires a rebuild — intentional, so a
|
||||
// compromised Gitea instance cannot also rotate the trust anchor.
|
||||
//
|
||||
//go:embed minisign.pub
|
||||
var ReleasePublicKey string
|
||||
|
||||
+35
-2
@@ -272,12 +272,24 @@ func runServer() {
|
||||
})
|
||||
|
||||
mux.HandleFunc("GET /docs", func(w http.ResponseWriter, _ *http.Request) {
|
||||
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
|
||||
// by secHeaders for this one page: allow scripts/styles from the jsdelivr
|
||||
// CDN plus inline (Scalar uses inline <script> + inline styles). The CDN
|
||||
// host is the supply-chain trust boundary; pinning a version + SRI here
|
||||
// is the follow-up (M5 partial).
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"connect-src 'self'; "+
|
||||
"font-src 'self' data: https://cdn.jsdelivr.net")
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write([]byte(`<!doctype html><html><head><title>API</title>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg"></head>
|
||||
<body><script id="api-reference" data-url="/openapi.json" data-configuration='{"layout":"classic"}'></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script></body></html>`))
|
||||
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" crossorigin="anonymous"></script></body></html>`))
|
||||
})
|
||||
|
||||
addr := cfg.Server.Hostname + ":" + cfg.Server.Port
|
||||
@@ -286,7 +298,7 @@ func runServer() {
|
||||
Addr: addr,
|
||||
// WithClientIP records the source IP for the login throttle (H1); behind a
|
||||
// trusted proxy it reads X-Forwarded-For instead of the proxy's address.
|
||||
Handler: auth.WithClientIP(cfg.Server.TrustProxy, mux),
|
||||
Handler: secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
|
||||
@@ -343,6 +355,27 @@ func runServer() {
|
||||
}
|
||||
}
|
||||
|
||||
// secHeaders sets defensive response headers on every HTTP response. The
|
||||
// default Content-Security-Policy denies everything (`default-src 'none'`) —
|
||||
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
|
||||
// overrides it with a CDN-permissive policy because the Scalar bundle needs
|
||||
// to execute.
|
||||
//
|
||||
// HSTS is set unconditionally: nadir always serves TLS directly or sits behind
|
||||
// a TLS-terminating proxy (config rejects any other shape), so a browser
|
||||
// receiving this header is on an HTTPS connection.
|
||||
func secHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
|
||||
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func ensureRoot() {
|
||||
if os.Getuid() != 0 {
|
||||
fatalIf(fmt.Errorf("nadir must run as root"))
|
||||
|
||||
+136
-3
@@ -1,6 +1,8 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -15,10 +17,13 @@ import (
|
||||
|
||||
"nadir"
|
||||
"nadir/internal/config"
|
||||
|
||||
"github.com/jedisct1/go-minisign"
|
||||
)
|
||||
|
||||
// updateCmd implements `nadir update`: hit the configured Gitea repo's
|
||||
// releases/latest, pick the asset for the host's GOARCH, atomically replace
|
||||
// releases/latest, pick the asset for the host's GOARCH, verify the release
|
||||
// signature (minisign) and checksum (SHA-256), atomically replace
|
||||
// /usr/local/bin/nadir (or wherever the running binary lives), and restart
|
||||
// the systemd unit so the new code takes effect.
|
||||
func updateCmd(args []string) error {
|
||||
@@ -66,16 +71,25 @@ func updateCmd(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Locate the binary asset and the two verification assets in the release.
|
||||
var assetURL, assetName string
|
||||
var sumsURL, sigURL string
|
||||
for _, a := range rel.Assets {
|
||||
if strings.HasSuffix(a.Name, suffix) {
|
||||
switch {
|
||||
case strings.HasSuffix(a.Name, suffix):
|
||||
assetURL, assetName = a.URL, a.Name
|
||||
break
|
||||
case a.Name == "sha256sums.txt":
|
||||
sumsURL = a.URL
|
||||
case a.Name == "sha256sums.txt.minisig":
|
||||
sigURL = a.URL
|
||||
}
|
||||
}
|
||||
if assetURL == "" {
|
||||
return fmt.Errorf("no %s asset in release %s", suffix, rel.TagName)
|
||||
}
|
||||
if sumsURL == "" || sigURL == "" {
|
||||
return fmt.Errorf("release %s is missing sha256sums.txt or sha256sums.txt.minisig — cannot verify; refusing to install an unverified binary", rel.TagName)
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
@@ -88,6 +102,15 @@ func updateCmd(args []string) error {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify: download checksums + signature, check minisign, check SHA-256.
|
||||
fmt.Println("verifying release signature ...")
|
||||
if err := verifyRelease(tmp, assetName, sumsURL, sigURL); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("verification failed: %w", err)
|
||||
}
|
||||
fmt.Println("signature and checksum OK.")
|
||||
|
||||
// Atomic on the same filesystem; replaces the on-disk file without
|
||||
// disturbing the still-running process (its inode stays alive).
|
||||
if err := os.Rename(tmp, exe); err != nil {
|
||||
@@ -103,6 +126,113 @@ func updateCmd(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyRelease downloads sha256sums.txt + its minisig from the release,
|
||||
// verifies the signature against the embedded public key, then checks the
|
||||
// downloaded binary's SHA-256 against the matching line in the checksums file.
|
||||
func verifyRelease(binaryPath, assetName, sumsURL, sigURL string) error {
|
||||
// Parse the embedded public key. The placeholder file will fail here
|
||||
// (no valid base64 line), which is the desired behavior: updates are
|
||||
// disabled until a real key is committed.
|
||||
pubKey, err := minisign.DecodePublicKey(nadir.ReleasePublicKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("embedded minisign public key is invalid (is minisign.pub still the placeholder?): %w", err)
|
||||
}
|
||||
|
||||
// Download the checksums file and its signature.
|
||||
sumsBody, err := downloadBytes(sumsURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download sha256sums.txt: %w", err)
|
||||
}
|
||||
sigBody, err := downloadBytes(sigURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download sha256sums.txt.minisig: %w", err)
|
||||
}
|
||||
|
||||
// Verify the minisign signature on the checksums file.
|
||||
sig, err := minisign.DecodeSignature(string(sigBody))
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode minisig: %w", err)
|
||||
}
|
||||
ok, err := pubKey.Verify(sumsBody, sig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("minisign verify: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("minisign signature is not valid for this sha256sums.txt")
|
||||
}
|
||||
|
||||
// Find the expected hash for our binary in the signed checksums file.
|
||||
expectedHash, err := findChecksum(string(sumsBody), assetName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash the downloaded binary and compare.
|
||||
actualHash, err := sha256File(binaryPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hash downloaded binary: %w", err)
|
||||
}
|
||||
if actualHash != expectedHash {
|
||||
return fmt.Errorf("SHA-256 mismatch for %s: expected %s, got %s", assetName, expectedHash, actualHash)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// findChecksum parses a sha256sums.txt body (one "hash filename\n" per line)
|
||||
// and returns the hex hash for the named asset.
|
||||
func findChecksum(sums, assetName string) (string, error) {
|
||||
for _, line := range strings.Split(sums, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
// Standard sha256sum output: "<hex> <filename>" (two spaces).
|
||||
parts := strings.SplitN(line, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
// Also accept single-space separation.
|
||||
parts = strings.SplitN(line, " ", 2)
|
||||
}
|
||||
if len(parts) == 2 && strings.TrimSpace(parts[1]) == assetName {
|
||||
h := strings.TrimSpace(parts[0])
|
||||
if len(h) != 64 {
|
||||
return "", fmt.Errorf("sha256sums.txt: invalid hash length for %s: %q", assetName, h)
|
||||
}
|
||||
return strings.ToLower(h), nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("sha256sums.txt does not contain a hash for %s", assetName)
|
||||
}
|
||||
|
||||
// sha256File returns the lowercase hex SHA-256 of the file at path.
|
||||
func sha256File(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// downloadBytes fetches a URL and returns its body as a byte slice (for small
|
||||
// files like sha256sums.txt and .minisig).
|
||||
func downloadBytes(srcURL string) ([]byte, error) {
|
||||
c := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := c.Get(srcURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: %s", srcURL, resp.Status)
|
||||
}
|
||||
// Cap read to 1 MB — sha256sums.txt and .minisig are tiny.
|
||||
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
}
|
||||
|
||||
type giteaRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Assets []struct {
|
||||
@@ -136,6 +266,9 @@ func releaseAPIURL(repoURL string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("release_repo: %w", err)
|
||||
}
|
||||
if u.Scheme != "https" {
|
||||
return "", fmt.Errorf("release_repo must use https:// (got %q) — auto-update downloads and executes the binary, plaintext would let any on-path attacker replace it", repoURL)
|
||||
}
|
||||
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", fmt.Errorf("release_repo must look like https://host/owner/repo, got %q", repoURL)
|
||||
|
||||
@@ -7,19 +7,21 @@ require github.com/msteinert/pam v1.2.0
|
||||
require github.com/danielgtaylor/huma/v2 v2.38.0
|
||||
|
||||
require (
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.52.0
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/creack/pty v1.1.24
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.52.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22 // indirect
|
||||
github.com/mattn/go-isatty v0.0.21 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
modernc.org/libc v1.72.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
|
||||
@@ -16,6 +16,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22 h1:C68TAi+k12EKJCAmsdaERzQ22ZxVE6n+CuB3kOkhQ7c=
|
||||
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22/go.mod h1:vYVVh81Lqe/TP0sPLjiNYcX9Hxy/YSfkUx96lYJeyKo=
|
||||
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
|
||||
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
|
||||
@@ -30,12 +32,16 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
|
||||
@@ -60,6 +60,40 @@ do_install() {
|
||||
|
||||
echo "downloading $asset_url ..."
|
||||
curl -f --progress-bar -L "$asset_url" -o /usr/local/bin/nadir.tmp
|
||||
|
||||
asset_name=$(basename "$asset_url")
|
||||
|
||||
# Verify SHA-256: download the checksums file published alongside the binary
|
||||
# and confirm the hash matches. This catches CDN corruption and (together with
|
||||
# the HTTPS transport) makes tampered binaries detectable.
|
||||
sums_url="$host/api/v1/repos/$path/releases/latest"
|
||||
sums_asset_url=$(curl -fsSL "$sums_url" \
|
||||
| grep -o '"browser_download_url":"[^"]*sha256sums\.txt"' \
|
||||
| head -n1 \
|
||||
| cut -d'"' -f4)
|
||||
|
||||
if [ -n "$sums_asset_url" ]; then
|
||||
echo "verifying checksum ..."
|
||||
curl -fsSL "$sums_asset_url" -o /tmp/nadir-sha256sums.txt
|
||||
# Extract the expected hash for our asset and compare.
|
||||
expected=$(grep "$asset_name" /tmp/nadir-sha256sums.txt | awk '{print $1}')
|
||||
actual=$(sha256sum /usr/local/bin/nadir.tmp | awk '{print $1}')
|
||||
rm -f /tmp/nadir-sha256sums.txt
|
||||
if [ -z "$expected" ]; then
|
||||
echo "warning: sha256sums.txt does not contain a hash for $asset_name" >&2
|
||||
echo "proceeding without verification" >&2
|
||||
elif [ "$expected" != "$actual" ]; then
|
||||
echo "SHA-256 MISMATCH: expected $expected, got $actual" >&2
|
||||
echo "the downloaded binary may be corrupted or tampered with — aborting" >&2
|
||||
rm -f /usr/local/bin/nadir.tmp
|
||||
exit 1
|
||||
else
|
||||
echo "checksum OK ($actual)"
|
||||
fi
|
||||
else
|
||||
echo "warning: no sha256sums.txt in release — skipping verification" >&2
|
||||
fi
|
||||
|
||||
mv /usr/local/bin/nadir.tmp /usr/local/bin/nadir
|
||||
chmod +x /usr/local/bin/nadir
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"nadir/internal/auditlog"
|
||||
@@ -10,6 +11,11 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
|
||||
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
|
||||
// the terminal handler or showing up verbatim in audit logs / throttle keys.
|
||||
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
|
||||
|
||||
// authenticator verifies a username/password (PAM in production). It's a field
|
||||
// of the login handler rather than a package global so tests can inject a stub
|
||||
// without mutating shared state.
|
||||
@@ -53,6 +59,11 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
|
||||
Tags: []string{"Authentication"},
|
||||
Errors: []int{401, 429},
|
||||
}, func(ctx context.Context, in *LoginInput) (*LoginOutput, error) {
|
||||
// Reject malformed usernames at the trust boundary so PAM, su, and the
|
||||
// audit log never see flag-like or shell-metacharacter input.
|
||||
if !loginNameRe.MatchString(in.Body.Username) {
|
||||
return nil, huma.Error401Unauthorized("invalid credentials")
|
||||
}
|
||||
// Throttle brute force: too many recent failures for this account/source
|
||||
// put it in a short cooldown before the password is even checked.
|
||||
throttleKey := in.Body.Username + "|" + ClientIP(ctx)
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -108,6 +109,15 @@ func Load(path string) (*File, error) {
|
||||
if err := yaml.Unmarshal(data, &f); err != nil {
|
||||
return nil, fmt.Errorf("parse config %s: %w", path, err)
|
||||
}
|
||||
// release_repo, when set, is downloaded over the wire and (for /api/update)
|
||||
// executed. Reject http:// at the boundary so /install.sh and the updater
|
||||
// never have to re-check.
|
||||
if f.Server.ReleaseRepo != "" {
|
||||
u, err := url.Parse(f.Server.ReleaseRepo)
|
||||
if err != nil || u.Scheme != "https" {
|
||||
return nil, fmt.Errorf("server.release_repo must use https:// (got %q)", f.Server.ReleaseRepo)
|
||||
}
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"nadir/internal/oscmd"
|
||||
@@ -9,6 +10,11 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
)
|
||||
|
||||
// hostnameRe matches RFC-1123 labels joined by dots, max 253 chars total. Anchored
|
||||
// so a leading "-" can't be read as a hostnamectl flag and shell metacharacters
|
||||
// can't survive — same pattern the other modules use (CLAUDE.md §5).
|
||||
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}))*$`)
|
||||
|
||||
type HostnameBody struct {
|
||||
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
|
||||
}
|
||||
@@ -49,7 +55,10 @@ func registerHostname(api huma.API) {
|
||||
if name == "" {
|
||||
return nil, huma.Error400BadRequest("empty hostname")
|
||||
}
|
||||
if _, err := oscmd.Run("hostnamectl", "set-hostname", name); err != nil {
|
||||
if len(name) > 253 || !hostnameRe.MatchString(name) {
|
||||
return nil, huma.Error400BadRequest("invalid hostname: " + name)
|
||||
}
|
||||
if _, err := oscmd.Run("hostnamectl", "set-hostname", "--", name); err != nil {
|
||||
return nil, huma.Error500InternalServerError("hostnamectl failed", err)
|
||||
}
|
||||
return oscmd.OK(), nil
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
@@ -161,7 +162,19 @@ func cpuInfo() CPUInfo {
|
||||
// ponytail: cpufreq sysfs is absent on many VMs and stock Ubuntu server
|
||||
// kernels; fall back to /proc/cpuinfo "cpu MHz" — VMs have a fixed clock,
|
||||
// so min == max == cur is the honest answer.
|
||||
if mhz := cpuinfoMaxMHz(string(data)); mhz > 0 {
|
||||
mhz := cpuinfoMaxMHz(string(data))
|
||||
// ponytail: ARM /proc/cpuinfo has no "cpu MHz" and often no "model name";
|
||||
// lscpu decodes the ARM part-id table and reads DMI, so use it as last resort.
|
||||
if c.Model == "" || mhz == 0 {
|
||||
model, lscpuMHz := lscpuFallback()
|
||||
if c.Model == "" {
|
||||
c.Model = model
|
||||
}
|
||||
if mhz == 0 {
|
||||
mhz = lscpuMHz
|
||||
}
|
||||
}
|
||||
if mhz > 0 {
|
||||
if c.CurrentMHz == 0 {
|
||||
c.CurrentMHz = mhz
|
||||
}
|
||||
@@ -175,6 +188,56 @@ func cpuInfo() CPUInfo {
|
||||
return c
|
||||
}
|
||||
|
||||
// lscpuFallback parses `lscpu` for "Model name" and any embedded "@ X.X GHz"
|
||||
// or "CPU max MHz:" value. Returns zeros when lscpu is missing or silent.
|
||||
func lscpuFallback() (model string, mhz int) {
|
||||
out, err := exec.Command("lscpu").Output()
|
||||
if err != nil {
|
||||
return "", 0
|
||||
}
|
||||
for line := range strings.SplitSeq(string(out), "\n") {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
|
||||
switch k {
|
||||
case "Model name":
|
||||
if model == "" {
|
||||
model = v
|
||||
}
|
||||
case "BIOS Model name":
|
||||
if model == "" {
|
||||
model = v
|
||||
}
|
||||
case "CPU max MHz", "CPU MHz":
|
||||
if f, err := strconv.ParseFloat(v, 64); err == nil && int(f) > mhz {
|
||||
mhz = int(math.Round(f))
|
||||
}
|
||||
}
|
||||
}
|
||||
if mhz == 0 {
|
||||
mhz = parseGHzSuffix(model)
|
||||
}
|
||||
return model, mhz
|
||||
}
|
||||
|
||||
// parseGHzSuffix pulls "2.0GHz" / "@ 2.0 GHz" out of a model string.
|
||||
func parseGHzSuffix(s string) int {
|
||||
i := strings.LastIndex(s, "@")
|
||||
if i < 0 {
|
||||
return 0
|
||||
}
|
||||
rest := strings.TrimSpace(s[i+1:])
|
||||
rest = strings.TrimSuffix(strings.TrimSuffix(rest, "GHz"), "Ghz")
|
||||
rest = strings.TrimSpace(strings.TrimSuffix(rest, "G"))
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(rest), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return int(math.Round(f * 1000))
|
||||
}
|
||||
|
||||
// cpuinfoMaxMHz returns the highest "cpu MHz" value across all cores in
|
||||
// /proc/cpuinfo, rounded to an int. Returns 0 when no such line exists.
|
||||
func cpuinfoMaxMHz(cpuinfo string) int {
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestSystemHandlers(t *testing.T) {
|
||||
if reflect.DeepEqual(args, []string{"hostname"}) {
|
||||
return oscmd.MockCommand{Stdout: "server01\n", ExitCode: 0}
|
||||
}
|
||||
if reflect.DeepEqual(args, []string{"set-hostname", "server02"}) {
|
||||
if reflect.DeepEqual(args, []string{"set-hostname", "--", "server02"}) {
|
||||
return oscmd.MockCommand{ExitCode: 0}
|
||||
}
|
||||
return oscmd.MockCommand{ExitCode: 1}
|
||||
|
||||
@@ -126,7 +126,7 @@ func (m *terminalModule) Register(api huma.API) {
|
||||
|
||||
// Launch the user's login shell via su.
|
||||
// "su - <username>" ensures we get their actual environment and shell.
|
||||
cmd := exec.CommandContext(req.Context(), "su", "-", sess.Username)
|
||||
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
|
||||
|
||||
// Start the command with a PTY.
|
||||
ptmx, err := pty.Start(cmd)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
untrusted comment: minisign public key: 702ABD7F45200669
|
||||
RWRpBiBFf70qcEXS0cOS+8tZ1hpoLj9mX0V5OiE8qYIIZsetU8hNA4Ou
|
||||
Reference in New Issue
Block a user