Security fixes for v2026.11.18 #77
No files matched your search
+93
-16
@@ -23,9 +23,11 @@ import (
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -40,15 +42,15 @@ import (
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state"
|
||||
)
|
||||
|
||||
// Images are the defaults. They are tags rather than digests for now: the
|
||||
// registry is ours and the tags are immutable releases, and pinning digests
|
||||
// here would mean this program needing a release of its own for every one of
|
||||
// theirs.
|
||||
// Images are the defaults. The suite's own name one release each, by tag:
|
||||
// the registry is ours, but its tags can be pushed again by anyone holding a
|
||||
// push token, so they are a release's name rather than a guarantee of its
|
||||
// contents. Caddy, from Docker Hub, is pinned by digest (release.CaddyImage).
|
||||
const (
|
||||
DefaultServerImage = release.ServerImage
|
||||
DefaultConsoleImage = "registry.coffeylabs.org/inbuxa/inbuxa-admin:" + release.ConsoleVersion
|
||||
DefaultWebmailImage = "registry.coffeylabs.org/inbuxa/inbuxa-webmail:" + release.WebmailVersion
|
||||
DefaultCaddyImage = "docker.io/library/caddy:2-alpine"
|
||||
DefaultCaddyImage = release.CaddyImage
|
||||
DefaultSubnet = "172.31.253.0/24"
|
||||
// DefaultIPv6Subnet is a unique local /64 for the same network, on a
|
||||
// machine with IPv6 (#65). Nothing outside the machine ever sees it.
|
||||
@@ -330,12 +332,12 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
override := filepath.Join(os.TempDir(), "inbuxa-bootstrap.yaml")
|
||||
if err := os.WriteFile(override, []byte(
|
||||
"services:\n server:\n environment:\n INBUXA_RECOVERY_ADMIN: ${INBUXA_BOOTSTRAP_ADMIN:?}\n"), 0o600); err != nil {
|
||||
override, cleanup, err := setupOverride("inbuxa-bootstrap.yaml",
|
||||
"services:\n server:\n environment:\n INBUXA_RECOVERY_ADMIN: ${INBUXA_BOOTSTRAP_ADMIN:?}\n")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.Remove(override)
|
||||
defer cleanup()
|
||||
|
||||
log.Step("starting the mail server in bootstrap mode")
|
||||
serverURL := "http://" + stack.ServerBind
|
||||
@@ -364,7 +366,7 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro
|
||||
return nil, withLogs(ctx, err, srvLogs, "server")
|
||||
}
|
||||
|
||||
bootClient := &jmap.Client{BaseURL: serverURL, Username: "admin", Password: bootPass}
|
||||
bootClient := setupClient(onHost, jmap.Client{BaseURL: serverURL, Username: "admin", Password: bootPass})
|
||||
if err := bootClient.CheckBootstrapMode(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -397,12 +399,12 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro
|
||||
// does the rest of the setup, is removed when the setup ends, and expires
|
||||
// within the hour anyway, so a setup that stops halfway leaves nothing
|
||||
// that still works.
|
||||
basicOverride := filepath.Join(os.TempDir(), "inbuxa-basic-auth.yaml")
|
||||
if err := os.WriteFile(basicOverride, []byte(
|
||||
"services:\n server:\n environment:\n INBUXA_HTTP_BASIC_AUTH: all\n"), 0o600); err != nil {
|
||||
basicOverride, cleanupBasic, err := setupOverride("inbuxa-basic-auth.yaml",
|
||||
"services:\n server:\n environment:\n INBUXA_HTTP_BASIC_AUTH: all\n")
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
defer os.Remove(basicOverride)
|
||||
defer cleanupBasic()
|
||||
log.Step("restarting the mail server configured, to give the setup an API key")
|
||||
if onHost {
|
||||
if err := hs.Start(ctx, modeBasic, ""); err != nil {
|
||||
@@ -415,7 +417,7 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
adminBasic := &jmap.Client{BaseURL: serverURL, Username: admin.Username, Password: admin.Secret}
|
||||
adminBasic := setupClient(onHost, jmap.Client{BaseURL: serverURL, Username: admin.Username, Password: admin.Secret})
|
||||
var keyID, key string
|
||||
if err := waitFor(ctx, log, "the server to come back configured", 120*time.Second, func(ctx context.Context) error {
|
||||
var err error
|
||||
@@ -424,7 +426,7 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro
|
||||
}); err != nil {
|
||||
return res, withLogs(ctx, fmt.Errorf("an API key for the setup: %w", err), srvLogs, "server")
|
||||
}
|
||||
srv := &jmap.Client{BaseURL: serverURL, Token: key}
|
||||
srv := setupClient(onHost, jmap.Client{BaseURL: serverURL, Token: key})
|
||||
defer func() {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
@@ -953,3 +955,78 @@ func password(n int) (string, error) {
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// setupOverride writes a compose override for one step of first boot, and
|
||||
// returns its path and what removes it. It goes in a new directory only root
|
||||
// can reach, never at a fixed name in the shared temporary directory, where
|
||||
// another local user could have put a file or a link of its own first.
|
||||
func setupOverride(name, content string) (string, func(), error) {
|
||||
dir, err := os.MkdirTemp("", "inbuxa-setup-")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
cleanup := func() { os.RemoveAll(dir) }
|
||||
path := filepath.Join(dir, name)
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err == nil {
|
||||
_, err = f.WriteString(content)
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
return path, cleanup, nil
|
||||
}
|
||||
|
||||
// setupClient is a client for the server at a loopback address, carrying
|
||||
// the administrator's password or an API key. On the host those are ports
|
||||
// 8080 and 8081, which any local user may listen on while the installer
|
||||
// restarts the server: so before each request, whatever listens there must
|
||||
// be the server the unit started, or nothing is sent. In a container the
|
||||
// runtime publishes the port and nobody else can take it.
|
||||
//
|
||||
// The check is of the client's address at the time of each request, as
|
||||
// first boot moves its client from 8080 to 8081 once the listeners are
|
||||
// fitted.
|
||||
func setupClient(onHost bool, c jmap.Client) *jmap.Client {
|
||||
cl := &c
|
||||
if onHost {
|
||||
cl.Guard = func(ctx context.Context) error { return serversOwnListener(ctx, cl.BaseURL) }
|
||||
}
|
||||
return cl
|
||||
}
|
||||
|
||||
// serversOwnListener is nil when what listens on base's port is the host
|
||||
// server unit's main process.
|
||||
func serversOwnListener(ctx context.Context, base string) error {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
port, err := strconv.Atoi(u.Port())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s names no port", base)
|
||||
}
|
||||
pid := serverMainPID(ctx)
|
||||
if pid <= 0 {
|
||||
return fmt.Errorf("%s is not running", HostServerUnit)
|
||||
}
|
||||
if err := host.PortHeldBy(port, pid); err != nil {
|
||||
return fmt.Errorf("%w; the mail server is pid %d, so nothing was sent there", err, pid)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// serverMainPID is the host server unit's main process, or 0; a variable so
|
||||
// a test can stand in for systemd.
|
||||
var serverMainPID = func(ctx context.Context) int {
|
||||
out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", HostServerUnit).Output()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
pid, _ := strconv.Atoi(strings.TrimSpace(string(out)))
|
||||
return pid
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package apply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The server's user can write its home, so it can swap data/ for a symbolic
|
||||
// link to a directory of root's. Install runs again as root on every
|
||||
// converge or move, and must not then give that directory to the server's
|
||||
// user (INSTALLER-1).
|
||||
func TestServerDirsRefusesALinkedDataDir(t *testing.T) {
|
||||
deploy := t.TempDir()
|
||||
victim := t.TempDir() // a directory of root's, as far as the installer knows
|
||||
h := hostServer{deploy: deploy}
|
||||
if err := os.MkdirAll(h.home(), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(victim, filepath.Join(h.home(), "data")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var chowned []string
|
||||
defer func(f func(context.Context, ...string) error) { chownServer = f }(chownServer)
|
||||
chownServer = func(_ context.Context, args ...string) error {
|
||||
chowned = append(chowned, strings.Join(args, " "))
|
||||
return nil
|
||||
}
|
||||
|
||||
err := h.serverDirs(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "symbolic link") {
|
||||
t.Errorf("a data directory that is a symbolic link should be refused, got %v", err)
|
||||
}
|
||||
for _, c := range chowned {
|
||||
// chown follows a link it is given unless told -h, and always
|
||||
// through a trailing slash.
|
||||
if !strings.HasPrefix(c, "-h ") || strings.HasSuffix(c, "/") || strings.Contains(c, "/data") {
|
||||
t.Errorf("chown %s: would reach the link's target", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A first install, and a converge over directories already right, make
|
||||
// both and give them to the server's user without following anything.
|
||||
func TestServerDirsMakesBoth(t *testing.T) {
|
||||
h := hostServer{deploy: t.TempDir()}
|
||||
var chowned []string
|
||||
defer func(f func(context.Context, ...string) error) { chownServer = f }(chownServer)
|
||||
chownServer = func(_ context.Context, args ...string) error {
|
||||
chowned = append(chowned, strings.Join(args, " "))
|
||||
return nil
|
||||
}
|
||||
for range 2 {
|
||||
chowned = nil
|
||||
if err := h.serverDirs(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{
|
||||
"-h inbuxa:inbuxa " + h.home(),
|
||||
"-h inbuxa:inbuxa " + filepath.Join(h.home(), "data"),
|
||||
}
|
||||
if strings.Join(chowned, "|") != strings.Join(want, "|") {
|
||||
t.Errorf("chown %v, want %v", chowned, want)
|
||||
}
|
||||
if fi, err := os.Lstat(filepath.Join(h.home(), "data")); err != nil || !fi.IsDir() {
|
||||
t.Errorf("data/ is not a directory: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ package apply
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -122,17 +123,65 @@ func (h hostServer) Install(ctx context.Context) (replaced bool, err error) {
|
||||
if err := os.Chmod(h.deploy, 0o711); err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, d := range []string{h.home(), h.DataPath()} {
|
||||
if err := os.MkdirAll(d, 0o750); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := runQuiet(ctx, "chown", HostServerUser+":"+HostServerUser, d); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := h.serverDirs(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return replaced, nil
|
||||
}
|
||||
|
||||
// chownServer runs chown; a variable so a test can watch it without root.
|
||||
var chownServer = func(ctx context.Context, args ...string) error {
|
||||
return runQuiet(ctx, "chown", args...)
|
||||
}
|
||||
|
||||
// serverDirs makes the server's home and its data directory and gives them
|
||||
// to the server's user. The home is in the deployment directory, which is
|
||||
// root's, but data/ is in the home, which that user can write: something
|
||||
// running as it could have put a symbolic link there, and following the
|
||||
// link would give it whatever directory the link names. So a data/ that is
|
||||
// not a plain directory is refused, and chown is given -h and no trailing
|
||||
// slash, so a link swapped in after the check is what changes owner, not
|
||||
// what it points at.
|
||||
func (h hostServer) serverDirs(ctx context.Context) error {
|
||||
for _, d := range []string{h.home(), filepath.Join(h.home(), "data")} {
|
||||
if err := plainDir(d, 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := chownServer(ctx, "-h", HostServerUser+":"+HostServerUser, d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// plainDir makes dir when it is not there, and refuses one that is a
|
||||
// symbolic link or not a directory at all.
|
||||
func plainDir(dir string, mode os.FileMode) error {
|
||||
fi, err := os.Lstat(dir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if err := os.Mkdir(dir, mode); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
fi, err = os.Lstat(dir)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return isPlainDir(dir, fi)
|
||||
}
|
||||
|
||||
func isPlainDir(dir string, fi os.FileInfo) error {
|
||||
switch {
|
||||
case fi.Mode()&os.ModeSymlink != 0:
|
||||
return fmt.Errorf("%s is a symbolic link, where the installer keeps a directory of the server's; "+
|
||||
"nothing was changed through it. Something running as %s may have put it there: look at where it points, "+
|
||||
"then move it aside and run this again", dir, HostServerUser)
|
||||
case !fi.IsDir():
|
||||
return fmt.Errorf("%s is not a directory", dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h hostServer) fetchBinary(ctx context.Context) error {
|
||||
arch := runtime.GOARCH
|
||||
sum, ok := release.ServerSHA256[arch]
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package apply
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Everything this installer downloads as a file is checked against a
|
||||
// checksum in its source. Caddy, the proxy that holds the TLS keys, was
|
||||
// pulled by a floating tag from Docker Hub instead, so whoever could push
|
||||
// that tag chose what ran (INSTALLER-5). It is pinned by its digest now.
|
||||
func TestCaddyIsPinnedByDigest(t *testing.T) {
|
||||
if !regexp.MustCompile(`@sha256:[0-9a-f]{64}$`).MatchString(DefaultCaddyImage) {
|
||||
t.Errorf("DefaultCaddyImage = %q, not pinned by digest", DefaultCaddyImage)
|
||||
}
|
||||
}
|
||||
|
||||
// The suite's own images name one exact release, never a moving tag. The
|
||||
// webmail's releases on this line are named by version and commit.
|
||||
func TestSuiteImagesNameAnExactRelease(t *testing.T) {
|
||||
exact := regexp.MustCompile(`:\d+\.\d+(\.\d+)*(-rc\.\d+|-g[0-9a-f]+)?$`)
|
||||
for _, img := range []string{DefaultServerImage, DefaultConsoleImage, DefaultWebmailImage} {
|
||||
if !exact.MatchString(img) {
|
||||
t.Errorf("%s does not name an exact release", img)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package apply
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/jmap"
|
||||
)
|
||||
|
||||
// squatter listens on loopback as this test's own process and records the
|
||||
// Authorization header of anything sent to it.
|
||||
func squatter(t *testing.T) (url string, seen func() []string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
got = append(got, r.Header.Get("Authorization"))
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), got...)
|
||||
}
|
||||
}
|
||||
|
||||
// During a host first boot or a move the server is restarted and then sent
|
||||
// the administrator's password or an API key on 127.0.0.1:8080 or :8081,
|
||||
// ports any local user may listen on while the server is down. What answers
|
||||
// there must be the server the unit started before anything is sent to it
|
||||
// (INSTALLER-4). Here the listener is this test's, and the unit's main
|
||||
// process is another one.
|
||||
func TestSetupCredentialsGoOnlyToTheServersOwnListener(t *testing.T) {
|
||||
url, seen := squatter(t)
|
||||
defer func(f func(context.Context) int) { serverMainPID = f }(serverMainPID)
|
||||
serverMainPID = func(context.Context) int { return os.Getppid() }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
admin := setupClient(true, jmap.Client{BaseURL: url, Username: "admin", Password: "the-admin-password"})
|
||||
if _, _, err := admin.CreateAPIKey(ctx, "setup", time.Hour); err == nil {
|
||||
t.Error("an API key was made through a listener that isn't the server's")
|
||||
}
|
||||
keyed := setupClient(true, jmap.Client{BaseURL: url, Token: "the-api-key"})
|
||||
if err := keyed.HostListeners(ctx, hostFinalBind, false); err == nil {
|
||||
t.Error("the listeners were fitted through a listener that isn't the server's")
|
||||
}
|
||||
if got := seen(); len(got) != 0 {
|
||||
t.Errorf("credentials went to a listener that isn't the server's: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// When the listener is the server's, the request goes through; and a
|
||||
// container's server, reached through the runtime's port, is not checked.
|
||||
func TestSetupCredentialsGoToTheServer(t *testing.T) {
|
||||
url, seen := squatter(t)
|
||||
defer func(f func(context.Context) int) { serverMainPID = f }(serverMainPID)
|
||||
serverMainPID = func(context.Context) int { return os.Getpid() }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
setupClient(true, jmap.Client{BaseURL: url, Token: "k"}).Listeners(ctx)
|
||||
serverMainPID = func(context.Context) int { return os.Getppid() }
|
||||
setupClient(false, jmap.Client{BaseURL: url, Token: "k"}).Listeners(ctx)
|
||||
if got := seen(); len(got) != 2 {
|
||||
t.Errorf("want both requests sent, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// First boot moves its client from 8080 to 8081 once the listeners are
|
||||
// fitted; the check follows it there.
|
||||
func TestSetupCredentialsCheckTheClientsCurrentAddress(t *testing.T) {
|
||||
old, _ := squatter(t)
|
||||
url, seen := squatter(t)
|
||||
defer func(f func(context.Context) int) { serverMainPID = f }(serverMainPID)
|
||||
serverMainPID = func(context.Context) int { return os.Getpid() }
|
||||
srv := setupClient(true, jmap.Client{BaseURL: old, Token: "k"})
|
||||
srv.BaseURL = url
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
srv.Listeners(ctx)
|
||||
if got := seen(); len(got) != 1 {
|
||||
t.Errorf("want the request sent to the new address, got %q", got)
|
||||
}
|
||||
// Both of the test's listeners are its own, so stand in a listener
|
||||
// that is not: a closed one, where nothing listens any more.
|
||||
srv.BaseURL = "http://127.0.0.1:1"
|
||||
if err := serversOwnListener(ctx, srv.BaseURL); err == nil {
|
||||
t.Error("a port nothing listens on passed the check")
|
||||
}
|
||||
}
|
||||
+52
-5
@@ -34,6 +34,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/compose"
|
||||
@@ -310,7 +311,7 @@ func (m *serverMove) toHost(ctx context.Context, stack compose.Stack, snippets b
|
||||
if err := m.cameBack(ctx, hostSetupBind, func() string { return hs.Logs(ctx, "server", 400) }); err != nil {
|
||||
return back(withLogs(ctx, err, hs, "server"))
|
||||
}
|
||||
srv := &jmap.Client{BaseURL: hostSetupBind, Token: m.key}
|
||||
srv := setupClient(true, jmap.Client{BaseURL: hostSetupBind, Token: m.key})
|
||||
if err := srv.HostListeners(ctx, hostFinalBind, m.local); err != nil {
|
||||
return back(fmt.Errorf("fitting the server's listeners to the host: %w", err))
|
||||
}
|
||||
@@ -456,6 +457,12 @@ func (m *serverMove) restoreHost(ctx context.Context, why error) error {
|
||||
// copied into it: what an earlier install on the host left there is
|
||||
// archived, never mixed with this.
|
||||
func (m *serverMove) clearForCopy(ctx context.Context, hs hostServer) error {
|
||||
data := filepath.Join(hs.home(), "data")
|
||||
if fi, err := os.Lstat(data); err == nil {
|
||||
if err := isPlainDir(data, fi); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
entries, _ := os.ReadDir(hs.DataPath())
|
||||
if len(entries) == 0 && !exists(hs.configPath()) {
|
||||
return nil
|
||||
@@ -504,8 +511,17 @@ func allowOnce(ctx context.Context, srv *jmap.Client, address, reason string) er
|
||||
// rewriteDataPath points the data store's description at its new home. Only
|
||||
// a path under the old home is changed: a store kept elsewhere (PostgreSQL,
|
||||
// a path the operator chose) is left alone.
|
||||
//
|
||||
// config.json is in the server's home, which the server's user can write, so
|
||||
// it is read without following a link and replaced by a rename, never
|
||||
// written through whatever is there.
|
||||
func rewriteDataPath(configPath, from, to string) error {
|
||||
b, err := os.ReadFile(configPath)
|
||||
f, err := openNoFollow(configPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the server's configuration: %w", err)
|
||||
}
|
||||
b, err := io.ReadAll(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the server's configuration: %w", err)
|
||||
}
|
||||
@@ -522,11 +538,42 @@ func rewriteDataPath(configPath, from, to string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Stat(configPath)
|
||||
info, err := os.Lstat(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(configPath, out, info.Mode().Perm())
|
||||
return replaceFile(configPath, out, info.Mode().Perm())
|
||||
}
|
||||
|
||||
// openNoFollow opens a file for reading, refusing a symbolic link.
|
||||
func openNoFollow(path string) (*os.File, error) {
|
||||
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if errors.Is(err, syscall.ELOOP) {
|
||||
return nil, fmt.Errorf("%s is a symbolic link, which the installer will not follow there", path)
|
||||
}
|
||||
return f, err
|
||||
}
|
||||
|
||||
// replaceFile puts content at path by writing a new file beside it and
|
||||
// renaming it over the old one: a link at path is replaced, not followed.
|
||||
func replaceFile(path string, content []byte, mode os.FileMode) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(content); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(mode); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
|
||||
// moveContents renames everything in src into dest, which is made if need
|
||||
@@ -550,7 +597,7 @@ func moveContents(src, dest string) error {
|
||||
}
|
||||
|
||||
func copyFile(src, dest string, mode os.FileMode) error {
|
||||
in, err := os.Open(src)
|
||||
in, err := openNoFollow(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -108,3 +108,28 @@ func TestMovedContentsArriveAndLeaveTheStageEmpty(t *testing.T) {
|
||||
t.Errorf("nothing to move is not an error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// config.json is in the server's home, which its user can write. A move runs
|
||||
// as root and must not read or write through a link planted there
|
||||
// (INSTALLER-1).
|
||||
func TestRewriteDataPathRefusesALink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
victim := filepath.Join(t.TempDir(), "root.json")
|
||||
body := `{"path":"/var/lib/inbuxa/x","secret":"root's"}`
|
||||
if err := os.WriteFile(victim, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := filepath.Join(dir, "config.json")
|
||||
if err := os.Symlink(victim, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rewriteDataPath(cfg, containerDataPath, "/var/lib/inbuxa/server/data/"); err == nil {
|
||||
t.Error("a config.json that is a symbolic link should be refused")
|
||||
}
|
||||
if b, _ := os.ReadFile(victim); string(b) != body {
|
||||
t.Errorf("written through the link: %s", b)
|
||||
}
|
||||
if err := copyFile(cfg, filepath.Join(dir, "staged.json"), 0o640); err == nil {
|
||||
t.Error("copying a config.json that is a symbolic link should be refused")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package apply
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The setup's compose overrides are given to docker compose as root. Put at a
|
||||
// fixed name in the shared temporary directory, they could be planted
|
||||
// beforehand by any local user: as a link, to have root write over another
|
||||
// file, or as their own file, to rewrite it after root wrote it
|
||||
// (INSTALLER-3). Each now goes in a directory of its own that only root can
|
||||
// reach, and is gone after.
|
||||
func TestSetupOverrideIsNotAtAFixedNameInTmp(t *testing.T) {
|
||||
shared := t.TempDir()
|
||||
t.Setenv("TMPDIR", shared)
|
||||
victim := filepath.Join(t.TempDir(), "victim")
|
||||
if err := os.WriteFile(victim, []byte("root's\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"inbuxa-bootstrap.yaml", "inbuxa-basic-auth.yaml"} {
|
||||
if err := os.Symlink(victim, filepath.Join(shared, name)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
path, cleanup, err := setupOverride("inbuxa-bootstrap.yaml", "services: {}\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(victim); string(b) != "root's\n" {
|
||||
t.Errorf("written through a planted link: %q", b)
|
||||
}
|
||||
if b, _ := os.ReadFile(path); string(b) != "services: {}\n" {
|
||||
t.Errorf("the override holds %q", b)
|
||||
}
|
||||
dir := filepath.Dir(path)
|
||||
if dir == shared {
|
||||
t.Errorf("%s is straight in the shared temporary directory", path)
|
||||
} else if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
|
||||
t.Errorf("%s should be a directory only its owner can reach: %v %v", dir, fi, err)
|
||||
}
|
||||
cleanup()
|
||||
if _, err := os.Lstat(dir); err == nil && dir != shared {
|
||||
t.Errorf("%s is left behind", dir)
|
||||
}
|
||||
}
|
||||
+28
-3
@@ -31,6 +31,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -348,10 +349,11 @@ func nodeNeed(f host.Facts) Need {
|
||||
}
|
||||
n.steps = []step{
|
||||
{"fetching node " + nodeVersion, func(ctx context.Context, log io.Writer) error {
|
||||
tmp := filepath.Join(os.TempDir(), "inbuxa-node.tar.xz")
|
||||
if err := fetchVerified(ctx, log, url, sum, tmp, 0o644); err != nil {
|
||||
tmp, cleanup, err := fetchToTemp(ctx, log, url, sum, "inbuxa-node.tar.xz")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
// A different version unpacked over the old one would leave
|
||||
// the old one's files behind it.
|
||||
if err := os.RemoveAll("/opt/inbuxa/node"); err != nil {
|
||||
@@ -482,8 +484,13 @@ func fetchVerified(ctx context.Context, log io.Writer, url, want, dest string, m
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
// A new file, never one already at the name: what a failed run left is
|
||||
// removed first, and a link there is removed, not written through.
|
||||
tmp := dest + ".part"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
|
||||
if err := os.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -569,3 +576,21 @@ func describeOS(o host.OSInfo) string {
|
||||
}
|
||||
return "this distribution"
|
||||
}
|
||||
|
||||
// fetchToTemp downloads url, checked against sum, to a temporary file named
|
||||
// name, and returns its path and what removes it. The file is in a new
|
||||
// directory only root can reach, so nobody else can put it there first or
|
||||
// change it between the checksum and its use.
|
||||
func fetchToTemp(ctx context.Context, log io.Writer, url, sum, name string) (string, func(), error) {
|
||||
dir, err := os.MkdirTemp("", "inbuxa-fetch-")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
cleanup := func() { os.RemoveAll(dir) }
|
||||
tmp := filepath.Join(dir, name)
|
||||
if err := fetchVerified(ctx, log, url, sum, tmp, 0o644); err != nil {
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp, cleanup, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package deps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func serve(t *testing.T, body string) (url, sum string) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
io.WriteString(w, body)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
h := sha256.Sum256([]byte(body))
|
||||
return srv.URL, hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func plantedVictim(t *testing.T) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(t.TempDir(), "victim")
|
||||
if err := os.WriteFile(p, []byte("root's\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Node is downloaded and then unpacked as root. At a fixed name in the
|
||||
// shared temporary directory, a local user could plant the file, or a link,
|
||||
// before the install, and change what root unpacks after its checksum
|
||||
// passed (INSTALLER-3). It now goes in a directory of its own, removed after.
|
||||
func TestNodeTarballIsNotAtAFixedNameInTmp(t *testing.T) {
|
||||
shared := t.TempDir()
|
||||
t.Setenv("TMPDIR", shared)
|
||||
victim := plantedVictim(t)
|
||||
for _, name := range []string{"inbuxa-node.tar.xz", "inbuxa-node.tar.xz.part"} {
|
||||
if err := os.Symlink(victim, filepath.Join(shared, name)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
url, sum := serve(t, "a node tarball")
|
||||
path, cleanup, err := fetchToTemp(context.Background(), io.Discard, url, sum, "inbuxa-node.tar.xz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(victim); string(b) != "root's\n" {
|
||||
t.Errorf("written through a planted link: %q", b)
|
||||
}
|
||||
if fi, err := os.Lstat(path); err != nil || !fi.Mode().IsRegular() {
|
||||
t.Errorf("%s should be a plain file: %v %v", path, fi, err)
|
||||
}
|
||||
dir := filepath.Dir(path)
|
||||
if dir == shared {
|
||||
t.Errorf("%s is straight in the shared temporary directory", path)
|
||||
} else if fi, err := os.Lstat(dir); err != nil || fi.Mode().Perm() != 0o700 {
|
||||
t.Errorf("%s should be a directory only its owner can reach: %v %v", dir, fi, err)
|
||||
}
|
||||
cleanup()
|
||||
if _, err := os.Lstat(path); err == nil {
|
||||
t.Errorf("%s is left behind", path)
|
||||
}
|
||||
}
|
||||
|
||||
// A download is written to a new file, never through whatever is at its
|
||||
// .part name already.
|
||||
func TestFetchVerifiedDoesNotWriteThroughAPartLink(t *testing.T) {
|
||||
dest := filepath.Join(t.TempDir(), "file")
|
||||
victim := plantedVictim(t)
|
||||
if err := os.Symlink(victim, dest+".part"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
url, sum := serve(t, "the download")
|
||||
if err := fetchVerified(context.Background(), io.Discard, url, sum, dest, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(victim); string(b) != "root's\n" {
|
||||
t.Errorf("written through a planted link: %q", b)
|
||||
}
|
||||
if fi, err := os.Lstat(dest); err != nil || !fi.Mode().IsRegular() {
|
||||
t.Errorf("%s should be a plain file: %v %v", dest, fi, err)
|
||||
}
|
||||
}
|
||||
+53
-14
@@ -477,6 +477,34 @@ func surveyPort(n int, for_ string) Port {
|
||||
// /proc, which means it only sees the whole truth as root; a guess is better
|
||||
// than nothing and the caller treats it as one.
|
||||
func holderOf(port int) string {
|
||||
inodes := listenInodes(port)
|
||||
if len(inodes) == 0 {
|
||||
return ""
|
||||
}
|
||||
procs, err := filepath.Glob("/proc/[0-9]*/fd/*")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, fd := range procs {
|
||||
link, err := os.Readlink(fd)
|
||||
if err != nil || !strings.HasPrefix(link, "socket:[") {
|
||||
continue
|
||||
}
|
||||
inode := strings.TrimSuffix(strings.TrimPrefix(link, "socket:["), "]")
|
||||
if !inodes[inode] {
|
||||
continue
|
||||
}
|
||||
pid := strings.Split(fd, "/")[2]
|
||||
if comm, err := os.ReadFile("/proc/" + pid + "/comm"); err == nil {
|
||||
return strings.TrimSpace(string(comm)) + " (pid " + pid + ")"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// listenInodes are the socket inodes listening on a TCP port, on any
|
||||
// address, IPv4 or IPv6.
|
||||
func listenInodes(port int) map[string]bool {
|
||||
inodes := map[string]bool{}
|
||||
for _, tab := range []string{"/proc/net/tcp", "/proc/net/tcp6"} {
|
||||
file, err := os.Open(tab)
|
||||
@@ -505,28 +533,35 @@ func holderOf(port int) string {
|
||||
}
|
||||
file.Close()
|
||||
}
|
||||
return inodes
|
||||
}
|
||||
|
||||
// portHeldBy is nil when every socket listening on port is the process
|
||||
// pid's own, and says why not otherwise.
|
||||
func portHeldBy(port, pid int) error {
|
||||
inodes := listenInodes(port)
|
||||
if len(inodes) == 0 {
|
||||
return ""
|
||||
return fmt.Errorf("nothing listens on port %d yet", port)
|
||||
}
|
||||
procs, err := filepath.Glob("/proc/[0-9]*/fd/*")
|
||||
fds, err := os.ReadDir(fmt.Sprintf("/proc/%d/fd", pid))
|
||||
if err != nil {
|
||||
return ""
|
||||
return fmt.Errorf("the sockets of pid %d: %w", pid, err)
|
||||
}
|
||||
for _, fd := range procs {
|
||||
link, err := os.Readlink(fd)
|
||||
for _, fd := range fds {
|
||||
link, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/%s", pid, fd.Name()))
|
||||
if err != nil || !strings.HasPrefix(link, "socket:[") {
|
||||
continue
|
||||
}
|
||||
inode := strings.TrimSuffix(strings.TrimPrefix(link, "socket:["), "]")
|
||||
if !inodes[inode] {
|
||||
continue
|
||||
}
|
||||
pid := strings.Split(fd, "/")[2]
|
||||
if comm, err := os.ReadFile("/proc/" + pid + "/comm"); err == nil {
|
||||
return strings.TrimSpace(string(comm)) + " (pid " + pid + ")"
|
||||
}
|
||||
delete(inodes, strings.TrimSuffix(strings.TrimPrefix(link, "socket:["), "]"))
|
||||
}
|
||||
return ""
|
||||
if len(inodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
who := holderOf(port)
|
||||
if who == "" {
|
||||
who = "another process"
|
||||
}
|
||||
return fmt.Errorf("port %d is held by %s, not pid %d", port, who, pid)
|
||||
}
|
||||
|
||||
func memoryMB() int {
|
||||
@@ -596,3 +631,7 @@ func (f Facts) Port(n int) (Port, bool) {
|
||||
}
|
||||
return Port{}, false
|
||||
}
|
||||
|
||||
// PortHeldBy is nil when everything listening on a TCP port is process
|
||||
// pid's, and says what else is there otherwise.
|
||||
func PortHeldBy(port, pid int) error { return portHeldBy(port, pid) }
|
||||
@@ -36,6 +36,9 @@ type Client struct {
|
||||
// /jmap (contract C-23), so a configured server takes an API key only.
|
||||
Token string
|
||||
HTTP *http.Client
|
||||
// Guard, when set, is asked before every request: an error from it
|
||||
// stops the request before any credential is sent.
|
||||
Guard func(context.Context) error
|
||||
}
|
||||
|
||||
// Call is one method call in a request.
|
||||
@@ -77,6 +80,13 @@ func (e *HTTPError) Error() string {
|
||||
return fmt.Sprintf("HTTP %d: %s", e.Status, strings.TrimSpace(e.Body))
|
||||
}
|
||||
|
||||
func (c *Client) guard(ctx context.Context) error {
|
||||
if c.Guard == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Guard(ctx)
|
||||
}
|
||||
|
||||
func (c *Client) httpClient() *http.Client {
|
||||
if c.HTTP != nil {
|
||||
return c.HTTP
|
||||
@@ -105,6 +115,9 @@ func (c *Client) do(ctx context.Context, using []string, calls ...Call) ([]Respo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.guard(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
} else {
|
||||
|
||||
@@ -39,6 +39,9 @@ func (c *Client) AccountID(ctx context.Context) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := c.guard(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
} else {
|
||||
|
||||
@@ -17,6 +17,24 @@ const ServerVersion = "2026.11.11"
|
||||
// ServerImage is that release as a container image.
|
||||
const ServerImage = "registry.coffeylabs.org/inbuxa/inbuxa-server:" + ServerVersion
|
||||
|
||||
// Caddy, the proxy in front of the console and the webmail, which holds
|
||||
// their TLS keys, from Docker Hub. It is pinned by the digest of its image
|
||||
// index, as the binaries are by their checksums: a tag there moves, and even
|
||||
// a full version's tag is pushed again when its image is rebuilt (for a new
|
||||
// Alpine, say). CaddyVersion is the tag the digest was read from, X.Y.Z of
|
||||
// caddy:X.Y.Z-alpine. This line has no pin-check: the pin is moved by hand,
|
||||
// like the versions here.
|
||||
// The digest is read with
|
||||
// `docker buildx imagetools inspect docker.io/library/caddy:<version>-alpine`.
|
||||
const (
|
||||
CaddyVersion = "2.11.9"
|
||||
CaddyDigest = "sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0"
|
||||
)
|
||||
|
||||
// CaddyImage is that image, by its digest alone, which every runtime the
|
||||
// installer drives reads the same way.
|
||||
const CaddyImage = "docker.io/library/caddy@" + CaddyDigest
|
||||
|
||||
// ServerSHA256 is the SHA-256 of each architecture's release tarball, copied
|
||||
// from the release's SHA256SUMS when the version was moved and checked here
|
||||
// rather than fetched beside the download: a checksum that arrives with the
|
||||
|
||||
Reference in new issue
Block a user