Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,387 @@
|
||||
package main
|
||||
|
||||
// adpanel:export-toctou regression tests.
|
||||
//
|
||||
// handleExportServer used to Lstat every entry through filepath.Walk and then
|
||||
// os.Open(p) the same NAME: a symlink planted between the walk and the open
|
||||
// (plugins/mods are arbitrary code on the bind-mounted server dir, the race is
|
||||
// retryable per file) was followed by the root daemon and its target streamed
|
||||
// into the requester's tar. Both export walks (server dir and
|
||||
// .adpanel_backups) now pin their root once with safeOpenRoot and open every
|
||||
// regular file RELATIVE to that fd via safeOpenRegularAt
|
||||
// (openat2(RESOLVE_BENEATH) + O_NOFOLLOW leaf + regular-file gate), the same
|
||||
// containment copyDir and handleFSDownload enforce; tar headers for regular
|
||||
// files come from the opened fd's Stat. Planted symlinks must never leak their
|
||||
// targets. A regular source entry that cannot be read aborts the export, and
|
||||
// a readable tree must export byte-identically to the old walks.
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type exportTarEntry struct {
|
||||
name string
|
||||
typeflag byte
|
||||
body []byte
|
||||
}
|
||||
|
||||
// readExportTar parses the whole response body as a tar stream; a misaligned
|
||||
// stream (e.g. a header written for a body that was never copied) fails here.
|
||||
func readExportTar(t *testing.T, rr *httptest.ResponseRecorder) []exportTarEntry {
|
||||
t.Helper()
|
||||
tr := tar.NewReader(bytes.NewReader(rr.Body.Bytes()))
|
||||
var entries []exportTarEntry
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
return entries
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("parse export tar: %v", err)
|
||||
}
|
||||
var body []byte
|
||||
if hdr.Size > 0 {
|
||||
body, err = io.ReadAll(tr)
|
||||
if err != nil {
|
||||
t.Fatalf("read body of %s: %v", hdr.Name, err)
|
||||
}
|
||||
}
|
||||
entries = append(entries, exportTarEntry{name: hdr.Name, typeflag: hdr.Typeflag, body: body})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportServerRejectsReservedArchivePaths(t *testing.T) {
|
||||
for _, reserved := range []string{".adpanel_backups", ".adpanel_meta"} {
|
||||
t.Run(reserved, func(t *testing.T) {
|
||||
agent, _ := newTestAgent(t)
|
||||
const name = "fixture"
|
||||
serverDir := agent.serverDir(name)
|
||||
if err := os.MkdirAll(filepath.Join(serverDir, reserved), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(serverDir, reserved, "settings.json"), []byte("fixture"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/v1/servers/fixture/export", nil)
|
||||
agent.handleExportServer(response, request, name)
|
||||
if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), reserved) {
|
||||
t.Fatalf("got status %d: %s; want 409 naming %q", response.Code, response.Body.String(), reserved)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// runExportPlantedSymlinkCase builds a server dir (plus .adpanel_backups and
|
||||
// meta) containing regular files AND symlinks pointing outside the tree, then
|
||||
// runs handleExportServer. It returns the parsed tar entries.
|
||||
func runExportPlantedSymlinkCase(t *testing.T) []exportTarEntry {
|
||||
t.Helper()
|
||||
a, vol := newTestAgent(t)
|
||||
const name = "alpha"
|
||||
serverDir := a.serverDir(name)
|
||||
if err := os.MkdirAll(filepath.Join(serverDir, "plugins"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(serverDir, "server.properties"), []byte("level-name=world\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(serverDir, "plugins", "Potato.jar"), []byte("jar-bytes"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Outside secrets a planted symlink would love to leak.
|
||||
outside := t.TempDir()
|
||||
secret := filepath.Join(outside, "shadow")
|
||||
if err := os.WriteFile(secret, []byte("top-secret-host-bytes"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsideDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(outsideDir, "inner.txt"), []byte("top-secret-host-bytes"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Leaf symlinks (one per walk) and a symlinked DIRECTORY entry: the walk
|
||||
// must skip every one of them and never follow them at open time.
|
||||
if err := os.Symlink(secret, filepath.Join(serverDir, "leak")); err != nil {
|
||||
t.Skipf("symlinks unsupported: %v", err)
|
||||
}
|
||||
if err := os.Symlink(outsideDir, filepath.Join(serverDir, "leakdir")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(secret, filepath.Join(serverDir, "plugins", "leak.jar")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A planted FIFO must not wedge the walk inside open(2).
|
||||
mkfifoInRoot(t, filepath.Join(serverDir, "pipe"))
|
||||
|
||||
// Second walk: .adpanel_backups with a regular artifact and a leaf symlink.
|
||||
backups := a.serverBackupsDir(name)
|
||||
if err := os.MkdirAll(backups, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(backups, "backup-1.tar.gz"), []byte("backup-bytes"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(secret, filepath.Join(backups, "leak")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Meta tail (exported by name, unchanged by the fix).
|
||||
if err := os.MkdirAll(a.metaDir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(a.metaPath(name), []byte(`{"type":"custom"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_ = vol
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/servers/"+name+"/export", nil)
|
||||
rr := rrSettleWithin(t, "handleExportServer over planted FIFO", func() *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
a.handleExportServer(rec, req, name)
|
||||
return rec
|
||||
})
|
||||
if rr.Code != 200 {
|
||||
t.Fatalf("export status: got %d body=%q", rr.Code, rr.Body.String())
|
||||
}
|
||||
return readExportTar(t, rr)
|
||||
}
|
||||
|
||||
// The deterministic regression: regular files (and only they) are exported
|
||||
// with their exact bytes; every planted symlink is absent; no outside bytes
|
||||
// appear anywhere in the stream; the tar stays well-formed.
|
||||
func TestExportServer_SkipsPlantedSymlinks(t *testing.T) {
|
||||
entries := runExportPlantedSymlinkCase(t)
|
||||
|
||||
got := make(map[string]exportTarEntry, len(entries))
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
names = append(names, e.name)
|
||||
got[e.name] = e
|
||||
}
|
||||
// Exact entry set and order: FIFO header-only entry, dir entry with the
|
||||
// trailing slash, regular files, the ".adpanel_backups/" prefix and the
|
||||
// meta tail - the symlink-free skeleton the old walks produced.
|
||||
want := []string{
|
||||
"pipe",
|
||||
"plugins/",
|
||||
"plugins/Potato.jar",
|
||||
"server.properties",
|
||||
".adpanel_backups/backup-1.tar.gz",
|
||||
".adpanel_meta/alpha.json",
|
||||
}
|
||||
if strings.Join(names, "|") != strings.Join(want, "|") {
|
||||
t.Fatalf("tar entries mismatch:\n got %v\nwant %v", names, want)
|
||||
}
|
||||
if got["pipe"].typeflag != tar.TypeFifo {
|
||||
t.Fatalf("FIFO entry typeflag: got %q, want fifo", got["pipe"].typeflag)
|
||||
}
|
||||
if got["plugins/"].typeflag != tar.TypeDir {
|
||||
t.Fatalf("dir entry typeflag: got %q, want dir", got["plugins/"].typeflag)
|
||||
}
|
||||
for name, wantBody := range map[string]string{
|
||||
"plugins/Potato.jar": "jar-bytes",
|
||||
"server.properties": "level-name=world\n",
|
||||
".adpanel_backups/backup-1.tar.gz": "backup-bytes",
|
||||
".adpanel_meta/alpha.json": `{"type":"custom"}`,
|
||||
} {
|
||||
if string(got[name].body) != wantBody {
|
||||
t.Fatalf("content of %s: got %q, want %q", name, string(got[name].body), wantBody)
|
||||
}
|
||||
if got[name].typeflag != tar.TypeReg {
|
||||
t.Fatalf("typeflag of %s: got %q, want regular", name, got[name].typeflag)
|
||||
}
|
||||
}
|
||||
// No planted symlink may surface as an entry, under any shape.
|
||||
for _, bad := range []string{"leak", "leakdir/", "leakdir/inner.txt", "plugins/leak.jar", ".adpanel_backups/leak"} {
|
||||
if _, ok := got[bad]; ok {
|
||||
t.Fatalf("planted symlink %q must not be exported", bad)
|
||||
}
|
||||
}
|
||||
// And no outside bytes may leak through any entry (e.g. a followed
|
||||
// symlink masquerading under a legitimate name).
|
||||
for _, e := range entries {
|
||||
if strings.Contains(string(e.body), "top-secret-host-bytes") {
|
||||
t.Fatalf("outside content leaked through tar entry %q", e.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The legacy validate-then-open fallback (kernels without openat2) must skip
|
||||
// the planted symlinks just the same - never worse than the pinned path.
|
||||
func TestExportServer_SkipsPlantedSymlinks_ForcedFallback(t *testing.T) {
|
||||
safePathForceFallback.Store(true)
|
||||
defer safePathForceFallback.Store(false)
|
||||
entries := runExportPlantedSymlinkCase(t)
|
||||
for _, e := range entries {
|
||||
if strings.Contains(string(e.body), "top-secret-host-bytes") {
|
||||
t.Fatalf("outside content leaked through tar entry %q on the fallback path", e.name)
|
||||
}
|
||||
if e.name == "leak" || e.name == "plugins/leak.jar" || e.name == ".adpanel_backups/leak" || strings.HasPrefix(e.name, "leakdir/") {
|
||||
t.Fatalf("planted symlink %q must not be exported on the fallback path", e.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type exportMutationWriter struct {
|
||||
http.ResponseWriter
|
||||
beforeFirstWrite func()
|
||||
}
|
||||
|
||||
func (w *exportMutationWriter) Write(body []byte) (int, error) {
|
||||
if w.beforeFirstWrite != nil {
|
||||
mutate := w.beforeFirstWrite
|
||||
w.beforeFirstWrite = nil
|
||||
mutate()
|
||||
}
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
func TestExportServer_AbortsIfARegularFileDisappearsDuringExport(t *testing.T) {
|
||||
a, _ := newTestAgent(t)
|
||||
const name = "alpha"
|
||||
serverDir := a.serverDir(name)
|
||||
if err := os.MkdirAll(serverDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range []string{"first", "later"} {
|
||||
if err := os.WriteFile(filepath.Join(serverDir, file), []byte("test payload"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writer := &exportMutationWriter{ResponseWriter: httptest.NewRecorder(), beforeFirstWrite: func() {
|
||||
if err := os.Remove(filepath.Join(serverDir, "later")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}}
|
||||
defer func() {
|
||||
if aborted := recover(); aborted != http.ErrAbortHandler {
|
||||
t.Fatalf("incomplete export must abort the HTTP stream, got %v", aborted)
|
||||
}
|
||||
}()
|
||||
a.handleExportServer(writer, httptest.NewRequest(http.MethodGet, "/v1/servers/alpha/export", nil), name)
|
||||
}
|
||||
|
||||
// TestExportServer_ExportWalksOpenThroughPinnedRoots pins the wiring itself:
|
||||
// the behavioral tests above would still pass if the two walks were reverted
|
||||
// to os.Open(p) on an unlucky (non-raced) run, and both suites stay green if
|
||||
// the tar bodies are reverted from io.CopyN to an unbounded io.Copy. Like
|
||||
// TestHandleApplyVersionKeepsQuotaGuardedDownloader, this reads the source
|
||||
// windows and fails on the revert.
|
||||
func TestExportServer_ExportWalksOpenThroughPinnedRoots(t *testing.T) {
|
||||
src, err := os.ReadFile("main.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read main.go: %v", err)
|
||||
}
|
||||
s := string(src)
|
||||
exportSource, err := os.ReadFile("server-export.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read server-export.go: %v", err)
|
||||
}
|
||||
window := string(exportSource)
|
||||
if strings.Count(window, "func (a *Agent) handleExportServer(") != 1 || strings.Contains(s, "func (a *Agent) handleExportServer(") {
|
||||
t.Fatal("server-export.go must own the single export implementation")
|
||||
}
|
||||
if !strings.Contains(window, "a.tryLockServerOp(name)") || !strings.Contains(window, "defer opMu.Unlock()") {
|
||||
t.Fatal("export must retain its fail-fast operation lock for the complete snapshot")
|
||||
}
|
||||
|
||||
// Both roots pinned once (server dir + .adpanel_backups).
|
||||
if got := strings.Count(window, "safeOpenRoot(serverDir)"); got != 1 {
|
||||
t.Fatalf("server-dir walk must pin its root once via safeOpenRoot(serverDir), found %d", got)
|
||||
}
|
||||
if got := strings.Count(window, "safeOpenRoot(backupsDir)"); got != 1 {
|
||||
t.Fatalf("backups walk must pin its root once via safeOpenRoot(backupsDir), found %d", got)
|
||||
}
|
||||
// Every regular-file content open resolves RELATIVE to the pinned root
|
||||
// with the O_NOFOLLOW leaf - exactly the call shape copyDir/handleFSDownload
|
||||
// use; neither walk may re-open the walked absolute name.
|
||||
if got := strings.Count(window, "safeOpenRegularAt(serverRoot, rel, os.O_RDONLY|openNoFollow, 0)"); got != 1 {
|
||||
t.Fatalf("server-dir walk must open content via safeOpenRegularAt relative to the pinned root, found %d", got)
|
||||
}
|
||||
if got := strings.Count(window, "safeOpenRegularAt(backupsRoot, rel, os.O_RDONLY|openNoFollow, 0)"); got != 1 {
|
||||
t.Fatalf("backups walk must open content via safeOpenRegularAt relative to the pinned root, found %d", got)
|
||||
}
|
||||
if strings.Contains(window, "os.Open(p)") {
|
||||
t.Fatal("handleExportServer must not os.Open(p) the walked name - a revert re-opens the walk-then-open-by-name TOCTOU (arbitrary host-file read as root)")
|
||||
}
|
||||
// Regular-file tar headers come from the OPENED fd's Stat (one per walk).
|
||||
if got := strings.Count(window, "tar.FileInfoHeader(fStat, \"\")"); got != 2 {
|
||||
t.Fatalf("both walks must build regular-file headers from the opened fd's Stat, found %d", got)
|
||||
}
|
||||
// The constraint comment must document both walk sites.
|
||||
if got := strings.Count(window, "adpanel:export-toctou"); got < 2 {
|
||||
t.Fatalf("both export walk sites must carry the adpanel:export-toctou constraint comment, found %d", got)
|
||||
}
|
||||
|
||||
// adpanel:tar-body-size-race - the export walks copy exactly the OPENED
|
||||
// fd's stat size, and the meta tail uses its own stat size. Reverting
|
||||
// any body write to io.Copy re-opens
|
||||
// the walk-to-open size race: a file grown after its header was written
|
||||
// from the walked stat would stream past the header's size contract and
|
||||
// desynchronize the archive stream (and the export flow's
|
||||
// early-response/byte-accounting around it).
|
||||
if got := strings.Count(window, "io.CopyN(tw, f, fStat.Size())"); got != 2 {
|
||||
t.Fatalf("both export walks must CopyN-bound each body to the opened fd's stat size (2 sites), found %d", got)
|
||||
}
|
||||
if got := strings.Count(window, "io.CopyN(tw, f, metaInfo.Size())"); got != 1 {
|
||||
t.Fatalf("the export meta tail must CopyN-bound its body to the stat'd header size, found %d", got)
|
||||
}
|
||||
if strings.Contains(window, "io.Copy(tw, f)") {
|
||||
t.Fatal("handleExportServer must not keep an unbounded io.Copy(tw, f) tar body - every body copies CopyN-bounded to its header size (adpanel:tar-body-size-race)")
|
||||
}
|
||||
|
||||
// Both archive source paths must delegate to the same bounded writer.
|
||||
archiveWindow := sourceWindow(t, s, "func (a *Agent) handleFilesArchive(")
|
||||
if strings.Count(archiveWindow, "writeArchiveSources(tw, rootHandle, root, body.Paths, skipArchiveOutput)") != 1 {
|
||||
t.Fatal("the archive handler must delegate source writing through the pinned root")
|
||||
}
|
||||
archiveSource, err := os.ReadFile("fs-archive.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read fs-archive.go: %v", err)
|
||||
}
|
||||
archiveWriter := string(archiveSource)
|
||||
archiveSources := sourceWindow(t, archiveWriter, "func writeArchiveSources(")
|
||||
if strings.Count(archiveSources, "writeArchiveEntry(writer, scope,") != 2 {
|
||||
t.Fatal("selected files and walked directory entries must use the same archive entry writer")
|
||||
}
|
||||
for _, required := range []string{
|
||||
"filepath.Rel(scope.path, source)",
|
||||
"safeOpenRegularAt(scope, relative, os.O_RDONLY|openNoFollow, 0)",
|
||||
"file, info = opened, stat",
|
||||
"tar.FileInfoHeader(info, \"\")",
|
||||
"io.CopyN(writer, file, info.Size())",
|
||||
} {
|
||||
if strings.Count(archiveWriter, required) != 1 {
|
||||
t.Fatalf("archive entry writer must derive its header and bounded body from the pinned file: %s", required)
|
||||
}
|
||||
}
|
||||
if strings.Contains(archiveWriter, "io.Copy(") || strings.Contains(archiveWindow, "io.Copy(tw,") {
|
||||
t.Fatal("archive bodies must never use an unbounded copy")
|
||||
}
|
||||
}
|
||||
|
||||
// sourceWindow bounds a top-level function's source text: from the anchor to
|
||||
// the next "\nfunc " at column zero (the same bounding the pins below apply
|
||||
// when reading main.go).
|
||||
func sourceWindow(t *testing.T, src, anchor string) string {
|
||||
t.Helper()
|
||||
start := strings.Index(src, anchor)
|
||||
if start < 0 {
|
||||
t.Fatalf("anchor not found: %s", anchor)
|
||||
}
|
||||
end := strings.Index(src[start:], "\nfunc ")
|
||||
if end < 0 {
|
||||
t.Fatalf("could not bound the source window for %s", anchor)
|
||||
}
|
||||
return src[start : start+end]
|
||||
}
|
||||
Reference in new issue
Block a user