feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+671
View File
@@ -0,0 +1,671 @@
package isolation
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
var safeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$`)
type Agent struct {
Root string
BackupRoot string
LegacyRoot string
FileOwner string
NodePIDRoot string
NginxVhostRoot, NginxBinary string
PurePWBinary string
PHPStateRoot, PHPRunRoot string
PythonManagerRoot string
PythonBuildRoot string
PythonMetadataBaseURL string
PythonMetadataCacheRoot string
PythonSourceBaseURLs []string
UsageStatePath, NginxLogRoot string
CertificateRoot, PureFTPConfig, PureFTPPem string
runCommand func(context.Context, string, ...string) error
lookupUID func(string) (uint64, error)
InternalToken string
databaseAdminDSN string
FTPLogPath string
}
func (a Agent) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/database/phpmyadmin",a.authorizeInternal(a.phpMyAdmin))
mux.HandleFunc("POST /v1/scheduler/configure",a.authorizeInternal(a.configureSchedulerBridge))
mux.HandleFunc("POST /v1/schedule/execute",a.authorizeInternal(a.executeSchedule))
mux.HandleFunc("POST /v1/ftp/disconnect",a.authorizeInternal(a.disconnectFTP))
mux.HandleFunc("POST /v1/site/startup",a.authorizeInternal(a.configureStartup))
mux.HandleFunc("POST /v1/site/settings",a.authorizeInternal(a.configureWebsite))
mux.HandleFunc("POST /v1/site/log",a.authorizeInternal(a.readSiteLog))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
mux.HandleFunc("POST /v1/prepare", a.authorizeInternal(a.prepare))
mux.HandleFunc("POST /v1/quarantine", a.authorizeInternal(a.quarantine))
mux.HandleFunc("POST /v1/web-protection/apply", a.authorizeInternal(a.applyWebProtection))
mux.HandleFunc("POST /v1/web-protection/remove", a.authorizeInternal(a.removeWebProtection))
mux.HandleFunc("POST /v1/runtime/executable", a.authorizeInternal(a.prepareExecutable))
mux.HandleFunc("POST /v1/runtime/panel-state", a.authorizeInternal(a.preparePanelRuntime))
mux.HandleFunc("POST /v1/runtime/python/install", a.authorizeInternal(a.installPythonRuntime))
mux.HandleFunc("POST /v1/runtime/probe", a.authorizeInternal(a.probeRuntime))
mux.HandleFunc("POST /v1/runtime/php/maintenance", a.authorizeInternal(a.maintainPHP))
mux.HandleFunc("POST /v1/runtime/backups/prune", a.authorizeInternal(a.pruneRuntimeBackups))
mux.HandleFunc("POST /v1/runtime/python/dependencies", a.authorizeInternal(a.copyPythonDependencies))
mux.HandleFunc("POST /v1/run-path/release", a.authorizeInternal(a.releaseRunPath))
mux.HandleFunc("POST /v1/trash/prepare", a.authorizeInternal(a.prepareTrash))
mux.HandleFunc("POST /v1/ftp/identity", a.authorizeInternal(a.configureFTPIdentity))
mux.HandleFunc("POST /v1/credentials/disconnect",a.authorizeInternal(a.disconnectCredentialSessions))
mux.HandleFunc("POST /v1/php/identity", a.authorizeInternal(a.configurePHPIdentity))
mux.HandleFunc("POST /v1/php/identity/start", a.authorizeInternal(a.startPHPIdentity))
mux.HandleFunc("POST /v1/php/identity/stop", a.authorizeInternal(a.stopPHPIdentity))
mux.HandleFunc("POST /v1/php/identity/remove", a.authorizeInternal(a.removePHPIdentity))
mux.HandleFunc("POST /v1/resources/usage", a.authorizeInternal(a.resourceUsage))
mux.HandleFunc("POST /v1/resources/processes/terminate", a.authorizeInternal(a.terminateProcesses))
mux.HandleFunc("POST /v1/resources/runtime/terminate", a.authorizeInternal(a.terminateRuntime))
mux.HandleFunc("POST /v1/project/freeze-writes", a.authorizeInternal(a.freezeWrites))
mux.HandleFunc("POST /v1/ftp/tls", a.authorizeInternal(a.configureFTPTLS))
mux.HandleFunc("POST /v1/nginx/network", a.authorizeInternal(a.configureNginxNetwork))
mux.HandleFunc("POST /v1/database/access", a.authorizeInternal(a.configureDatabaseAccess))
mux.HandleFunc("POST /v1/resources/limits", a.authorizeInternal(a.configureTrafficLimits))
mux.HandleFunc("POST /v1/lifecycle/backup", a.authorizeInternal(a.createProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/backup/delete", a.authorizeInternal(a.deleteProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/backup/verify", a.authorizeInternal(a.verifyProjectBackup))
mux.HandleFunc("POST /v1/lifecycle/project/purge", a.authorizeInternal(a.purgeProject))
mux.HandleFunc("POST /v1/import/project", a.authorizeInternal(a.importLegacyProject))
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){limit:=int64(64<<10);if r.URL.Path=="/v1/database/phpmyadmin"{limit=4<<20};r.Body=http.MaxBytesReader(w,r.Body,limit);mux.ServeHTTP(w,r)})
}
// freezeWrites leaves the unprivileged Sea vHost file service as owner so the
// tenant can delete content and recover below quota, while removing write
// access from the per-host runtime/FTP identity. Existing runtime-created
// files are first reclaimed because their owner may be the host identity.
func (a Agent) freezeWrites(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
if err = requirePhysicalDirectory(projectRoot); err != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
fileOwner := a.FileOwner
if fileOwner == "" {
fileOwner = "sea-vhost"
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
// aaPanel's immutable .user.ini is already root-owned and read-only. Exclude
// it from recursive ownership/ACL operations so the quota transition never
// needs to relax PHP's open_basedir guard.
if err = a.command(ctx, "find", projectRoot, "-xdev", "!", "-name", ".user.ini", "-exec", "chown", "-h", fileOwner+":"+spec.HostName, "{}", "+"); err != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "u+rwx,g+rX,g-w,o-rwx", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "chmod", "u+rw,g+r,g-w,o-rwx", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", "u:www:r-x,m::r-x,d:u:"+fileOwner+":rwx,d:u:www:r-x,d:g::r-x,d:m::r-x,d:o::---", "{}", "+") != nil ||
a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "!", "-name", ".user.ini", "-exec", "setfacl", "-m", "u:www:r--,m::r--,o::---", "{}", "+") != nil {
http.Error(w, "cannot freeze project writes", http.StatusInternalServerError)
return
}
runtimeRoot := filepath.Join(projectRoot, ".sea-runtime")
if err = requirePhysicalDirectory(runtimeRoot); err == nil {
if err = a.command(ctx, "find", runtimeRoot, "-xdev", "-exec", "setfacl", "-m", "u:www:---", "{}", "+"); err != nil {
http.Error(w, "cannot preserve private runtime directory", http.StatusInternalServerError)
return
}
} else if !errors.Is(err, os.ErrNotExist) {
http.Error(w, "unsafe private runtime directory", http.StatusPreconditionFailed)
return
}
if err = a.freezeFTPLogin(ctx, spec.HostName); err != nil {
http.Error(w, "cannot freeze FTP login", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) authorizeInternal(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if a.InternalToken != "" {
supplied := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if len(supplied) != len(a.InternalToken) || subtle.ConstantTimeCompare([]byte(supplied), []byte(a.InternalToken)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
}
next(w, r)
}
}
// releaseRunPath removes only aaPanel's immutable PHP isolation file from an
// exact managed run directory after its site has been deleted. Source files
// are deliberately retained and remain owned by the Sea vHost file service.
func (a Agent) releaseRunPath(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
runDirectory, err := physicalRunDirectory(projectRoot, spec.RunPath)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil {
http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed)
return
}
if err = a.removeUserINI(r.Context(), filepath.Join(runDirectory, ".user.ini")); err != nil {
http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// prepareTrash makes interrupted/deleted-site trash removable by the
// unprivileged API process. It may only unlock and remove regular .user.ini
// files below the fixed .sea-trash directory; it never deletes tenant data.
func (a Agent) prepareTrash(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
trash := filepath.Join(projectRoot, ".sea-trash")
info, err := os.Lstat(trash)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe trash directory", http.StatusPreconditionFailed)
return
}
files, err := findProjectUserINIFiles(trash, 128)
if err != nil {
http.Error(w, "unsafe PHP isolation file in trash", http.StatusPreconditionFailed)
return
}
for _, file := range files {
if err = a.removeUserINI(r.Context(), file); err != nil {
http.Error(w, "cannot release PHP isolation file in trash", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) removeUserINI(parent context.Context, file string) error {
info, err := os.Lstat(file)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("PHP isolation file is not a regular file")
}
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
defer cancel()
if err = a.command(ctx, "chattr", "-i", file); err != nil {
return err
}
return os.Remove(file)
}
func (a Agent) command(ctx context.Context, name string, args ...string) error {
if a.runCommand != nil {
return a.runCommand(ctx, name, args...)
}
return command(ctx, name, args...)
}
func (a Agent) commandAt(ctx context.Context, directory, name string, args ...string) error {
if a.runCommand != nil {
return a.runCommand(ctx, name, args...)
}
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = directory
cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output)))
}
return nil
}
func (a Agent) prepareExecutable(w http.ResponseWriter, r *http.Request) {
var input ExecutableSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) || input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 || !validExecutablePath(input.RelativePath) {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(input.Project)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
defer root.Close()
info, err := root.Lstat(input.RelativePath)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "runtime entry is not a regular file", http.StatusPreconditionFailed)
return
}
if err = root.Chmod(input.RelativePath, 0750); err != nil {
http.Error(w, "cannot mark runtime entry executable", http.StatusInternalServerError)
return
}
if err = a.command(r.Context(), "setfacl", "-m", "u:www:r--,g::r-x,m::r-x,o::---", filepath.Join(projectRoot, filepath.FromSlash(input.RelativePath))); err != nil {
http.Error(w, "cannot apply executable identity ACL", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func validExecutablePath(value string) bool {
if value == "" || len(value) > 255 || strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean("/"+value)) != "/"+value {
return false
}
for _, segment := range strings.Split(value, "/") {
if segment == "" || segment == "." || segment == ".." || len(segment) > 100 {
return false
}
for _, character := range segment {
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
return false
}
}
}
return true
}
func (a Agent) decode(w http.ResponseWriter, r *http.Request) (ProjectSpec, bool) {
var spec ProjectSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if spec.RunPath == "" {
spec.RunPath = "/"
}
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(spec.HostName) || !validProjectRunPath(spec.RunPath) || spec.TenantID == 0 || spec.TenantID > 9_999_999_999 || spec.StorageBytes == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 {
http.Error(w, "invalid request", http.StatusBadRequest)
return ProjectSpec{}, false
}
return spec, true
}
func (a Agent) projectPath(spec ProjectSpec) (string, error) {
base, err := filepath.Abs(a.Root)
if err != nil {
return "", err
}
projectRoot := filepath.Join(base, spec.HostName)
relative, err := filepath.Rel(base, projectRoot)
if err != nil || relative != spec.HostName || strings.Contains(relative, string(os.PathSeparator)) {
return "", errors.New("path outside root")
}
return projectRoot, nil
}
func (a Agent) prepare(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
runtimeUser := spec.HostName
fileOwner := a.FileOwner
if fileOwner == "" {
fileOwner = "sea-vhost"
}
runtimeGroup := runtimeUser
base := filepath.Dir(projectRoot)
if err = ensureDirectory(base, 0755); err != nil {
http.Error(w, "unsafe tenant root", http.StatusPreconditionFailed)
return
}
if err = a.ensureHostIdentity(ctx, spec, projectRoot); err != nil {
http.Error(w, "cannot create isolated project identity", http.StatusInternalServerError)
return
}
// /www/wwwroot is shared with aaPanel and may already contain sites. Never
// change its owner or mode; Sea vHost only mutates its random host directory.
if err = ensureDirectory(projectRoot, 0770); err != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
if err = ensureProjectRunDirectory(projectRoot, spec.RunPath); err != nil {
http.Error(w, "unsafe project run directory", http.StatusPreconditionFailed)
return
}
userINIFiles, err := findProjectUserINIFiles(projectRoot, 64)
if err != nil {
http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed)
return
}
unlockedUserINI := make([]string, 0, len(userINIFiles))
defer func() {
if len(unlockedUserINI) == 0 {
return
}
lockCtx, cancelLock := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelLock()
for _, userINI := range unlockedUserINI {
_ = command(lockCtx, "chattr", "+i", userINI)
}
}()
for _, userINI := range userINIFiles {
if err = command(ctx, "chattr", "-i", userINI); err != nil {
http.Error(w, "cannot unlock PHP isolation file", http.StatusInternalServerError)
return
}
unlockedUserINI = append(unlockedUserINI, userINI)
}
if err = a.command(ctx, "setfacl", "-Rb", projectRoot); err != nil {
http.Error(w, "cannot reset project ACL", http.StatusInternalServerError)
return
}
if err = a.command(ctx, "chown", "-hR", fileOwner+":"+runtimeGroup, projectRoot); err != nil {
http.Error(w, "cannot set project owner", http.StatusInternalServerError)
return
}
if err = a.command(ctx, "chmod", "-R", "u+rwX,g+rwX,o-rwx", projectRoot); err != nil || a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "chmod", "g+s", "{}", "+") != nil {
http.Error(w, "cannot set project permissions", http.StatusInternalServerError)
return
}
if err = a.applyProjectACL(ctx, projectRoot, fileOwner); err != nil {
http.Error(w, "cannot apply isolated project ACL", http.StatusInternalServerError)
return
}
for _, userINI := range userINIFiles {
if err = a.command(ctx, "chown", "root:root", userINI); err != nil || a.command(ctx, "chmod", "0644", userINI) != nil || a.command(ctx, "chattr", "+i", userINI) != nil {
http.Error(w, "cannot secure PHP isolation file", http.StatusInternalServerError)
return
}
}
unlockedUserINI = nil
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(Prepared{RootPath: filepath.ToSlash(projectRoot), RunUser: runtimeUser})
}
func (a Agent) ensureHostIdentity(ctx context.Context, spec ProjectSpec, projectRoot string) error {
name := spec.HostName
if err := a.command(ctx, "getent", "group", name); err != nil {
if err = a.command(ctx, "groupadd", "--system", name); err != nil {
return err
}
}
// The OS identity is only a process/ownership boundary. It deliberately has
// no usable home directory; FTP keeps its independent Pure-FTPd chroot at
// projectRoot and does not rely on the passwd home field.
const disabledHome = "/nonexistent"
if err := a.command(ctx, "id", "-u", name); err != nil {
// aaPanel's built-in Python project model intentionally ignores system
// accounts below UID_MIN. Allocate from the normal UID range while still
// disabling login, passwords and home-directory creation. This preserves
// process isolation without depending on a panel-version-specific user
// whitelist.
if err = a.command(ctx, "useradd", "--gid", name, "--home-dir", disabledHome, "--no-create-home", "--shell", "/usr/sbin/nologin", name); err != nil {
return err
}
}
if err := a.command(ctx, "usermod", "--gid", name, "--groups", name, "--home", disabledHome, "--shell", "/usr/sbin/nologin", name); err != nil {
return err
}
return a.command(ctx, "passwd", "--lock", name)
}
func (a Agent) applyProjectACL(ctx context.Context, projectRoot, fileOwner string) error {
directoryACL := "u:www:r-x,m::rwx,d:u:" + fileOwner + ":rwx,d:u:www:r-x,d:g::rwx,d:m::rwx,d:o::---"
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", directoryACL, "{}", "+"); err != nil {
return err
}
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-exec", "setfacl", "-m", "u:www:r--,m::rw-,o::---", "{}", "+"); err != nil {
return err
}
// A directory repair must not revoke execution from existing Go binaries,
// venv tools or tenant scripts. www remains read-only even on these files.
if err := a.command(ctx, "find", projectRoot, "-xdev", "-type", "f", "-perm", "/111", "-exec", "setfacl", "-m", "u:www:r--,m::rwx,o::---", "{}", "+"); err != nil {
return err
}
// Every website can use its own run directory. Preserve private runtime
// trees at all depths, and never follow venv executable symlinks while
// applying ACLs (those may point to shared server-owned interpreters).
return filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() && entry.Name() == ".sea-runtime" {
if err := a.securePythonRuntimeACL(ctx, current); err != nil {
return err
}
return filepath.SkipDir
}
return nil
})
}
func findProjectUserINIFiles(projectRoot string, limit int) ([]string, error) {
files := make([]string, 0, 2)
err := filepath.WalkDir(projectRoot, func(current string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.Type()&os.ModeSymlink != 0 {
if entry.Name() == ".user.ini" {
return errors.New("PHP isolation file is a symlink")
}
return nil
}
if entry.Name() != ".user.ini" {
return nil
}
info, err := entry.Info()
if err != nil || !info.Mode().IsRegular() {
return errors.New("PHP isolation file is not regular")
}
files = append(files, current)
if len(files) > limit {
return errors.New("too many PHP isolation files")
}
return nil
})
return files, err
}
func (a Agent) quarantine(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
source := projectRoot
info, statErr := os.Lstat(source)
if statErr != nil && os.IsNotExist(statErr) {
w.WriteHeader(http.StatusOK)
return
}
if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
trash := filepath.Join(a.Root, ".sea-vhost-quarantine")
if err = ensureDirectory(trash, 0700); err != nil || a.command(ctx, "chown", "root:root", trash) != nil || a.command(ctx, "chmod", "0700", trash) != nil {
http.Error(w, "cannot create quarantine", http.StatusInternalServerError)
return
}
target := filepath.Join(trash, fmt.Sprintf("%s-%d", spec.HostName, time.Now().Unix()))
if err = os.Rename(source, target); err != nil {
http.Error(w, "cannot quarantine", http.StatusInternalServerError)
return
}
// Named ACL entries are stored by numeric UID. Remove any Node.js PID
// access before deleting the account so a future UID reuse cannot inherit
// access to another host's process state. Restore the project directory if
// revocation fails so deletion remains safely retryable.
if err = a.revokeNodePIDAccess(ctx, spec.HostName); err != nil {
_ = os.Rename(target, source)
http.Error(w, "cannot revoke isolated Node.js PID access", http.StatusInternalServerError)
return
}
if a.command(ctx, "id", "-u", spec.HostName) == nil {
if err = a.command(ctx, "userdel", spec.HostName); err != nil {
http.Error(w, "cannot remove isolated project identity", http.StatusInternalServerError)
return
}
}
if a.command(ctx, "getent", "group", spec.HostName) == nil {
if err = a.command(ctx, "groupdel", spec.HostName); err != nil {
http.Error(w, "cannot remove isolated project group", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}
func command(ctx context.Context, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(output)))
}
return nil
}
func ensureDirectory(path string, mode os.FileMode) error {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
if err = os.Mkdir(path, mode); err != nil {
return err
}
info, err = os.Lstat(path)
}
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("path is not a physical directory")
}
return nil
}
func ensureProjectRunDirectory(projectRoot, runPath string) error {
if !validProjectRunPath(runPath) {
return errors.New("invalid run path")
}
if runPath == "/" {
return nil
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
return err
}
defer root.Close()
current := ""
for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") {
if current == "" {
current = segment
} else {
current += "/" + segment
}
info, statErr := root.Lstat(current)
if errors.Is(statErr, os.ErrNotExist) {
if err = root.Mkdir(current, 0770); err != nil {
return err
}
info, statErr = root.Lstat(current)
}
if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("run path is not a physical directory")
}
}
return nil
}
func physicalRunDirectory(projectRoot, runPath string) (string, error) {
if !validProjectRunPath(runPath) {
return "", errors.New("invalid run path")
}
root, err := os.OpenRoot(projectRoot)
if err != nil {
return "", err
}
defer root.Close()
if runPath == "/" {
return projectRoot, nil
}
current := ""
for _, segment := range strings.Split(strings.TrimPrefix(runPath, "/"), "/") {
if current == "" {
current = segment
} else {
current += "/" + segment
}
info, statErr := root.Lstat(current)
if statErr != nil {
return "", statErr
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("run path is not a physical directory")
}
}
return filepath.Join(projectRoot, filepath.FromSlash(strings.TrimPrefix(runPath, "/"))), nil
}
func validProjectRunPath(value string) bool {
if value == "/" {
return true
}
if len(value) < 2 || len(value) > 255 || !strings.HasPrefix(value, "/") || strings.Contains(value, "\\") || filepath.ToSlash(filepath.Clean(value)) != value {
return false
}
for _, segment := range strings.Split(strings.TrimPrefix(value, "/"), "/") {
if segment == "" || segment == "." || segment == ".." || len(segment) > 80 {
return false
}
for _, character := range segment {
if !(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') && !(character >= '0' && character <= '9') && !strings.ContainsRune("._-", character) {
return false
}
}
}
return true
}
+657
View File
@@ -0,0 +1,657 @@
package isolation
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func lifecycleRequest(t *testing.T, agent Agent, route string, value any) *httptest.ResponseRecorder {
t.Helper()
body, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
return response
}
func TestLifecycleBackupArchivesOnlyManagedProject(t *testing.T) {
root, backupRoot := t.TempDir(), t.TempDir()
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(filepath.Join(projectRoot, "public"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(projectRoot, "public", "marker.txt"), []byte("tenant-marker"), 0600); err != nil {
t.Fatal(err)
}
response := lifecycleRequest(t, Agent{Root: root, BackupRoot: backupRoot}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1})
if response.Code != http.StatusOK {
t.Fatalf("backup status=%d body=%s", response.Code, response.Body.String())
}
var backup ProjectBackup
if err := json.Unmarshal(response.Body.Bytes(), &backup); err != nil {
t.Fatal(err)
}
file, err := os.Open(backup.ArchivePath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
gzipReader, err := gzip.NewReader(file)
if err != nil {
t.Fatal(err)
}
tarReader := tar.NewReader(gzipReader)
found := false
for {
header, nextErr := tarReader.Next()
if errors.Is(nextErr, io.EOF) {
break
}
if nextErr != nil {
t.Fatal(nextErr)
}
if header.Name == hostName+"/public/marker.txt" {
found = true
}
if strings.Contains(header.Name, "..") || strings.HasPrefix(header.Name, "/") {
t.Fatalf("unsafe archive path %q", header.Name)
}
}
if !found {
t.Fatal("managed marker was not archived")
}
}
func TestLifecyclePurgeIsIdempotentAndRemovesIdentity(t *testing.T) {
root := t.TempDir()
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(projectRoot, 0700); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 4)
agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "id" || name == "getent" {
return nil
}
return nil
}}
spec := ProjectSpec{TenantID: 42, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
response := lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec)
if response.Code != http.StatusOK {
t.Fatalf("purge status=%d body=%s", response.Code, response.Body.String())
}
if _, err := os.Stat(projectRoot); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("project directory still exists: %v", err)
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "userdel "+hostName) || !strings.Contains(joined, "groupdel "+hostName) {
t.Fatalf("identity cleanup missing: %s", joined)
}
commands = nil
agent.runCommand = func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return errors.New("missing")
}
response = lifecycleRequest(t, agent, "/v1/lifecycle/project/purge", spec)
if response.Code != http.StatusOK || strings.Contains(strings.Join(commands, "\n"), "userdel") {
t.Fatalf("retry was not idempotent: status=%d commands=%v", response.Code, commands)
}
}
func TestAgentHealthCheck(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
response := httptest.NewRecorder()
Agent{}.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"status":"ok"`) {
t.Fatalf("unexpected health response: %d %s", response.Code, response.Body.String())
}
}
func TestAgentMutationRequiresInternalToken(t *testing.T) {
agent := Agent{InternalToken: strings.Repeat("i", 32)}
request := httptest.NewRequest(http.MethodPost, "/v1/prepare", strings.NewReader(`{}`))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated mutation status = %d, want 401", response.Code)
}
}
func TestHostIdentityHasNoUsableHomeDirectory(t *testing.T) {
commands := make([]string, 0, 2)
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "getent" || name == "id" {
return errors.New("not found")
}
return nil
}}
if err := agent.ensureHostIdentity(context.Background(), ProjectSpec{HostName: "sv0123456789"}, "/www/wwwroot/seavHost/vHost/sv0123456789"); err != nil {
t.Fatal(err)
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "usermod --gid sv0123456789 --groups sv0123456789 --home /nonexistent --shell /usr/sbin/nologin sv0123456789") {
t.Fatalf("identity did not use the disabled home: %s", joined)
}
if strings.Contains(joined, "--home /www/wwwroot") {
t.Fatalf("project root was used as an OS home: %s", joined)
}
if !strings.Contains(joined, "useradd --gid sv0123456789 --home-dir /nonexistent --no-create-home --shell /usr/sbin/nologin sv0123456789") {
t.Fatalf("identity was not allocated from the normal UID range: %s", joined)
}
if strings.Contains(joined, "useradd --system") {
t.Fatalf("identity used a system UID rejected by aaPanel Python: %s", joined)
}
}
func TestPreparePanelRuntimeGrantsOnlyNodePIDDirectoryAccess(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
pidRoot := filepath.Join(t.TempDir(), "pids")
hostName := "sv0123456789"
if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(pidRoot, 0755); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 2)
agent := Agent{
Root: root, NodePIDRoot: pidRoot,
lookupUID: func(string) (uint64, error) { return 1001, nil },
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
},
}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Node.js"}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "chmod +t "+pidRoot) || !strings.Contains(joined, "setfacl -m u:"+hostName+":rwx,m::rwx "+pidRoot) {
t.Fatalf("unexpected Node.js compatibility commands: %s", joined)
}
if strings.Contains(joined, filepath.Join(root, hostName)+" ") {
t.Fatalf("Node.js compatibility grant escaped the fixed PID directory: %s", joined)
}
}
func TestPreparePanelRuntimeRejectsLegacyPythonUID(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
if err := os.MkdirAll(filepath.Join(root, hostName), 0770); err != nil {
t.Fatal(err)
}
agent := Agent{Root: root, lookupUID: func(string) (uint64, error) { return 999, nil }}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusPreconditionFailed || !strings.Contains(response.Body.String(), "legacy host UID") {
t.Fatalf("legacy Python UID status = %d, body = %s", response.Code, response.Body.String())
}
}
func TestPreparePanelRuntimeCreatesIsolatedPythonVirtualEnvironment(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
managerRoot := filepath.Join(t.TempDir(), "versions")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
basePython := filepath.Join(managerRoot, "3.12.0", "bin", "python3")
if err := os.MkdirAll(projectRoot, 0770); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(basePython), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(basePython, []byte("test"), 0755); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 3)
agent := Agent{
Root: root, FileOwner: "sea-vhost", PythonManagerRoot: managerRoot,
lookupUID: func(string) (uint64, error) { return 1001, nil },
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
if name == "runuser" {
venvPath := args[len(args)-1]
if err := os.MkdirAll(filepath.Join(venvPath, "bin"), 0770); err != nil {
return err
}
return os.WriteFile(filepath.Join(venvPath, "bin", "python3"), []byte("test"), 0755)
}
return nil
},
}
spec := PanelRuntimeSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}, Runtime: "Python", Version: "3.12.0", ProjectName: hostName}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/panel-state", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare status = %d, body = %s", response.Code, response.Body.String())
}
venvPath := filepath.Join(projectRoot, ".sea-runtime", "python", hostName+"-3.12.0")
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "runuser -u "+hostName+" -- "+basePython+" -m venv --system-site-packages "+venvPath) {
t.Fatalf("Python venv command was not confined: %s", joined)
}
if !strings.Contains(joined, "-xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") {
t.Fatalf("Python ACL command did not exclude virtualenv symlinks: %s", joined)
}
}
func TestFreezeWritesReclaimsOwnershipAndRemovesRuntimeWriteAccess(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(projectRoot, 0770); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 5)
agent := Agent{Root: root, FileOwner: "sea-vhost", PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
for _, expected := range []string{
"chown -h sea-vhost:" + hostName,
"chmod u+rwx,g+rX,g-w,o-rwx",
"chmod u+rw,g+r,g-w,o-rwx",
"d:g::r-x,d:m::r-x",
"u:www:r--,m::r--",
} {
if !strings.Contains(joined, expected) {
t.Fatalf("freeze commands missing %q: %s", expected, joined)
}
}
if !strings.Contains(joined, "! -name .user.ini") {
t.Fatalf("freeze commands did not preserve immutable .user.ini: %s", joined)
}
}
func TestFreezeWritesKeepsRuntimeDirectoryPrivate(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
projectRoot := filepath.Join(root, hostName)
if err := os.MkdirAll(filepath.Join(projectRoot, ".sea-runtime"), 0770); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 6)
agent := Agent{Root: root, PurePWBinary: filepath.Join(t.TempDir(), "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/project/freeze-writes", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("freeze status = %d, body = %s", response.Code, response.Body.String())
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, filepath.Join(projectRoot, ".sea-runtime")+" -xdev -exec setfacl -m u:www:---") {
t.Fatalf("freeze did not restore the runtime privacy ACL: %s", joined)
}
}
func TestBandwidthMeterCountsOnlyCompleteCurrentMonthLines(t *testing.T) {
root := t.TempDir()
logPath := filepath.Join(root, "example.test.log")
initial := "127.0.0.1 - - [30/Sep/2026:23:59:59 +0800] \"GET /old HTTP/1.1\" 200 90 \"-\" \"test\"\n" +
"127.0.0.1 - - [18/Oct/2026:10:00:00 +0800] \"GET / HTTP/1.1\" 200 120 \"-\" \"test\"\n"
if err := os.WriteFile(logPath, []byte(initial), 0600); err != nil {
t.Fatal(err)
}
cursor, err := measureDomainLog(logPath, trafficCursor{Month: "2026-10"}, "2026-10")
if err != nil || cursor.Bytes != 120 {
t.Fatalf("cursor=%+v err=%v", cursor, err)
}
completeOffset := cursor.Offset
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
_, _ = file.WriteString("127.0.0.1 - - [18/Oct/2026:10:00:01 +0800] \"GET /next HTTP/1.1\" 200 45")
_ = file.Close()
cursor, err = measureDomainLog(logPath, cursor, "2026-10")
if err != nil || cursor.Bytes != 120 || cursor.Offset != completeOffset {
t.Fatalf("partial cursor=%+v err=%v", cursor, err)
}
file, _ = os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0600)
_, _ = file.WriteString(" \"-\" \"test\"\n")
_ = file.Close()
cursor, err = measureDomainLog(logPath, cursor, "2026-10")
if err != nil || cursor.Bytes != 165 {
t.Fatalf("completed cursor=%+v err=%v", cursor, err)
}
}
func TestMeasureProjectStorageCountsManagedTreeWithoutFollowingSymlinks(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "private", "nested"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "index.html"), []byte("12345"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "private", "nested", "data.bin"), []byte("1234567"), 0600); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "outside.bin")
if err := os.WriteFile(outside, make([]byte, 1024*1024), 0600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "outside-link")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
usage, err := measureProjectStorage(root)
if err != nil {
t.Fatal(err)
}
linkInfo, err := os.Lstat(link)
if err != nil {
t.Fatal(err)
}
want := uint64(12 + linkInfo.Size())
if usage != want {
t.Fatalf("usage = %d, want %d", usage, want)
}
}
func TestMeasureProjectStorageRejectsSymlinkRoot(t *testing.T) {
realRoot := t.TempDir()
link := filepath.Join(t.TempDir(), "host-link")
if err := os.Symlink(realRoot, link); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
if _, err := measureProjectStorage(link); err == nil {
t.Fatal("symlink project root was accepted")
}
}
func TestPHPAdapterUsesPrivateSocketWithoutDuplicatingAAPanelLocation(t *testing.T) {
adapter := renderPHPNginxAdapter("/run/sea-vhost-php/sv0123456789.sock")
if strings.Contains(adapter, "location ~ [^/]\\.php(/|$)") {
t.Fatal("adapter duplicates aaPanel's shared PHP location")
}
if !strings.Contains(adapter, "location ~ ^.+\\.php(?:/|$)") ||
!strings.Contains(adapter, "fastcgi_pass unix:/run/sea-vhost-php/sv0123456789.sock;") {
t.Fatalf("adapter does not route PHP to the private socket:\n%s", adapter)
}
}
func TestPHPConfigRunsMasterAsPreselectedHostIdentity(t *testing.T) {
paths := phpIdentityPaths{
config: "/var/lib/sea-vhost-agent/php/sv0123456789.conf",
pid: "/run/sea-vhost-php/sv0123456789/php-fpm.pid",
socket: "/run/sea-vhost-php/sv0123456789/php-fpm.sock",
}
spec := PHPIdentitySpec{
Project: ProjectSpec{HostName: "sv0123456789"},
SiteName: "sv0123456789", ProcessLimit: 4,
}
config := renderPHPIdentityConfig(spec, "/www/wwwroot/seavHost/vHost/sv0123456789", "/www/wwwroot/seavHost/vHost/sv0123456789/.sea-runtime/php", paths)
for _, forbidden := range []string{"listen.owner", "listen.group"} {
if strings.Contains(config, forbidden) {
t.Fatalf("non-root PHP master config contains root-only directive %q", forbidden)
}
}
for _, required := range []string{paths.pid, paths.socket, "/.sea-runtime/php/fpm-error.log", "user = sv0123456789", "group = sv0123456789"} {
if !strings.Contains(config, required) {
t.Fatalf("PHP config is missing %q:\n%s", required, config)
}
}
}
func TestEnsureProjectRunDirectoryCreatesOnlyPhysicalChildren(t *testing.T) {
root := t.TempDir()
if err := ensureProjectRunDirectory(root, "/apps/web/public"); err != nil {
t.Fatal(err)
}
if info, err := os.Lstat(filepath.Join(root, "apps", "web", "public")); err != nil || !info.IsDir() {
t.Fatalf("run directory was not created: info=%v err=%v", info, err)
}
if err := os.Symlink(filepath.Join(root, "apps"), filepath.Join(root, "linked")); err == nil {
if err = ensureProjectRunDirectory(root, "/linked/public"); err == nil {
t.Fatal("symlinked run directory was accepted")
}
}
for _, unsafe := range []string{"/../etc", "/public/../etc", "/has space", `C:\\Windows`} {
if ensureProjectRunDirectory(root, unsafe) == nil {
t.Fatalf("unsafe run path %q was accepted", unsafe)
}
}
}
func TestFindProjectUserINIFilesIncludesNestedFilesAndRejectsSymlinks(t *testing.T) {
root := t.TempDir()
public := filepath.Join(root, "public")
if err := os.MkdirAll(public, 0750); err != nil {
t.Fatal(err)
}
for _, name := range []string{filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")} {
if err := os.WriteFile(name, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
}
files, err := findProjectUserINIFiles(root, 4)
if err != nil || len(files) != 2 {
t.Fatalf("files=%#v err=%v", files, err)
}
if err = os.Remove(filepath.Join(public, ".user.ini")); err != nil {
t.Fatal(err)
}
if err = os.Symlink(filepath.Join(root, ".user.ini"), filepath.Join(public, ".user.ini")); err != nil {
t.Skipf("symlink creation is unavailable: %v", err)
}
if _, err = findProjectUserINIFiles(root, 4); err == nil {
t.Fatal("symlinked .user.ini was accepted")
}
}
func TestReleaseRunPathRemovesOnlyExactIsolationFile(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "sv0123456789"
runDirectory := filepath.Join(root, hostName, "apps", "web")
if err := os.MkdirAll(runDirectory, 0770); err != nil {
t.Fatal(err)
}
userINI := filepath.Join(runDirectory, ".user.ini")
source := filepath.Join(runDirectory, "index.php")
if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(source, []byte("<?php"), 0660); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 1)
agent := Agent{Root: root, runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/apps/web", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/run-path/release", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("release status = %d, body = %s", response.Code, response.Body.String())
}
if _, err := os.Stat(userINI); !os.IsNotExist(err) {
t.Fatalf(".user.ini still exists: %v", err)
}
if _, err := os.Stat(source); err != nil {
t.Fatalf("source was changed: %v", err)
}
if len(commands) != 1 || !strings.HasPrefix(commands[0], "chattr -i ") {
t.Fatalf("commands = %#v", commands)
}
}
func TestPrepareTrashReleasesNestedIsolationFiles(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
hostName := "svabcdef0123"
trash := filepath.Join(root, hostName, ".sea-trash", "old-public")
if err := os.MkdirAll(trash, 0770); err != nil {
t.Fatal(err)
}
userINI := filepath.Join(trash, ".user.ini")
if err := os.WriteFile(userINI, []byte("open_basedir=/tmp"), 0644); err != nil {
t.Fatal(err)
}
agent := Agent{Root: root, runCommand: func(context.Context, string, ...string) error { return nil }}
spec := ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/", StorageBytes: 1024, ProcessLimit: 1}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/trash/prepare", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("prepare trash status = %d, body = %s", response.Code, response.Body.String())
}
if _, err := os.Stat(userINI); !os.IsNotExist(err) {
t.Fatalf("trash .user.ini still exists: %v", err)
}
}
func TestWebProtectionUsesFixedAaPanelExtensionAndReloadsSafely(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
vhostRoot := filepath.Join(t.TempDir(), "nginx")
hostName := "sv0123456789"
domain := hostName + ".hosts.example.com"
if err := os.MkdirAll(filepath.Join(root, hostName, "public"), 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(vhostRoot, "extension"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(vhostRoot, "sea-vhost-security-global.conf"), []byte(globalWebProtectionConfig), 0644); err != nil {
t.Fatal(err)
}
extensionGlob := filepath.ToSlash(filepath.Join(vhostRoot, "extension", domain, "*.conf"))
if err := os.WriteFile(filepath.Join(vhostRoot, domain+".conf"), []byte("server { include "+extensionGlob+"; }"), 0644); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 2)
agent := Agent{
Root: root, NginxVhostRoot: vhostRoot, NginxBinary: filepath.Join(t.TempDir(), "nginx"),
runCommand: func(_ context.Context, _ string, args ...string) error {
commands = append(commands, strings.Join(args, " "))
return nil
},
}
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, RunPath: "/public", StorageBytes: 1 << 30, ProcessLimit: 10}, Domain: domain}
body, _ := json.Marshal(spec)
request := httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body))
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("apply status = %d, body = %s", response.Code, response.Body.String())
}
siteFile := filepath.Join(vhostRoot, "extension", domain, "sea-vhost-security.conf")
content, err := os.ReadFile(siteFile)
if err != nil {
t.Fatal(err)
}
for _, expected := range []string{"root \"" + filepath.ToSlash(filepath.Join(root, hostName, "public")) + "\";", "limit_req zone=sea_vhost_per_ip", "client_max_body_size 64m", "X-Content-Type-Options", "TRACE|TRACK"} {
if !strings.Contains(string(content), expected) {
t.Fatalf("site protection is missing %q", expected)
}
}
if len(commands) != 2 || commands[0] != "-t" || commands[1] != "-s reload" {
t.Fatalf("nginx commands = %#v", commands)
}
request = httptest.NewRequest(http.MethodPost, "/v1/web-protection/remove", bytes.NewReader(body))
response = httptest.NewRecorder()
agent.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("remove status = %d, body = %s", response.Code, response.Body.String())
}
if _, err = os.Stat(siteFile); !os.IsNotExist(err) {
t.Fatalf("site protection still exists after removal: %v", err)
}
}
func TestWebProtectionRejectsUnmanagedIdentity(t *testing.T) {
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: "tenant-site", StorageBytes: 1024, ProcessLimit: 1}, Domain: "outside.example.com"}
body, _ := json.Marshal(spec)
request := httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body))
response := httptest.NewRecorder()
Agent{}.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("unmanaged identity status = %d, want 400", response.Code)
}
}
func TestWebProtectionRestoresFilesWhenNginxRejectsConfig(t *testing.T) {
root := filepath.Join(t.TempDir(), "wwwroot")
vhostRoot := filepath.Join(t.TempDir(), "nginx")
hostName := "svabcdef0123"
domain := hostName + ".hosts.example.com"
siteDirectory := filepath.Join(vhostRoot, "extension", domain)
if err := os.MkdirAll(filepath.Join(root, hostName), 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(siteDirectory, 0755); err != nil {
t.Fatal(err)
}
extensionGlob := filepath.ToSlash(filepath.Join(siteDirectory, "*.conf"))
if err := os.WriteFile(filepath.Join(vhostRoot, domain+".conf"), []byte("server { include "+extensionGlob+"; }"), 0644); err != nil {
t.Fatal(err)
}
globalFile := filepath.Join(vhostRoot, "sea-vhost-security-global.conf")
siteFile := filepath.Join(siteDirectory, "sea-vhost-security.conf")
if err := os.WriteFile(globalFile, []byte(globalWebProtectionConfig), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(siteFile, []byte("old-site"), 0644); err != nil {
t.Fatal(err)
}
agent := Agent{
Root: root, NginxVhostRoot: vhostRoot, NginxBinary: filepath.Join(t.TempDir(), "nginx"),
runCommand: func(_ context.Context, _ string, args ...string) error {
if len(args) == 1 && args[0] == "-t" {
return errors.New("invalid nginx config")
}
return nil
},
}
spec := WebProtectionSpec{Project: ProjectSpec{TenantID: 1, HostName: hostName, StorageBytes: 1024, ProcessLimit: 1}, Domain: domain}
body, _ := json.Marshal(spec)
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/web-protection/apply", bytes.NewReader(body)))
if response.Code != http.StatusPreconditionFailed {
t.Fatalf("apply status = %d, want 412", response.Code)
}
globalContent, _ := os.ReadFile(globalFile)
siteContent, _ := os.ReadFile(siteFile)
if string(globalContent) != globalWebProtectionConfig || string(siteContent) != "old-site" {
t.Fatalf("rollback failed: global=%q site=%q", globalContent, siteContent)
}
}
+120
View File
@@ -0,0 +1,120 @@
package isolation
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
func (a Agent) verifyProjectBackup(w http.ResponseWriter, r *http.Request) {
var backup ProjectBackup
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&backup) != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(backup.HostName) || backup.TenantID == 0 || backup.DatabaseCount < 0 || backup.DatabaseCount > 1 {
http.Error(w, "invalid backup verification", 400)
return
}
directory, err := a.backupDirectory(backup.TenantID)
path := filepath.Clean(backup.ArchivePath)
if err != nil || filepath.Dir(path) != directory || !strings.HasPrefix(filepath.Base(path), backup.HostName+"-") || !strings.HasSuffix(path, ".tar.gz") {
http.Error(w, "unsafe backup path", 400)
return
}
if err = verifyRecoveryArchive(r.Context(), path, backup.HostName, backup.DatabaseCount); err != nil {
http.Error(w, "recovery archive is missing, incomplete or corrupt", 412)
return
}
w.WriteHeader(200)
}
func verifyRecoveryArchive(ctx context.Context, path, hostName string, count int) error {
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("unsafe recovery archive")
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
compressed, err := gzip.NewReader(file)
if err != nil {
return err
}
defer compressed.Close()
reader := tar.NewReader(compressed)
type database struct {
Name, Path, SHA256 string
Bytes int64
}
var manifest struct {
Format int
HostName string
Databases []database
}
hashes := map[string]string{}
sizes := map[string]int64{}
hasManifest := false
for {
if ctx.Err() != nil {
return ctx.Err()
}
header, nextErr := reader.Next()
if nextErr == io.EOF {
break
}
if nextErr != nil {
return nextErr
}
if header.Name == ".sea-vhost-backup/manifest.json" {
if hasManifest || header.Size > 64<<10 {
return errors.New("invalid recovery manifest")
}
data, readErr := io.ReadAll(reader)
if readErr != nil {
return readErr
}
if json.Unmarshal(data, &manifest) != nil {
return errors.New("invalid recovery manifest")
}
hasManifest = true
} else if strings.HasPrefix(header.Name, ".sea-vhost-backup/databases/") {
if header.Name != ".sea-vhost-backup/databases/"+hostName+".sql" || header.Typeflag != tar.TypeReg || hashes[header.Name] != "" {
return errors.New("invalid database archive entry")
}
digest := sha256.New()
size, copyErr := io.Copy(digest, reader)
if copyErr != nil {
return copyErr
}
hashes[header.Name] = fmt.Sprintf("%x", digest.Sum(nil))
sizes[header.Name] = size
} else {
if _, err = io.Copy(io.Discard, reader); err != nil {
return err
}
}
}
// Read the gzip trailer as well; tar's end marker alone does not validate CRC.
if _, err = io.Copy(io.Discard, compressed); err != nil {
return err
}
if !hasManifest || manifest.Format != 2 || manifest.HostName != hostName || len(manifest.Databases) != count || len(hashes) != count {
return errors.New("incomplete recovery archive")
}
for _, db := range manifest.Databases {
if db.Name != hostName || db.SHA256 != hashes[db.Path] || db.Bytes != sizes[db.Path] || db.Bytes == 0 {
return errors.New("database recovery checksum mismatch")
}
}
return nil
}
+184
View File
@@ -0,0 +1,184 @@
package isolation
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
type Client struct {
http *http.Client
longHTTP *http.Client
internalToken string
}
func NewTransportClient(transport http.RoundTripper) *Client {
return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}}
}
func NewClient(socket string, internalToken ...string) *Client {
transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}}
token := ""
if len(internalToken) > 0 {
token = strings.TrimSpace(internalToken[0])
}
return &Client{http: &http.Client{Transport: transport, Timeout: 30 * time.Second}, longHTTP: &http.Client{Transport: transport, Timeout: 2 * time.Hour}, internalToken: token}
}
func (c *Client) Ping(ctx context.Context) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://unix/healthz", nil)
if err != nil {
return err
}
if c.internalToken != "" {
request.Header.Set("Authorization", "Bearer "+c.internalToken)
}
response, err := c.http.Do(request)
if err != nil {
return fmt.Errorf("isolation agent: %w", err)
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4<<10))
if response.StatusCode != http.StatusOK {
return fmt.Errorf("isolation agent health check failed (%d)", response.StatusCode)
}
return nil
}
func (c *Client) request(ctx context.Context, path string, input any, out any) error {
return c.requestWithClient(ctx, c.http, path, input, out)
}
func (c *Client) requestLong(ctx context.Context, path string, input any, out any) error {
return c.requestWithClient(ctx, c.longHTTP, path, input, out)
}
func (c *Client) requestWithClient(ctx context.Context, client *http.Client, path string, input any, out any) error {
body, err := json.Marshal(input)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://unix"+path, bytes.NewReader(body))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
if c.internalToken != "" {
request.Header.Set("Authorization", "Bearer "+c.internalToken)
}
response, err := client.Do(request)
if err != nil {
return fmt.Errorf("isolation agent: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
message, _ := io.ReadAll(io.LimitReader(response.Body, 512))
detail := strings.TrimSpace(string(message))
if detail == "" {
detail = "unspecified error"
}
return fmt.Errorf("isolation agent rejected request (%d): %s", response.StatusCode, detail)
}
if out != nil {
return json.NewDecoder(response.Body).Decode(out)
}
return nil
}
func (c *Client) Prepare(ctx context.Context, spec ProjectSpec) (Prepared, error) {
var result Prepared
err := c.request(ctx, "/v1/prepare", spec, &result)
return result, err
}
func (c *Client) Quarantine(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/quarantine", spec, nil)
}
func (c *Client) ApplyWebProtection(ctx context.Context, spec WebProtectionSpec) error {
return c.request(ctx, "/v1/web-protection/apply", spec, nil)
}
func (c *Client) RemoveWebProtection(ctx context.Context, spec WebProtectionSpec) error {
return c.request(ctx, "/v1/web-protection/remove", spec, nil)
}
func (c *Client) PrepareExecutable(ctx context.Context, spec ExecutableSpec) error {
return c.request(ctx, "/v1/runtime/executable", spec, nil)
}
func (c *Client) PreparePanelRuntime(ctx context.Context, spec PanelRuntimeSpec) error {
return c.request(ctx, "/v1/runtime/panel-state", spec, nil)
}
func (c *Client) InstallPythonRuntime(ctx context.Context, version string) error {
return c.requestLong(ctx, "/v1/runtime/python/install", PythonRuntimeInstallSpec{Version: version}, nil)
}
func (c *Client) TerminateRuntime(ctx context.Context, spec RuntimeProcessSpec) error {
return c.request(ctx, "/v1/resources/runtime/terminate", spec, nil)
}
func (c *Client) ReleaseRunPath(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/run-path/release", spec, nil)
}
func (c *Client) PrepareTrash(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/trash/prepare", spec, nil)
}
func (c *Client) ConfigureFTPIdentity(ctx context.Context, spec FTPIdentitySpec) error {
return c.request(ctx, "/v1/ftp/identity", spec, nil)
}
func (c *Client) ConfigurePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error {
return c.request(ctx, "/v1/php/identity", spec, nil)
}
func (c *Client) SetPHPIdentityState(ctx context.Context, spec PHPIdentitySpec, enabled bool) error {
path := "/v1/php/identity/stop"
if enabled {
path = "/v1/php/identity/start"
}
return c.request(ctx, path, spec, nil)
}
func (c *Client) RemovePHPIdentity(ctx context.Context, spec PHPIdentitySpec) error {
return c.request(ctx, "/v1/php/identity/remove", spec, nil)
}
func (c *Client) ResourceUsage(ctx context.Context, spec ResourceUsageSpec) (ResourceUsage, error) {
var result ResourceUsage
err := c.request(ctx, "/v1/resources/usage", spec, &result)
return result, err
}
func (c *Client) TerminateProcesses(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/resources/processes/terminate", spec, nil)
}
func (c *Client) FreezeWrites(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/project/freeze-writes", spec, nil)
}
func (c *Client) ConfigureDatabaseAccess(ctx context.Context, spec DatabaseAccessSpec) error {
return c.request(ctx, "/v1/database/access", spec, nil)
}
func (c *Client) ConfigureTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error {
return c.request(ctx, "/v1/resources/limits", spec, nil)
}
func (c *Client) ConfigureFTPTLS(ctx context.Context, domain string) (string, error) {
var result struct {
Policy string `json:"policy"`
}
err := c.request(ctx, "/v1/ftp/tls", map[string]string{"domain": domain}, &result)
return result.Policy, err
}
func (c *Client) ConfigureNginxNetwork(ctx context.Context, spec NginxNetworkSpec) error {
return c.request(ctx, "/v1/nginx/network", spec, nil)
}
func (c *Client) CreateProjectBackup(ctx context.Context, spec ProjectSpec) (ProjectBackup, error) {
var result ProjectBackup
err := c.requestLong(ctx, "/v1/lifecycle/backup", spec, &result)
return result, err
}
func (c *Client) DeleteProjectBackup(ctx context.Context, backup ProjectBackup) error {
return c.request(ctx, "/v1/lifecycle/backup/delete", backup, nil)
}
func (c *Client) VerifyProjectBackup(ctx context.Context, backup ProjectBackup) error {
return c.requestLong(ctx, "/v1/lifecycle/backup/verify", backup, nil)
}
func (c *Client) PurgeProject(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/lifecycle/project/purge", spec, nil)
}
func (c *Client) ImportLegacyProject(ctx context.Context, spec LegacyImportSpec) error {
return c.requestLong(ctx, "/v1/import/project", spec, nil)
}
@@ -0,0 +1,77 @@
package isolation
import (
"context"
"database/sql"
"errors"
"github.com/go-sql-driver/mysql"
"net/http"
"strconv"
)
type CredentialSessions interface {
DisconnectCredentialSessions(context.Context, ProjectSpec) error
}
func (c *Client) DisconnectCredentialSessions(ctx context.Context, spec ProjectSpec) error {
return c.request(ctx, "/v1/credentials/disconnect", spec, nil)
}
func (Mock) DisconnectCredentialSessions(context.Context, ProjectSpec) error { return nil }
func (a Agent) disconnectCredentialSessions(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
root, err := a.projectPath(spec)
if err != nil || !managedWebHostPattern.MatchString(spec.HostName) || requirePhysicalDirectory(root) != nil {
http.Error(w, "invalid managed identity", 412)
return
}
db, err := a.openMySQL(r.Context())
if err != nil {
http.Error(w, "database session inspection unavailable", 412)
return
}
defer db.Close()
if err = disconnectManagedDatabaseSessions(r.Context(), db, spec.HostName); err != nil {
http.Error(w, "cannot revoke managed database sessions", 412)
return
}
if err = disconnectFTPSessions(r.Context(), spec.HostName); err != nil {
http.Error(w, "cannot revoke managed FTP sessions", 412)
return
}
w.WriteHeader(200)
}
func disconnectManagedDatabaseSessions(ctx context.Context, db *sql.DB, name string) error {
if !managedWebHostPattern.MatchString(name) {
return errors.New("invalid database identity")
}
rows, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name)
if err != nil {
return err
}
var ids []uint64
for rows.Next() {
var id uint64
if err = rows.Scan(&id); err != nil {
rows.Close()
return err
}
ids = append(ids, id)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, id := range ids {
if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil {
var native *mysql.MySQLError
if !errors.As(err, &native) || native.Number != 1094 {
return err
}
}
}
return nil
}
@@ -0,0 +1,60 @@
//go:build linux
package isolation
import (
"context"
"errors"
"os"
"strconv"
"strings"
"syscall"
)
func disconnectFTPSessions(ctx context.Context, identity string) error {
uid, err := identityUID(identity)
if err != nil {
return err
}
pids, err := identityPIDs(identity)
if err != nil {
return err
}
for _, pid := range pids {
if ctx.Err() != nil {
return ctx.Err()
}
process, e := os.FindProcess(pid)
if e != nil {
continue
}
base := "/proc/" + strconv.Itoa(pid)
exe, exeErr := os.Readlink(base + "/exe")
status, readErr := os.ReadFile(base + "/status")
// CAP_SYS_PTRACE is intentionally absent from the agent. Linux can deny
// /proc/<pid>/exe across UIDs; status Name/Uid remain readable. Restrict the
// fallback to this host's UID and the exact FTP daemon name, with the pidfd
// acquired before either read so a recycled PID cannot target another task.
if readErr == nil && statusHasUID(status, uid) && managedFTPProcess(status, exe, exeErr != nil) {
e = process.Kill()
if e != nil && !errors.Is(e, os.ErrProcessDone) && !errors.Is(e, syscall.ESRCH) {
process.Release()
return e
}
}
process.Release()
}
return nil
}
func managedFTPProcess(status []byte, exe string, unreadable bool) bool {
if !unreadable {
return strings.HasPrefix(exe, "/www/server/pure-ftpd/") && strings.HasSuffix(exe, "/pure-ftpd")
}
for _, line := range strings.Split(string(status), "\n") {
if strings.HasPrefix(line, "Name:") {
return strings.TrimSpace(strings.TrimPrefix(line, "Name:")) == "pure-ftpd"
}
}
return false
}
@@ -0,0 +1,16 @@
//go:build linux
package isolation
import "testing"
func TestFTPSessionIdentificationDoesNotSelectRuntimeProcesses(t *testing.T) {
for _, test := range []struct {
name, exe string
unreadable, want bool
}{{"pure-ftpd", "/www/server/pure-ftpd/sbin/pure-ftpd", false, true}, {"node", "/www/server/nodejs/node", false, false}, {"node", "", true, false}, {"pure-ftpd", "/usr/bin/node", false, false}, {"pure-ftpd", "", true, true}, {"pure-ftpd-other", "", true, false}} {
if got := managedFTPProcess([]byte("Name:\t"+test.name+"\nUid:\t1001\t1001\t1001\t1001\n"), test.exe, test.unreadable); got != test.want {
t.Errorf("FTP match %s: %t", test.name, got)
}
}
}
@@ -0,0 +1,12 @@
//go:build !linux
package isolation
import (
"context"
"errors"
)
func disconnectFTPSessions(context.Context, string) error {
return errors.New("credential sessions require Linux")
}
@@ -0,0 +1,211 @@
package isolation
import (
"context"
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"os/exec"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
)
// Root credentials stay inside the root agent. The fixed, isolated Python
// program reads only aaPanel's local configuration; no shell or supplied code.
func (a Agent) mysqlConfig(ctx context.Context) (*mysql.Config, error) {
if a.databaseAdminDSN != "" {
return mysql.ParseDSN(a.databaseAdminDSN)
}
command := exec.CommandContext(ctx, "/www/server/panel/pyenv/bin/python3", "-I", "-c", `import os,sys,json,re
from pathlib import Path
os.chdir('/www/server/panel');sys.path.insert(0,'/www/server/panel/class');import public
password=public.M('config').where('id=?',(1,)).getField('mysql_root')
assert isinstance(password,str) and password
port=3306
socket='/tmp/mysql.sock'
p=Path('/etc/my.cnf')
if p.is_file():
text=p.read_text();section=False
for line in text.splitlines():
line=line.strip()
if line.startswith('['):section=line.lower()=='[mysqld]'
elif section:
m=re.fullmatch(r'port\s*=\s*(\d+)\s*(?:[#;].*)?',line)
if m:port=int(m.group(1))
m=re.fullmatch(r'socket\s*=\s*(/[^\s#;]+)\s*(?:[#;].*)?',line)
if m:socket=m.group(1)
assert 1<=port<=65535
print(json.dumps({'password':password,'port':port,'socket':socket}))`)
data, err := command.Output()
if err != nil || len(data) > 64<<10 {
return nil, errors.New("cannot read local MySQL administrator configuration")
}
var value struct {
Password string
Port int
Socket string
}
if json.Unmarshal(data, &value) != nil || value.Password == "" || value.Port < 1 || value.Port > 65535 {
return nil, errors.New("invalid local MySQL administrator configuration")
}
cfg := mysql.NewConfig()
cfg.User = "root"
cfg.Passwd = value.Password
cfg.Net = "unix"
cfg.Addr = value.Socket
if !strings.HasPrefix(cfg.Addr, "/") || strings.ContainsAny(cfg.Addr, "\r\n\x00") {
return nil, errors.New("invalid MySQL socket path")
}
if strings.HasPrefix(cfg.Addr, "/tmp/") {
cfg.Addr = "/etc/sea-vhost-mysql/host-tmp/" + strings.TrimPrefix(cfg.Addr, "/tmp/")
}
cfg.Timeout = 5 * time.Second
cfg.ReadTimeout = 30 * time.Second
cfg.WriteTimeout = 30 * time.Second
return cfg, nil
}
func (a Agent) openMySQL(ctx context.Context) (*sql.DB, error) {
cfg, err := a.mysqlConfig(ctx)
if err != nil {
return nil, err
}
db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, errors.New("cannot initialize local MySQL administrator connection")
}
db.SetMaxOpenConns(1)
if db.PingContext(ctx) != nil {
db.Close()
return nil, errors.New("cannot connect to local MySQL administrator")
}
return db, nil
}
func (a Agent) configureDatabaseAccess(w http.ResponseWriter, r *http.Request) {
var spec DatabaseAccessSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Database != spec.Project.HostName || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 {
http.Error(w, "invalid managed database identity", 400)
return
}
root, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(root) != nil {
http.Error(w, "managed project root unavailable", 412)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
db, err := a.openMySQL(ctx)
if err == nil {
defer db.Close()
err = setDatabaseAccess(ctx, db, spec.Database, spec.ReadOnly, spec.BlockCleanup)
}
if err != nil {
http.Error(w, "cannot enforce managed database access: "+err.Error(), 412)
return
}
w.WriteHeader(200)
}
func setDatabaseAccess(ctx context.Context, db *sql.DB, name string, readOnly, blockCleanup bool) error {
if !managedWebHostPattern.MatchString(name) {
return errors.New("invalid database name")
}
cleanupPrivilege := "Y"
if blockCleanup {
cleanupPrivilege = "N"
}
rows, err := db.QueryContext(ctx, `SELECT u.Host,COALESCE(d.Insert_priv,'N'),COALESCE(d.Select_priv='Y' AND d.Delete_priv=? AND d.Drop_priv=? AND d.Insert_priv='N' AND d.Update_priv='N' AND d.Create_priv='N' AND d.Grant_priv='N' AND d.References_priv='N' AND d.Index_priv='N' AND d.Alter_priv='N' AND d.Create_tmp_table_priv='N' AND d.Lock_tables_priv='N' AND d.Create_view_priv='N' AND d.Show_view_priv='N' AND d.Create_routine_priv='N' AND d.Alter_routine_priv='N' AND d.Execute_priv='N' AND d.Event_priv='N' AND d.Trigger_priv='N',FALSE) FROM mysql.user u LEFT JOIN mysql.db d ON d.User=u.User AND d.Host=u.Host AND d.Db=? WHERE u.User=?`, cleanupPrivilege, cleanupPrivilege, name, name)
if err != nil {
return errors.New("cannot inspect managed account")
}
type account struct {
host, insert string
readOnly bool
}
var accounts []account
for rows.Next() {
var item account
if err = rows.Scan(&item.host, &item.insert, &item.readOnly); err != nil {
rows.Close()
return err
}
if item.host != "localhost" && item.host != "127.0.0.1" && item.host != "::1" && item.host != "%" {
rows.Close()
return errors.New("unexpected managed account host")
}
accounts = append(accounts, item)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(accounts) == 0 {
return errors.New("managed account not found")
}
changed := false
for _, item := range accounts {
if (readOnly && item.readOnly) || (!readOnly && item.insert == "Y") {
continue
}
accountSQL := "'" + name + "'@'" + item.host + "'"
if _, err = db.ExecContext(ctx, "REVOKE ALL PRIVILEGES, GRANT OPTION FROM "+accountSQL); err != nil {
return errors.New("cannot revoke managed account privileges")
}
privileges := "ALL PRIVILEGES"
if readOnly {
privileges = "SELECT, DELETE, DROP"
if blockCleanup {
privileges = "SELECT"
}
}
if _, err = db.ExecContext(ctx, "GRANT "+privileges+" ON `"+name+"`.* TO "+accountSQL); err != nil {
return errors.New("cannot grant managed account recovery privileges")
}
changed = true
}
if !changed && !readOnly {
return nil
}
// Existing sessions cache database grants. Disconnect only this exact user,
// so pooled connections and transactions cannot retain the old write access.
sessions, err := db.QueryContext(ctx, "SELECT ID FROM information_schema.PROCESSLIST WHERE USER=?", name)
if err != nil {
return errors.New("cannot inspect managed database sessions")
}
var ids []uint64
for sessions.Next() {
var id uint64
if err = sessions.Scan(&id); err != nil {
sessions.Close()
return err
}
ids = append(ids, id)
}
err = sessions.Err()
sessions.Close()
if err != nil {
return err
}
for _, id := range ids {
if _, err = db.ExecContext(ctx, "KILL CONNECTION "+strconv.FormatUint(id, 10)); err != nil {
var mysqlErr *mysql.MySQLError
if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1094 {
return errors.New("cannot disconnect managed database session")
}
}
}
return nil
}
func mysqlOptionValue(value string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\r", `\r`).Replace(value) + `"`
}
@@ -0,0 +1,112 @@
package isolation
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"testing"
)
func TestDatabaseBackupManifestAndSQLAreInSameArchive(t *testing.T) {
root := t.TempDir()
sql := []byte("CREATE TABLE marker(value TEXT); INSERT INTO marker VALUES ('SEA-BACKUP-SENTINEL');\n")
file := filepath.Join(t.TempDir(), "db.sql")
if err := os.WriteFile(file, sql, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "index.php"), []byte("<?php echo 'site';"), 0600); err != nil {
t.Fatal(err)
}
digest := fmt.Sprintf("%x", sha256.Sum256(sql))
var output bytes.Buffer
err := writeTarGzipDatabase(context.Background(), &output, root, "sv0123456789", []backupDatabaseFile{{name: "sv0123456789", path: file, size: int64(len(sql)), digest: digest}})
if err != nil {
t.Fatal(err)
}
gz, err := gzip.NewReader(&output)
if err != nil {
t.Fatal(err)
}
defer gz.Close()
reader := tar.NewReader(gz)
foundSQL, foundManifest, foundSite := false, false, false
for {
header, err := reader.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(reader)
if err != nil {
t.Fatal(err)
}
switch header.Name {
case "sv0123456789/index.php":
foundSite = true
case ".sea-vhost-backup/databases/sv0123456789.sql":
foundSQL = bytes.Equal(data, sql)
if header.Mode != 0600 {
t.Fatal("SQL backup is not private")
}
case ".sea-vhost-backup/manifest.json":
var value struct {
Format int
Databases []struct {
Name, Path, SHA256 string
Bytes int64
}
}
if err = json.Unmarshal(data, &value); err != nil {
t.Fatal(err)
}
foundManifest = value.Format == 2 && len(value.Databases) == 1 && value.Databases[0].SHA256 == digest && value.Databases[0].Bytes == int64(len(sql))
}
}
if !foundSQL || !foundManifest || !foundSite {
t.Fatal("incomplete recovery archive")
}
archivePath := filepath.Join(t.TempDir(), "backup.tar.gz")
// output was consumed by gzip.NewReader; generate a fresh archive for CRC checks.
var complete bytes.Buffer
if err = writeTarGzipDatabase(context.Background(), &complete, root, "sv0123456789", []backupDatabaseFile{{name: "sv0123456789", path: file, size: int64(len(sql)), digest: digest}}); err != nil {
t.Fatal(err)
}
if err = os.WriteFile(archivePath, complete.Bytes(), 0600); err != nil {
t.Fatal(err)
}
if err = verifyRecoveryArchive(context.Background(), archivePath, "sv0123456789", 1); err != nil {
t.Fatal(err)
}
corrupt := append([]byte(nil), complete.Bytes()...)
corrupt[len(corrupt)-4] ^= 0xff
if err = os.WriteFile(archivePath, corrupt, 0600); err != nil {
t.Fatal(err)
}
if verifyRecoveryArchive(context.Background(), archivePath, "sv0123456789", 1) == nil {
t.Fatal("corrupt recovery archive accepted")
}
}
func TestDatabaseBackupRejectsForeignDatabaseBeforeExecution(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "sv0123456789"), 0700); err != nil {
t.Fatal(err)
}
response := lifecycleRequest(t, Agent{Root: root, BackupRoot: t.TempDir()}, "/v1/lifecycle/backup", ProjectSpec{TenantID: 1, HostName: "sv0123456789", RunPath: "/", StorageBytes: 1024, ProcessLimit: 1, Databases: []string{"mysql"}})
if response.Code != 400 {
t.Fatalf("foreign database status=%d", response.Code)
}
response = lifecycleRequest(t, Agent{Root: root}, "/v1/database/access", DatabaseAccessSpec{Project: ProjectSpec{TenantID: 1, HostName: "sv0123456789", StorageBytes: 1024, ProcessLimit: 1}, Database: "mysql", ReadOnly: true})
if response.Code != 400 {
t.Fatalf("foreign account status=%d", response.Code)
}
}
@@ -0,0 +1,128 @@
package isolation
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"io"
"net"
"net/http"
"net/textproto"
"strconv"
"time"
)
// The socket is private; all FastCGI parameters are assembled by the agent.
func callFastCGI(ctx context.Context, socket string, params map[string]string, body []byte) (int, http.Header, []byte, error) {
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
if e != nil {
return 0, nil, nil, e
}
defer conn.Close()
deadline := time.Now().Add(120 * time.Second)
if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
deadline = d
}
conn.SetDeadline(deadline)
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
conn.Close()
case <-done:
}
}()
record := func(kind byte, data []byte) error {
for len(data) > 0 {
n := min(len(data), 65535)
header := []byte{1, kind, 0, 1, byte(n >> 8), byte(n), 0, 0}
if _, e := conn.Write(header); e != nil {
return e
}
if _, e := conn.Write(data[:n]); e != nil {
return e
}
data = data[n:]
}
return nil
}
empty := func(kind byte) error { _, e := conn.Write([]byte{1, kind, 0, 1, 0, 0, 0, 0}); return e }
if e = record(1, []byte{0, 1, 0, 0, 0, 0, 0, 0}); e != nil {
return 0, nil, nil, e
}
var encoded bytes.Buffer
length := func(n int) {
if n < 128 {
encoded.WriteByte(byte(n))
} else {
var value [4]byte
binary.BigEndian.PutUint32(value[:], uint32(n)|0x80000000)
encoded.Write(value[:])
}
}
for name, value := range params {
length(len(name))
length(len(value))
encoded.WriteString(name)
encoded.WriteString(value)
}
if e = record(4, encoded.Bytes()); e == nil {
e = empty(4)
}
if e == nil {
e = record(5, body)
}
if e == nil {
e = empty(5)
}
if e != nil {
return 0, nil, nil, e
}
var output bytes.Buffer
for {
var header [8]byte
if _, e = io.ReadFull(conn, header[:]); e != nil {
return 0, nil, nil, e
}
if header[0] != 1 || header[2] != 0 || header[3] != 1 {
return 0, nil, nil, errors.New("invalid FastCGI record")
}
n := int(binary.BigEndian.Uint16(header[4:6]))
content := make([]byte, n+int(header[6]))
if _, e = io.ReadFull(conn, content); e != nil {
return 0, nil, nil, e
}
switch header[1] {
case 6:
if output.Len()+n > 2<<20 {
return 0, nil, nil, errors.New("phpMyAdmin response exceeds 2 MiB")
}
output.Write(content[:n])
case 3:
if n < 8 || binary.BigEndian.Uint32(content[:4]) != 0 || content[4] != 0 {
return 0, nil, nil, errors.New("phpMyAdmin process failed")
}
reader := bufio.NewReader(bytes.NewReader(output.Bytes()))
headers, e := textproto.NewReader(reader).ReadMIMEHeader()
if e != nil {
return 0, nil, nil, e
}
status := 200
if raw := headers.Get("Status"); raw != "" {
if len(raw) < 3 {
return 0, nil, nil, errors.New("invalid CGI status")
}
status, e = strconv.Atoi(raw[:3])
if e != nil || status < 100 || status > 599 {
return 0, nil, nil, errors.New("invalid CGI status")
}
}
headers.Del("Status")
data, e := io.ReadAll(reader)
return status, http.Header(headers), data, e
}
}
}
+63
View File
@@ -0,0 +1,63 @@
package isolation
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
)
// The panel's disabled state still permits 127.0.0.1. A suspended host must
// also reject local FTP clients; normal TCP peers cannot originate at 0.0.0.0.
// The panel's enable operation clears this source restriction on recovery.
func (a Agent) freezeFTPLogin(ctx context.Context, username string) error {
binary := a.PurePWBinary
if binary == "" {
binary = "/www/server/pure-ftpd/bin/pure-pw"
}
if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" || !safeName.MatchString(username) {
return errors.New("invalid FTP freeze identity")
}
directory := filepath.Join(filepath.Dir(filepath.Dir(binary)), "etc")
if a.PureFTPConfig != "" {
directory = filepath.Dir(a.PureFTPConfig)
}
if _, err := os.Lstat(directory); errors.Is(err, os.ErrNotExist) {
return nil
}
if err := requirePhysicalDirectory(directory); err != nil {
return err
}
root, err := os.OpenRoot(directory)
if err != nil {
return err
}
defer root.Close()
info, err := root.Lstat("pureftpd.passwd")
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 {
return errors.New("unsafe FTP account database")
}
file, err := root.Open("pureftpd.passwd")
if err != nil {
return err
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, (16<<20)+1))
if err != nil {
return err
}
if len(data) > 16<<20 {
return errors.New("FTP account database exceeds limit")
}
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, username+":") {
return a.command(ctx, binary, "usermod", username, "-r", "0.0.0.0", "-m")
}
}
return nil
}
@@ -0,0 +1,47 @@
package isolation
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
func TestFTPFreezeOnlyChangesMatchingManagedAccount(t *testing.T) {
root := t.TempDir()
directory := filepath.Join(root, "etc")
if err := os.Mkdir(directory, 0700); err != nil {
t.Fatal(err)
}
file := filepath.Join(directory, "pureftpd.passwd")
if err := os.WriteFile(file, []byte("other-user:private-hash:1001\nsv0123456789:private-hash:1002\n"), 0600); err != nil {
t.Fatal(err)
}
var calls []string
a := Agent{PurePWBinary: filepath.Join(root, "bin", "pure-pw"), runCommand: func(_ context.Context, name string, args ...string) error {
calls = append(calls, strings.Join(args, " "))
return nil
}}
if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err != nil {
t.Fatal(err)
}
if len(calls) != 1 || calls[0] != "usermod sv0123456789 -r 0.0.0.0 -m" {
t.Fatalf("unexpected FTP changes: %v", calls)
}
if err := a.freezeFTPLogin(context.Background(), "sv1111111111"); err != nil {
t.Fatal(err)
}
if len(calls) != 1 {
t.Fatal("missing account changed unrelated FTP resources")
}
if err := os.Remove(file); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "outside"), file); err != nil {
t.Skip("symlink unavailable")
}
if err := a.freezeFTPLogin(context.Background(), "sv0123456789"); err == nil {
t.Fatal("symlink account database accepted")
}
}
@@ -0,0 +1,43 @@
package isolation
import (
"context"
"encoding/json"
"io"
"net/http"
"path/filepath"
"strings"
"time"
)
func (a Agent) configureFTPIdentity(w http.ResponseWriter, r *http.Request) {
var spec FTPIdentitySpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!safeName.MatchString(spec.Project.HostName) || spec.Username != spec.Project.HostName ||
spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
binary := strings.TrimSpace(a.PurePWBinary)
if binary == "" {
binary = "/www/server/pure-ftpd/bin/pure-pw"
}
if !filepath.IsAbs(binary) || filepath.Base(binary) != "pure-pw" {
http.Error(w, "invalid Pure-FTPd identity tool", http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err = a.command(ctx, binary, "usermod", spec.Username, "-u", spec.Project.HostName, "-g", spec.Project.HostName, "-d", projectRoot, "-m"); err != nil {
http.Error(w, "cannot bind FTP account to isolated identity", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
@@ -0,0 +1,6 @@
package isolation
import("context";"net/http")
type FTPManager interface{DisconnectFTP(context.Context,ProjectSpec)error}
func(c *Client)DisconnectFTP(ctx context.Context,p ProjectSpec)error{return c.request(ctx,"/v1/ftp/disconnect",p,nil)}
func(Mock)DisconnectFTP(context.Context,ProjectSpec)error{return nil}
func(a Agent)disconnectFTP(w http.ResponseWriter,r *http.Request){p,ok:=a.decode(w,r);if !ok{return};root,e:=a.projectPath(p);if e!=nil||!managedWebHostPattern.MatchString(p.HostName)||requirePhysicalDirectory(root)!=nil{http.Error(w,"invalid managed identity",412);return};if e=disconnectFTPSessions(r.Context(),p.HostName);e!=nil{http.Error(w,"cannot disconnect FTP",422);return};w.WriteHeader(200)}
+187
View File
@@ -0,0 +1,187 @@
package isolation
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
var pureFTPTLSLine = regexp.MustCompile(`(?m)^[ \t]*TLS[ \t]+[0-9]+[ \t]*\r?$`)
var pureFTPCertFileLine = regexp.MustCompile(`(?m)^[ \t]*CertFile[ \t]+[^\r\n]+\r?$`)
func (a Agent) configureFTPTLS(w http.ResponseWriter, r *http.Request) {
var input struct {
Domain string `json:"domain"`
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
input.Domain = strings.ToLower(strings.TrimSpace(input.Domain))
if !webDomainPattern.MatchString(input.Domain) {
http.Error(w, "invalid FTP domain", http.StatusBadRequest)
return
}
policy, err := a.applyFTPTLSPolicy(r.Context(), input.Domain)
if err != nil {
http.Error(w, "cannot configure FTP TLS", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"policy": policy})
}
func (a Agent) applyFTPTLSPolicy(ctx context.Context, domain string) (string, error) {
certRoot := a.CertificateRoot
if certRoot == "" {
certRoot = "/www/server/panel/vhost/cert"
}
configPath := a.PureFTPConfig
if configPath == "" {
configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf"
}
pemPath := a.PureFTPPem
if pemPath == "" {
pemPath = "/www/server/pure-ftpd/etc/pure-ftpd.pem"
}
certPath := filepath.Join(certRoot, domain, "fullchain.pem")
keyPath := filepath.Join(certRoot, domain, "privkey.pem")
certInfo, certErr := os.Lstat(certPath)
keyInfo, keyErr := os.Lstat(keyPath)
hasCert := certErr == nil && keyErr == nil
if (certErr == nil) != (keyErr == nil) || (certErr != nil && !errors.Is(certErr, os.ErrNotExist)) || (keyErr != nil && !errors.Is(keyErr, os.ErrNotExist)) {
return "", errors.New("incomplete FTP certificate")
}
if hasCert && (!certInfo.Mode().IsRegular() || certInfo.Mode()&os.ModeSymlink != 0 || !keyInfo.Mode().IsRegular() || keyInfo.Mode()&os.ModeSymlink != 0) {
return "", errors.New("unsafe FTP certificate")
}
configInfo, err := os.Lstat(configPath)
if err != nil || !configInfo.Mode().IsRegular() || configInfo.Mode()&os.ModeSymlink != 0 {
return "", errors.New("unsafe Pure-FTPd configuration")
}
config, err := os.ReadFile(configPath)
if err != nil {
return "", err
}
wantedTLS := "TLS 0"
policy := "plain_allowed_no_certificate"
changed := false
if hasCert {
pair, pairErr := tls.LoadX509KeyPair(certPath, keyPath)
if pairErr != nil || len(pair.Certificate) == 0 {
return "", errors.New("invalid FTP certificate pair")
}
leaf, parseErr := x509.ParseCertificate(pair.Certificate[0])
if parseErr != nil || time.Now().Before(leaf.NotBefore) || !time.Now().Before(leaf.NotAfter) {
return "", errors.New("FTP certificate is not currently valid")
}
if err = leaf.VerifyHostname(domain); err != nil {
return "", errors.New("FTP certificate does not match the configured domain")
}
certPEM, readCertErr := os.ReadFile(certPath)
keyPEM, readKeyErr := os.ReadFile(keyPath)
if readCertErr != nil || readKeyErr != nil {
return "", errors.Join(readCertErr, readKeyErr)
}
combined := append(bytes.TrimSpace(certPEM), '\n')
combined = append(combined, bytes.TrimSpace(keyPEM)...)
combined = append(combined, '\n')
existing, _ := os.ReadFile(pemPath)
if !bytes.Equal(existing, combined) {
if err = writeSecureFile(pemPath, combined, 0600); err != nil {
return "", err
}
changed = true
}
wantedTLS = "TLS 2"
policy = "explicit_tls_required"
}
directiveCount := 0
updated := pureFTPTLSLine.ReplaceAllFunc(config, func([]byte) []byte {
directiveCount++
if directiveCount == 1 {
return []byte(wantedTLS)
}
return nil
})
if directiveCount == 0 {
updated = append(bytes.TrimRight(config, "\r\n"), []byte("\n"+wantedTLS+"\n")...)
}
if hasCert {
wantedCertFile := []byte("CertFile " + pemPath)
certFileCount := 0
updated = pureFTPCertFileLine.ReplaceAllFunc(updated, func([]byte) []byte {
certFileCount++
if certFileCount == 1 {
return wantedCertFile
}
return nil
})
if certFileCount == 0 {
updated = append(bytes.TrimRight(updated, "\r\n"), '\n')
updated = append(updated, wantedCertFile...)
updated = append(updated, '\n')
}
}
if !bytes.Equal(updated, config) {
if err = writeSecureFile(configPath, updated, configInfo.Mode().Perm()); err != nil {
return "", err
}
changed = true
}
if changed {
// Pure-FTPd turns the configuration into daemon command-line flags at
// process start. A SysV-generated unit may report a successful reload
// without replacing those flags, so TLS policy changes require a full
// restart rather than reload-or-restart.
if err = a.restartPureFTP(ctx, configPath); err != nil {
return "", err
}
}
return policy, nil
}
func (a Agent) restartPureFTP(ctx context.Context, configPath string) error {
if err := a.command(ctx, "systemctl", "stop", "pure-ftpd.service"); err != nil {
return err
}
binaryPath := filepath.Join(filepath.Dir(filepath.Dir(configPath)), "sbin", "pure-ftpd")
if err := terminatePureFTPDaemons(ctx, binaryPath); err != nil {
return err
}
return a.command(ctx, "systemctl", "start", "pure-ftpd.service")
}
func writeSecureFile(path string, data []byte, mode os.FileMode) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".sea-vhost-*.tmp")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err = temporary.Chmod(mode); err == nil {
_, err = temporary.Write(data)
}
if err == nil {
err = temporary.Sync()
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return err
}
return os.Rename(temporaryPath, path)
}
+129
View File
@@ -0,0 +1,129 @@
package isolation
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestApplyFTPTLSPolicyRejectsCertificateForAnotherDomain(t *testing.T) {
root := t.TempDir()
certRoot := filepath.Join(root, "cert")
domain := "ftp.example.com"
certDir := filepath.Join(certRoot, domain)
if err := os.MkdirAll(certDir, 0700); err != nil {
t.Fatal(err)
}
certificate, privateKey := ftpTestCertificatePair(t, "other.example.com")
if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(root, "pure-ftpd.conf")
if err := os.WriteFile(configPath, []byte("TLS 0\n"), 0600); err != nil {
t.Fatal(err)
}
pemPath := filepath.Join(root, "pure-ftpd.pem")
agent := Agent{
CertificateRoot: certRoot,
PureFTPConfig: configPath,
PureFTPPem: pemPath,
runCommand: func(context.Context, string, ...string) error {
t.Fatal("service restart must not run for a mismatched certificate")
return nil
},
}
_, err := agent.applyFTPTLSPolicy(context.Background(), domain)
if err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("mismatched certificate error = %v", err)
}
if _, statErr := os.Stat(pemPath); !os.IsNotExist(statErr) {
t.Fatalf("FTP PEM was written for a mismatched certificate: %v", statErr)
}
config, readErr := os.ReadFile(configPath)
if readErr != nil || string(config) != "TLS 0\n" {
t.Fatalf("FTP config changed after rejection: %q, %v", config, readErr)
}
}
func TestApplyFTPTLSPolicyNormalizesTLSAndRestartsDaemon(t *testing.T) {
root := t.TempDir()
certRoot := filepath.Join(root, "cert")
domain := "ftp.example.com"
certDir := filepath.Join(certRoot, domain)
if err := os.MkdirAll(certDir, 0700); err != nil {
t.Fatal(err)
}
certificate, privateKey := ftpTestCertificatePair(t, domain)
if err := os.WriteFile(filepath.Join(certDir, "fullchain.pem"), certificate, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(certDir, "privkey.pem"), privateKey, 0600); err != nil {
t.Fatal(err)
}
configPath := filepath.Join(root, "pure-ftpd.conf")
if err := os.WriteFile(configPath, []byte("NoAnonymous yes\r\nTLS 1\r\nTLS 0\n"), 0600); err != nil {
t.Fatal(err)
}
commands := make([]string, 0, 1)
agent := Agent{
CertificateRoot: certRoot, PureFTPConfig: configPath, PureFTPPem: filepath.Join(root, "pure-ftpd.pem"),
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
},
}
policy, err := agent.applyFTPTLSPolicy(context.Background(), domain)
if err != nil || policy != "explicit_tls_required" {
t.Fatalf("policy = %q, error = %v", policy, err)
}
config, err := os.ReadFile(configPath)
if err != nil {
t.Fatal(err)
}
matches := pureFTPTLSLine.FindAll(config, -1)
if strings.Count(string(config), "TLS 2") != 1 || len(matches) != 1 {
t.Fatalf("TLS directives were not normalized: %q", config)
}
wantedCertFile := "CertFile " + filepath.Join(root, "pure-ftpd.pem")
if strings.Count(string(config), wantedCertFile) != 1 || len(pureFTPCertFileLine.FindAll(config, -1)) != 1 {
t.Fatalf("certificate file directive was not normalized: %q", config)
}
if len(commands) != 2 || commands[0] != "systemctl stop pure-ftpd.service" || commands[1] != "systemctl start pure-ftpd.service" {
t.Fatalf("Pure-FTPd was not fully restarted: %#v", commands)
}
}
func ftpTestCertificatePair(t *testing.T, domain string) ([]byte, []byte) {
t.Helper()
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: domain}, DNSNames: []string{domain},
NotBefore: now.Add(-time.Hour), NotAfter: now.Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, publicKey, privateKey)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
}
+59
View File
@@ -0,0 +1,59 @@
package isolation
import (
"errors"
"path/filepath"
"strconv"
"strings"
"time"
)
// Pure-FTPd's documented stats format:
// epoch session username ip U|D bytes duration filename (last field unquoted).
func parseFTPStats(line, username, month string, location *time.Location) (uint64, bool) {
fields := strings.Fields(line)
if len(fields) < 8 || fields[2] != username || (fields[4] != "U" && fields[4] != "D") {
return 0, false
}
epoch, err := strconv.ParseInt(fields[0], 10, 64)
if err != nil || epoch <= 0 || time.Unix(epoch, 0).In(location).Format("2006-01") != month {
return 0, false
}
bytes, err := strconv.ParseUint(fields[5], 10, 64)
return bytes, err == nil
}
func (a Agent) measureFTPBandwidth(username string, now time.Time) (uint64, error) {
if !managedWebHostPattern.MatchString(username) {
return 0, errors.New("invalid FTP usage identity")
}
trafficStateMu.Lock()
defer trafficStateMu.Unlock()
statePath := a.UsageStatePath
if statePath == "" {
statePath = "/var/lib/sea-vhost-agent/traffic.json"
}
if !filepath.IsAbs(statePath) {
return 0, errors.New("invalid traffic state path")
}
state, err := loadTrafficState(statePath)
if err != nil {
return 0, err
}
key := "ftp:" + username
cursor := state.Domains[key]
month := now.Format("2006-01")
if cursor.Month != month {
cursor.Month = month
cursor.Bytes = 0
}
cursor, err = measureTransferLog(a.ftpTransferLogPath(), cursor, month, func(line string) (uint64, bool) { return parseFTPStats(line, username, month, now.Location()) })
if err != nil {
return 0, err
}
state.Domains[key] = cursor
if err = saveTrafficState(statePath, state); err != nil {
return 0, err
}
return cursor.Bytes, nil
}
@@ -0,0 +1,52 @@
package isolation
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
)
func TestFTPMeterCountsBothDirectionsWithRotationAndPartialLines(t *testing.T) {
dir := t.TempDir()
log := filepath.Join(dir, "ftp.log")
now := time.Date(2026, 10, 25, 10, 0, 0, 0, time.UTC)
agent := Agent{UsageStatePath: filepath.Join(dir, "traffic.json"), FTPLogPath: log}
line := func(name, direction string, size int) string {
return fmt.Sprintf("%d session %s 127.0.0.1 %s %d 0.5 file with spaces.txt\n", now.Unix(), name, direction, size)
}
partial := line("sv0123456789", "D", 17)
data := line("sv0123456789", "U", 101) + line("sv0123456789", "D", 202) + line("sv9876543210", "D", 999) + partial[:len(partial)-1]
if err := os.WriteFile(log, []byte(data), 0600); err != nil {
t.Fatal(err)
}
check := func(want uint64) {
t.Helper()
got, err := agent.measureFTPBandwidth("sv0123456789", now)
if err != nil || got != want {
t.Fatalf("bytes=%d want=%d error=%v", got, want, err)
}
}
check(303)
check(303)
file, err := os.OpenFile(log, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
t.Fatal(err)
}
_, _ = file.WriteString("\n")
file.Close()
check(320)
if err = os.Rename(log, log+".1"); err != nil {
t.Fatal(err)
}
if err = os.WriteFile(log, []byte(line("sv0123456789", "U", 23)), 0600); err != nil {
t.Fatal(err)
}
check(343)
next := now.AddDate(0, 1, 0)
got, err := agent.measureFTPBandwidth("sv0123456789", next)
if err != nil || got != 0 {
t.Fatalf("month reset=%d error=%v", got, err)
}
}
+169
View File
@@ -0,0 +1,169 @@
package isolation
import "context"
type ProjectSpec struct {
TenantID uint64 `json:"tenantId"`
HostName string `json:"hostName"`
RunPath string `json:"runPath"`
StorageBytes uint64 `json:"storageBytes"`
ProcessLimit uint32 `json:"processLimit"`
Databases []string `json:"databases,omitempty"`
}
type DatabaseAccessSpec struct {
Project ProjectSpec `json:"project"`
Database string `json:"database"`
ReadOnly bool `json:"readOnly"`
BlockCleanup bool `json:"blockCleanup,omitempty"`
}
type TrafficLimitSpec struct {
Project ProjectSpec `json:"project"`
Domains []string `json:"domains"`
Mbps uint32 `json:"mbps"`
}
type Prepared struct {
RootPath string `json:"rootPath"`
RunUser string `json:"runUser"`
}
type FTPIdentitySpec struct {
Project ProjectSpec `json:"project"`
Username string `json:"username"`
}
type PHPIdentitySpec struct {
Project ProjectSpec `json:"project"`
SiteName string `json:"siteName"`
Domain string `json:"domain"`
Version string `json:"version"`
ProcessLimit uint32 `json:"processLimit"`
}
type WebProtectionSpec struct {
Project ProjectSpec `json:"project"`
Domain string `json:"domain"`
}
type ExecutableSpec struct {
Project ProjectSpec `json:"project"`
RelativePath string `json:"relativePath"`
}
type PanelRuntimeSpec struct {
Project ProjectSpec `json:"project"`
Runtime string `json:"runtime"`
Version string `json:"version,omitempty"`
ProjectName string `json:"projectName,omitempty"`
}
type PythonRuntimeInstallSpec struct {
Version string `json:"version"`
}
type RuntimeProcessSpec struct {
Project ProjectSpec `json:"project"`
}
type ResourceUsageSpec struct {
Project ProjectSpec `json:"project"`
Domains []string `json:"domains"`
}
type ResourceUsage struct {
MemoryBytes uint64 `json:"memoryBytes"`
CPUTicks uint64 `json:"cpuTicks"`
StorageBytes uint64 `json:"storageBytes"`
BandwidthBytes uint64 `json:"bandwidthBytes"`
ProcessCount uint32 `json:"processCount"`
}
type NginxNetworkSpec struct {
Project ProjectSpec `json:"project"`
Domain string `json:"domain"`
IPAddress string `json:"ipAddress"`
Dedicated bool `json:"dedicated"`
HTTPPort int `json:"httpPort"`
HTTPSPort int `json:"httpsPort"`
}
type ProjectBackup struct {
TenantID uint64 `json:"tenantId"`
HostName string `json:"hostName"`
ArchivePath string `json:"archivePath,omitempty"`
SizeBytes uint64 `json:"sizeBytes,omitempty"`
DatabaseCount int `json:"databaseCount"`
}
type LegacyImportSpec struct {
Project ProjectSpec `json:"project"`
SourcePath string `json:"sourcePath"`
}
type Interface interface {
Prepare(context.Context, ProjectSpec) (Prepared, error)
Quarantine(context.Context, ProjectSpec) error
ApplyWebProtection(context.Context, WebProtectionSpec) error
RemoveWebProtection(context.Context, WebProtectionSpec) error
PrepareExecutable(context.Context, ExecutableSpec) error
PreparePanelRuntime(context.Context, PanelRuntimeSpec) error
InstallPythonRuntime(context.Context, string) error
TerminateRuntime(context.Context, RuntimeProcessSpec) error
ReleaseRunPath(context.Context, ProjectSpec) error
PrepareTrash(context.Context, ProjectSpec) error
ConfigureFTPIdentity(context.Context, FTPIdentitySpec) error
ConfigurePHPIdentity(context.Context, PHPIdentitySpec) error
SetPHPIdentityState(context.Context, PHPIdentitySpec, bool) error
RemovePHPIdentity(context.Context, PHPIdentitySpec) error
ResourceUsage(context.Context, ResourceUsageSpec) (ResourceUsage, error)
TerminateProcesses(context.Context, ProjectSpec) error
FreezeWrites(context.Context, ProjectSpec) error
ConfigureDatabaseAccess(context.Context, DatabaseAccessSpec) error
ConfigureTrafficLimits(context.Context, TrafficLimitSpec) error
ConfigureFTPTLS(context.Context, string) (string, error)
ConfigureNginxNetwork(context.Context, NginxNetworkSpec) error
CreateProjectBackup(context.Context, ProjectSpec) (ProjectBackup, error)
DeleteProjectBackup(context.Context, ProjectBackup) error
VerifyProjectBackup(context.Context, ProjectBackup) error
PurgeProject(context.Context, ProjectSpec) error
ImportLegacyProject(context.Context, LegacyImportSpec) error
}
type Mock struct{ Root string }
func (m Mock) Prepare(_ context.Context, spec ProjectSpec) (Prepared, error) {
return Prepared{RootPath: m.Root + "/" + spec.HostName, RunUser: spec.HostName}, nil
}
func (Mock) Quarantine(context.Context, ProjectSpec) error { return nil }
func (Mock) ApplyWebProtection(context.Context, WebProtectionSpec) error { return nil }
func (Mock) RemoveWebProtection(context.Context, WebProtectionSpec) error { return nil }
func (Mock) PrepareExecutable(context.Context, ExecutableSpec) error { return nil }
func (Mock) PreparePanelRuntime(context.Context, PanelRuntimeSpec) error { return nil }
func (Mock) InstallPythonRuntime(context.Context, string) error { return nil }
func (Mock) TerminateRuntime(context.Context, RuntimeProcessSpec) error { return nil }
func (Mock) ReleaseRunPath(context.Context, ProjectSpec) error { return nil }
func (Mock) PrepareTrash(context.Context, ProjectSpec) error { return nil }
func (Mock) ConfigureFTPIdentity(context.Context, FTPIdentitySpec) error { return nil }
func (Mock) ConfigurePHPIdentity(context.Context, PHPIdentitySpec) error { return nil }
func (Mock) SetPHPIdentityState(context.Context, PHPIdentitySpec, bool) error { return nil }
func (Mock) RemovePHPIdentity(context.Context, PHPIdentitySpec) error { return nil }
func (Mock) ResourceUsage(context.Context, ResourceUsageSpec) (ResourceUsage, error) {
return ResourceUsage{}, nil
}
func (Mock) TerminateProcesses(context.Context, ProjectSpec) error { return nil }
func (Mock) FreezeWrites(context.Context, ProjectSpec) error { return nil }
func (Mock) ConfigureDatabaseAccess(context.Context, DatabaseAccessSpec) error { return nil }
func (Mock) ConfigureTrafficLimits(context.Context, TrafficLimitSpec) error { return nil }
func (Mock) ConfigureFTPTLS(context.Context, string) (string, error) {
return "plain_allowed_no_certificate", nil
}
func (Mock) ConfigureNginxNetwork(context.Context, NginxNetworkSpec) error { return nil }
func (Mock) CreateProjectBackup(_ context.Context, spec ProjectSpec) (ProjectBackup, error) {
return ProjectBackup{TenantID: spec.TenantID, HostName: spec.HostName, ArchivePath: "/tmp/sea-vhost-backup.full.tar.gz", DatabaseCount: len(spec.Databases)}, nil
}
func (Mock) DeleteProjectBackup(context.Context, ProjectBackup) error { return nil }
func (Mock) VerifyProjectBackup(context.Context, ProjectBackup) error { return nil }
func (Mock) PurgeProject(context.Context, ProjectSpec) error { return nil }
func (Mock) ImportLegacyProject(context.Context, LegacyImportSpec) error { return nil }
+148
View File
@@ -0,0 +1,148 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
)
func (a Agent) importLegacyProject(w http.ResponseWriter, r *http.Request) {
var input LegacyImportSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(input.Project.HostName) || input.Project.TenantID == 0 || !validProjectRunPath(input.Project.RunPath) {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
target, err := a.projectPath(input.Project)
if err != nil || requirePhysicalDirectory(target) != nil {
http.Error(w, "unsafe target directory", http.StatusPreconditionFailed)
return
}
legacyRoot := strings.TrimSpace(a.LegacyRoot)
if legacyRoot == "" {
legacyRoot = "/www/wwwroot"
}
legacyRoot = filepath.Clean(legacyRoot)
source := filepath.Clean(strings.TrimSpace(input.SourcePath))
managedRoot := filepath.Clean(a.Root)
if !filepath.IsAbs(source) || source == legacyRoot || !strings.HasPrefix(source+string(filepath.Separator), legacyRoot+string(filepath.Separator)) || strings.HasPrefix(source+string(filepath.Separator), managedRoot+string(filepath.Separator)) || requirePhysicalDirectory(source) != nil {
http.Error(w, "legacy source is outside import boundary", http.StatusBadRequest)
return
}
empty, err := importTargetEmpty(target, input.Project.RunPath)
if err != nil || !empty {
http.Error(w, "target directory is not empty", http.StatusConflict)
return
}
if err = copyLegacyTree(r.Context(), source, target); err != nil {
_ = removeImportedContents(target)
http.Error(w, "cannot import legacy project", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func importTargetEmpty(root, runPath string) (bool, error) {
// Prepare creates the selected run-directory chain before importing. Only
// those empty directories may pre-exist; never overwrite files or siblings.
runRoot := filepath.Clean(filepath.Join(root, strings.TrimPrefix(runPath, "/")))
empty := true
err := filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if current == root {
return nil
}
if !entry.IsDir() || (current != runRoot && !strings.HasPrefix(runRoot+string(filepath.Separator), current+string(filepath.Separator))) {
empty = false
return fs.SkipAll
}
return nil
})
return empty, err
}
func copyLegacyTree(ctx context.Context, source, target string) error {
sourceRoot, err := os.OpenRoot(source)
if err != nil {
return err
}
defer sourceRoot.Close()
return filepath.WalkDir(source, func(current string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
relative, err := filepath.Rel(source, current)
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return errors.New("legacy import escaped source")
}
if relative == "." {
return nil
}
destination := filepath.Join(target, relative)
info, err := entry.Info()
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 || !(info.IsDir() || info.Mode().IsRegular()) {
return errors.New("legacy project contains unsupported links or special files")
}
if info.IsDir() {
if err := os.Mkdir(destination, info.Mode().Perm()|0700); err != nil {
if !errors.Is(err, os.ErrExist) {
return err
}
return requirePhysicalDirectory(destination)
}
return nil
}
return copyLegacyFile(sourceRoot, relative, destination, info.Mode().Perm())
})
}
func copyLegacyFile(sourceRoot *os.Root, relative, target string, mode os.FileMode) error {
input, err := sourceRoot.Open(relative)
if err != nil {
return err
}
defer input.Close()
info, err := input.Stat()
if err != nil || !info.Mode().IsRegular() {
return errors.New("legacy source is not a regular file")
}
output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode|0600)
if err != nil {
return err
}
_, copyErr := io.Copy(output, input)
closeErr := output.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}
func removeImportedContents(root string) error {
entries, err := os.ReadDir(root)
if err != nil {
return err
}
var result error
for _, entry := range entries {
result = errors.Join(result, os.RemoveAll(filepath.Join(root, entry.Name())))
}
return result
}
@@ -0,0 +1,59 @@
package isolation
import (
"context"
"os"
"path/filepath"
"testing"
)
func TestLegacyImportAcceptsOnlyPreparedEmptyRunDirectories(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "apps", "public"), 0750); err != nil {
t.Fatal(err)
}
if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || !empty {
t.Fatalf("prepared directory refused: %v", err)
}
file := filepath.Join(root, "apps", "public", "existing.txt")
if err := os.WriteFile(file, []byte("do not overwrite"), 0600); err != nil {
t.Fatal(err)
}
if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || empty {
t.Fatal("nonempty directory accepted")
}
if err := os.Remove(file); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(root, "unrelated"), 0750); err != nil {
t.Fatal(err)
}
if empty, err := importTargetEmpty(root, "/apps/public"); err != nil || empty {
t.Fatal("unrelated directory accepted")
}
}
func TestLegacyCopyPreservesSourceAndPreparedDirectories(t *testing.T) {
source, target := t.TempDir(), t.TempDir()
for _, root := range []string{source, target} {
if err := os.Mkdir(filepath.Join(root, "public"), 0750); err != nil {
t.Fatal(err)
}
}
original := filepath.Join(source, "public", "index.php")
if err := os.WriteFile(original, []byte("source marker"), 0600); err != nil {
t.Fatal(err)
}
if err := copyLegacyTree(context.Background(), source, target); err != nil {
t.Fatal(err)
}
for _, name := range []string{original, filepath.Join(target, "public", "index.php")} {
data, err := os.ReadFile(name)
if err != nil || string(data) != "source marker" {
t.Fatalf("copy changed data: %v", err)
}
}
if err := copyLegacyTree(context.Background(), source, target); err == nil {
t.Fatal("existing file overwritten")
}
}
+347
View File
@@ -0,0 +1,347 @@
package isolation
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
func (a Agent) backupDirectory(tenantID uint64) (string, error) {
root := strings.TrimSpace(a.BackupRoot)
if root == "" {
root = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(root) || tenantID == 0 {
return "", errors.New("invalid backup root")
}
return filepath.Join(filepath.Clean(root), strconv.FormatUint(tenantID, 10)), nil
}
func (a Agent) createProjectBackup(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
if len(spec.Databases) > 1 || (len(spec.Databases) == 1 && (spec.Databases[0] != spec.HostName || !managedWebHostPattern.MatchString(spec.HostName))) {
http.Error(w, "invalid backup database ownership", 400)
return
}
backupDir, err := a.backupDirectory(spec.TenantID)
if err != nil || os.MkdirAll(backupDir, 0700) != nil || os.Chmod(backupDir, 0700) != nil {
http.Error(w, "cannot prepare backup directory", http.StatusInternalServerError)
return
}
stamp := time.Now().UTC().Format("20060102T150405.000000000Z")
finalPath := filepath.Join(backupDir, spec.HostName+"-"+stamp+".tar.gz")
temporary, err := os.CreateTemp(backupDir, "."+spec.HostName+"-*.tmp")
if err != nil {
http.Error(w, "cannot create backup", http.StatusInternalServerError)
return
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
_ = temporary.Chmod(0600)
var dumps []backupDatabaseFile
for _, name := range spec.Databases {
dump, dumpErr := a.dumpDatabase(r.Context(), backupDir, name)
if dumpErr != nil {
temporary.Close()
http.Error(w, "cannot archive customer database", 500)
return
}
defer os.Remove(dump.path)
dumps = append(dumps, dump)
}
err = writeTarGzipDatabase(r.Context(), temporary, projectRoot, spec.HostName, dumps)
if err == nil {
err = temporary.Sync()
}
closeErr := temporary.Close()
if err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(temporaryPath, finalPath)
}
if err == nil && runtime.GOOS != "windows" {
directory, openErr := os.Open(backupDir)
if openErr != nil {
err = openErr
} else {
err = directory.Sync()
directory.Close()
}
}
if err != nil {
http.Error(w, "cannot archive project", http.StatusInternalServerError)
return
}
info, err := os.Stat(finalPath)
if err != nil {
http.Error(w, "cannot inspect backup", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(ProjectBackup{TenantID: spec.TenantID, HostName: spec.HostName, ArchivePath: finalPath, SizeBytes: uint64(info.Size()), DatabaseCount: len(dumps)})
}
func writeTarGzip(ctx context.Context, output io.Writer, root, hostName string) error {
return writeTarGzipDatabase(ctx, output, root, hostName, nil)
}
type backupDatabaseFile struct {
name, path string
size int64
digest string
}
func (a Agent) dumpDatabase(ctx context.Context, directory, name string) (backupDatabaseFile, error) {
if !managedWebHostPattern.MatchString(name) {
return backupDatabaseFile{}, errors.New("invalid managed database name")
}
cfg, err := a.mysqlConfig(ctx)
if err != nil {
return backupDatabaseFile{}, err
}
options, err := os.CreateTemp(directory, ".mysql-options-*")
if err != nil {
return backupDatabaseFile{}, err
}
defer os.Remove(options.Name())
_ = options.Chmod(0600)
if cfg.Net == "unix" {
_, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nsocket=%s\nprotocol=SOCKET\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), mysqlOptionValue(cfg.Addr))
} else {
_, err = fmt.Fprintf(options, "[client]\nuser=%s\npassword=%s\nhost=127.0.0.1\nport=%s\nprotocol=TCP\n", mysqlOptionValue(cfg.User), mysqlOptionValue(cfg.Passwd), strings.TrimPrefix(cfg.Addr, "127.0.0.1:"))
}
closeErr := options.Close()
if err == nil {
err = closeErr
}
if err != nil {
return backupDatabaseFile{}, err
}
file, err := os.CreateTemp(directory, ".database-*.sql")
if err != nil {
return backupDatabaseFile{}, err
}
_ = file.Chmod(0600)
cleanup := func() { file.Close(); os.Remove(file.Name()) }
command := exec.CommandContext(ctx, "/www/server/mysql/bin/mysqldump", "--defaults-extra-file="+options.Name(), "--single-transaction", "--quick", "--routines", "--events", "--triggers", "--hex-blob", "--no-tablespaces", "--set-gtid-purged=OFF", "--databases", name)
hash := sha256.New()
command.Stdout = io.MultiWriter(file, hash)
if command.Run() != nil {
cleanup()
return backupDatabaseFile{}, errors.New("customer database dump failed")
}
info, err := file.Stat()
if err != nil || info.Size() == 0 {
cleanup()
return backupDatabaseFile{}, errors.New("empty customer database dump")
}
if err = file.Close(); err != nil {
os.Remove(file.Name())
return backupDatabaseFile{}, err
}
return backupDatabaseFile{name: name, path: file.Name(), size: info.Size(), digest: fmt.Sprintf("%x", hash.Sum(nil))}, nil
}
func writeTarGzipDatabase(ctx context.Context, output io.Writer, root, hostName string, dumps []backupDatabaseFile) error {
archiveRoot, openErr := os.OpenRoot(root)
if openErr != nil {
return openErr
}
defer archiveRoot.Close()
gzipWriter := gzip.NewWriter(output)
tarWriter := tar.NewWriter(gzipWriter)
err := filepath.WalkDir(root, func(current string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
info, err := entry.Info()
if err != nil {
return err
}
if !(info.Mode().IsRegular() || info.IsDir() || info.Mode()&os.ModeSymlink != 0) {
return nil
}
relative, err := filepath.Rel(root, current)
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return errors.New("backup path escaped project root")
}
link := ""
if info.Mode()&os.ModeSymlink != 0 {
link, err = os.Readlink(current)
if err != nil {
return err
}
}
header, err := tar.FileInfoHeader(info, link)
if err != nil {
return err
}
header.Name = filepath.ToSlash(filepath.Join(hostName, relative))
if err = tarWriter.WriteHeader(header); err != nil || !info.Mode().IsRegular() {
return err
}
file, err := archiveRoot.Open(relative)
if err != nil {
return err
}
_, copyErr := io.Copy(tarWriter, file)
closeErr := file.Close()
if copyErr != nil {
return copyErr
}
return closeErr
})
manifest := map[string]any{"format": 2, "hostName": hostName, "createdAt": time.Now().UTC(), "databases": []map[string]any{}}
entries := []map[string]any{}
for _, dump := range dumps {
if err != nil {
break
}
if ctx.Err() != nil {
err = ctx.Err()
break
}
name := ".sea-vhost-backup/databases/" + dump.name + ".sql"
if err = tarWriter.WriteHeader(&tar.Header{Name: name, Mode: 0600, Size: dump.size, ModTime: time.Now().UTC()}); err != nil {
break
}
file, openErr := os.Open(dump.path)
if openErr != nil {
err = openErr
break
}
_, err = io.Copy(tarWriter, file)
closeErr := file.Close()
if err == nil {
err = closeErr
}
entries = append(entries, map[string]any{"name": dump.name, "path": name, "bytes": dump.size, "sha256": dump.digest})
}
manifest["databases"] = entries
if err == nil {
data, marshalErr := json.Marshal(manifest)
if marshalErr != nil {
err = marshalErr
} else {
err = tarWriter.WriteHeader(&tar.Header{Name: ".sea-vhost-backup/manifest.json", Mode: 0600, Size: int64(len(data)), ModTime: time.Now().UTC()})
if err == nil {
_, err = tarWriter.Write(data)
}
}
}
if closeErr := tarWriter.Close(); err == nil {
err = closeErr
}
if closeErr := gzipWriter.Close(); err == nil {
err = closeErr
}
return err
}
func (a Agent) deleteProjectBackup(w http.ResponseWriter, r *http.Request) {
var backup ProjectBackup
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&backup) != nil || !safeName.MatchString(backup.HostName) || backup.TenantID == 0 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
directory, err := a.backupDirectory(backup.TenantID)
cleaned := filepath.Clean(backup.ArchivePath)
if err != nil || filepath.Dir(cleaned) != directory || !strings.HasPrefix(filepath.Base(cleaned), backup.HostName+"-") || !strings.HasSuffix(cleaned, ".tar.gz") {
http.Error(w, "unsafe backup path", http.StatusBadRequest)
return
}
info, err := os.Lstat(cleaned)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe backup file", http.StatusPreconditionFailed)
return
}
if err = os.Remove(cleaned); err != nil {
http.Error(w, "cannot delete backup", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) purgeProject(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
physicalErr := requirePhysicalDirectory(projectRoot)
if physicalErr == nil {
files, findErr := findProjectUserINIFiles(projectRoot, 512)
if findErr != nil {
http.Error(w, "unsafe PHP isolation file", http.StatusPreconditionFailed)
return
}
for _, file := range files {
if err = a.removeUserINI(r.Context(), file); err != nil {
http.Error(w, "cannot release PHP isolation file", http.StatusInternalServerError)
return
}
}
if err = os.RemoveAll(projectRoot); err != nil {
http.Error(w, "cannot purge project", http.StatusInternalServerError)
return
}
} else if !errors.Is(physicalErr, os.ErrNotExist) {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
// Probe identities first so retries are idempotent without depending on
// distribution-specific userdel/groupdel error text.
if a.command(ctx, "id", "-u", spec.HostName) == nil {
if err = a.command(ctx, "userdel", spec.HostName); err != nil {
http.Error(w, "cannot remove project identity", http.StatusInternalServerError)
return
}
}
if a.command(ctx, "getent", "group", spec.HostName) == nil {
if err = a.command(ctx, "groupdel", spec.HostName); err != nil {
http.Error(w, "cannot remove project group", http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
}
+112
View File
@@ -0,0 +1,112 @@
package isolation
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
var nginxListenLine = regexp.MustCompile(`(?m)^(\s*)listen\s+(?:\[[0-9A-Fa-f:]+\]|[0-9.]+)?(?::)?([0-9]{1,5})([^;]*);\s*$`)
func (a Agent) configureNginxNetwork(w http.ResponseWriter, r *http.Request) {
var spec NginxNetworkSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!managedWebHostPattern.MatchString(spec.Project.HostName) || !webDomainPattern.MatchString(spec.Domain) ||
spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 ||
spec.HTTPPort < 1 || spec.HTTPPort > 65535 || spec.HTTPSPort < 1 || spec.HTTPSPort > 65535 || spec.HTTPPort == spec.HTTPSPort {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
if spec.Dedicated && net.ParseIP(spec.IPAddress) == nil {
http.Error(w, "invalid dedicated ip", http.StatusBadRequest)
return
}
if !spec.Dedicated && strings.TrimSpace(spec.IPAddress) != "" {
http.Error(w, "shared mode cannot bind an ip", http.StatusBadRequest)
return
}
vhostRoot, err := filepath.Abs(a.NginxVhostRoot)
if err != nil || !filepath.IsAbs(vhostRoot) || requirePhysicalDirectory(vhostRoot) != nil {
http.Error(w, "nginx vhost root is unavailable", http.StatusPreconditionFailed)
return
}
configPath := filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf")
info, err := os.Lstat(configPath)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 2<<20 {
http.Error(w, "unsafe nginx site configuration", http.StatusPreconditionFailed)
return
}
content, err := os.ReadFile(configPath)
if err != nil {
http.Error(w, "cannot read nginx site configuration", http.StatusInternalServerError)
return
}
matched := 0
updated := nginxListenLine.ReplaceAllStringFunc(string(content), func(line string) string {
parts := nginxListenLine.FindStringSubmatch(line)
if len(parts) != 4 {
return line
}
port, parseErr := strconv.Atoi(parts[2])
if parseErr != nil {
return line
}
suffix := parts[3]
isTLS := strings.Contains(strings.ToLower(suffix), "ssl") || port == 443
wanted := spec.HTTPPort
if isTLS {
wanted = spec.HTTPSPort
}
address := ""
if spec.Dedicated {
address = spec.IPAddress
if strings.Contains(address, ":") {
address = "[" + address + "]"
}
address += ":"
}
matched++
return parts[1] + "listen " + address + strconv.Itoa(wanted) + suffix + ";"
})
if matched == 0 {
http.Error(w, "nginx listen directives were not found", http.StatusPreconditionFailed)
return
}
if updated == string(content) {
w.WriteHeader(http.StatusOK)
return
}
restore, err := writeManagedFile(configPath, []byte(updated))
if err != nil {
http.Error(w, "cannot write nginx site configuration", http.StatusInternalServerError)
return
}
ctx, cancel := contextWithNetworkTimeout(r)
defer cancel()
rollback := func() { _ = restore(); _ = a.runNginx(ctx, "-t"); _ = a.runNginx(ctx, "-s", "reload") }
if err = a.runNginx(ctx, "-t"); err != nil {
rollback()
http.Error(w, "nginx rejected network configuration", http.StatusPreconditionFailed)
return
}
if err = a.runNginx(ctx, "-s", "reload"); err != nil {
rollback()
http.Error(w, "cannot reload nginx", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func contextWithNetworkTimeout(r *http.Request) (context.Context, context.CancelFunc) {
return context.WithTimeout(r.Context(), 20*time.Second)
}
@@ -0,0 +1,40 @@
package isolation
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestRepeatedCustomNetworkPortIsIdempotent(t *testing.T) {
root := t.TempDir()
domain := "sv0123456789.hosts.example.test"
file := filepath.Join(root, domain+".conf")
if err := os.WriteFile(file, []byte("server {\n listen 80;\n server_name "+domain+";\n}\n"), 0600); err != nil {
t.Fatal(err)
}
commands := 0
a := Agent{NginxVhostRoot: root, NginxBinary: filepath.Join(root, "nginx"), runCommand: func(context.Context, string, ...string) error { commands++; return nil }}
spec := NginxNetworkSpec{Project: ProjectSpec{TenantID: 1, HostName: "sv0123456789", StorageBytes: 1, ProcessLimit: 1}, Domain: domain, HTTPPort: 18080, HTTPSPort: 18443}
data, _ := json.Marshal(spec)
for i := 0; i < 2; i++ {
response := httptest.NewRecorder()
a.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/nginx/network", bytes.NewReader(data)))
if response.Code != http.StatusOK {
t.Fatalf("request %d: %d %s", i, response.Code, response.Body.String())
}
}
if commands != 2 {
t.Fatalf("repeated request unnecessarily reloaded Nginx: %d", commands)
}
content, err := os.ReadFile(file)
if err != nil || !strings.Contains(string(content), "listen 18080;") {
t.Fatal("custom port was not retained")
}
}
+249
View File
@@ -0,0 +1,249 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
)
const defaultNodePIDRoot = "/www/server/nodejs/vhost/pids"
var (
pythonManagerVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
panelProjectNamePattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`)
)
// preparePanelRuntime applies only the narrowly-scoped host-side state that
// aaPanel's free language modules require. Project creation and lifecycle stay
// behind the panel broker; this endpoint never grants a tenant access to the
// panel installation as a whole.
func (a Agent) preparePanelRuntime(w http.ResponseWriter, r *http.Request) {
var input PanelRuntimeSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) ||
input.Project.TenantID == 0 || input.Project.TenantID > 9_999_999_999 ||
input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 || input.Project.ProcessLimit > 100_000 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(input.Project)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "unsafe project directory", http.StatusPreconditionFailed)
return
}
uid, err := a.hostUID(input.Project.HostName)
if err != nil {
http.Error(w, "isolated project identity is unavailable", http.StatusPreconditionFailed)
return
}
switch input.Runtime {
case "Node.js":
if err = a.prepareNodePIDAccess(r.Context(), input.Project.HostName); err != nil {
http.Error(w, "cannot prepare isolated Node.js PID access", http.StatusPreconditionFailed)
return
}
case "Python":
// aaPanel's current Python manager lists only root and identities from
// the normal UID range. Detect legacy Sea vHost system UIDs before the
// panel can create an untracked partial project.
if uid < 1000 {
http.Error(w, "legacy host UID is incompatible with the aaPanel Python project manager", http.StatusPreconditionFailed)
return
}
if !pythonManagerVersionPattern.MatchString(input.Version) || !panelProjectNamePattern.MatchString(input.ProjectName) {
http.Error(w, "invalid Python runtime specification", http.StatusBadRequest)
return
}
if err = a.preparePythonVirtualEnvironment(r.Context(), projectRoot, input); err != nil {
http.Error(w, "cannot prepare isolated Python environment", http.StatusPreconditionFailed)
return
}
default:
http.Error(w, "unsupported panel runtime", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) preparePythonVirtualEnvironment(ctx context.Context, projectRoot string, input PanelRuntimeSpec) error {
managerRoot := a.PythonManagerRoot
if managerRoot == "" {
managerRoot = "/www/server/python_manager/versions"
}
baseRoot := filepath.Join(managerRoot, input.Version)
resolvedBase, err := filepath.EvalSymlinks(baseRoot)
if err != nil || filepath.Clean(resolvedBase) != filepath.Clean(baseRoot) {
return errors.New("Python manager version path is unavailable")
}
if err = a.repairManagedPythonAccess(ctx, baseRoot, input.Version); err != nil {
return err
}
basePython := filepath.Join(baseRoot, "bin", "python3")
resolvedPython, err := filepath.EvalSymlinks(basePython)
if err != nil || !strings.HasPrefix(filepath.Clean(resolvedPython)+string(os.PathSeparator), filepath.Clean(baseRoot)+string(os.PathSeparator)) {
return errors.New("Python manager interpreter escaped its version directory")
}
info, err := os.Stat(resolvedPython)
if err != nil || !runtimeExecutable(info) {
return errors.New("Python manager interpreter is not executable")
}
runtimeRelative := filepath.ToSlash(filepath.Join(strings.TrimPrefix(input.Project.RunPath, "/"), ".sea-runtime", "python"))
if !strings.HasPrefix(runtimeRelative, "/") {
runtimeRelative = "/" + runtimeRelative
}
if err = ensureProjectRunDirectory(projectRoot, runtimeRelative); err != nil {
return err
}
runtimeParent, err := physicalRunDirectory(projectRoot, runtimeRelative)
if err != nil {
return err
}
runtimeRoot := filepath.Dir(runtimeParent)
if err = requirePhysicalDirectory(runtimeRoot); err != nil {
return err
}
fileOwner := a.FileOwner
if fileOwner == "" {
fileOwner = "sea-vhost"
}
if err = a.command(ctx, "chown", fileOwner+":"+input.Project.HostName, runtimeRoot, runtimeParent); err != nil {
return err
}
if err = a.command(ctx, "chmod", "2770", runtimeRoot, runtimeParent); err != nil {
return err
}
venvPath := filepath.Join(runtimeParent, input.ProjectName+"-"+input.Version)
if venvInfo, statErr := os.Lstat(venvPath); statErr == nil {
if !venvInfo.IsDir() || venvInfo.Mode()&os.ModeSymlink != 0 {
return errors.New("Python virtual environment path is unsafe")
}
venvPython := filepath.Join(venvPath, "bin", "python3")
if existing, existingErr := os.Stat(venvPython); existingErr == nil && runtimeExecutable(existing) {
return a.securePythonRuntimeACL(ctx, runtimeRoot)
}
return errors.New("Python virtual environment is incomplete")
} else if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
if err = a.command(ctx, "runuser", "-u", input.Project.HostName, "--", basePython, "-m", "venv", "--system-site-packages", venvPath); err != nil {
return err
}
venvInfo, err := os.Lstat(venvPath)
if err != nil || !venvInfo.IsDir() || venvInfo.Mode()&os.ModeSymlink != 0 {
return errors.New("Python virtual environment was not created safely")
}
venvPython, err := os.Stat(filepath.Join(venvPath, "bin", "python3"))
if err != nil || !runtimeExecutable(venvPython) {
return errors.New("Python virtual environment interpreter is unavailable")
}
return a.securePythonRuntimeACL(ctx, runtimeRoot)
}
// The agent's restrictive umask must not make shared standard libraries or
// pip metadata unreadable to isolated UIDs. Only the fixed interpreter tree
// is normalized; tenant venvs keep their private ACLs.
func (a Agent) normalizeSharedPythonAccess(ctx context.Context, root string) error {
if requirePhysicalDirectory(root) != nil {
return errors.New("unsafe shared Python installation")
}
if err := a.command(ctx, "chown", "-hR", "root:root", root); err != nil {
return err
}
if err := a.command(ctx, "find", root, "-xdev", "-type", "d", "-exec", "chmod", "a+rx,go-w", "{}", "+"); err != nil {
return err
}
return a.command(ctx, "find", root, "-xdev", "-type", "f", "-exec", "chmod", "a+rX,go-w", "{}", "+")
}
func (a Agent) repairManagedPythonAccess(ctx context.Context, root, version string) error {
marker := filepath.Join(root, ".sea-vhost-runtime")
info, err := os.Lstat(marker)
if errors.Is(err, os.ErrNotExist) {
return nil
} // Do not rewrite administrator-managed installations.
if err != nil || !info.Mode().IsRegular() {
return errors.New("invalid managed Python marker")
}
data, err := os.ReadFile(marker)
if err != nil || strings.TrimSpace(string(data)) != version {
return errors.New("managed Python version marker mismatch")
}
return a.normalizeSharedPythonAccess(ctx, root)
}
func runtimeExecutable(info os.FileInfo) bool {
return info.Mode().IsRegular() && (runtime.GOOS == "windows" || info.Mode()&0111 != 0)
}
func (a Agent) securePythonRuntimeACL(ctx context.Context, runtimeRoot string) error {
// Do not pass venv symlinks to setfacl: Python intentionally links its
// executable back to the server-owned base interpreter, and setfacl follows
// those links. The private parent directory already prevents www from
// traversing the links; only real directories and files need explicit ACLs.
if err := a.command(ctx, "find", runtimeRoot, "-xdev", "(", "-type", "d", "-o", "-type", "f", ")", "-exec", "setfacl", "-m", "u:www:---", "{}", "+"); err != nil {
return err
}
return a.command(ctx, "find", runtimeRoot, "-xdev", "-type", "d", "-exec", "setfacl", "-m", "d:u:www:---", "{}", "+")
}
func (a Agent) hostUID(name string) (uint64, error) {
if a.lookupUID != nil {
return a.lookupUID(name)
}
account, err := user.Lookup(name)
if err != nil {
return 0, err
}
return strconv.ParseUint(account.Uid, 10, 64)
}
func (a Agent) nodePIDDirectory() (string, error) {
root := a.NodePIDRoot
if root == "" {
root = defaultNodePIDRoot
}
if !filepath.IsAbs(root) || root != filepath.Clean(root) {
return "", errors.New("invalid Node.js PID directory")
}
if err := requirePhysicalDirectory(root); err != nil {
return "", err
}
resolved, err := filepath.EvalSymlinks(root)
if err != nil || filepath.Clean(resolved) != root {
return "", errors.New("Node.js PID directory contains a symbolic link")
}
return root, nil
}
func (a Agent) prepareNodePIDAccess(ctx context.Context, hostName string) error {
root, err := a.nodePIDDirectory()
if err != nil {
return err
}
if err = a.command(ctx, "chmod", "+t", root); err != nil {
return err
}
return a.command(ctx, "setfacl", "-m", "u:"+hostName+":rwx,m::rwx", root)
}
func (a Agent) revokeNodePIDAccess(ctx context.Context, hostName string) error {
root, err := a.nodePIDDirectory()
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
return a.command(ctx, "setfacl", "-x", "u:"+hostName, root)
}
+483
View File
@@ -0,0 +1,483 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
var (
phpSiteNamePattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`)
phpVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]$`)
)
type phpIdentityPaths struct {
config, pid, socket, nginx string
}
func (a Agent) decodePHPIdentity(w http.ResponseWriter, r *http.Request) (PHPIdentitySpec, bool) {
var spec PHPIdentitySpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!safeName.MatchString(spec.Project.HostName) || !phpSiteNamePattern.MatchString(spec.SiteName) ||
!webDomainPattern.MatchString(spec.Domain) || !phpVersionPattern.MatchString(spec.Version) ||
!validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 ||
spec.Project.ProcessLimit == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 {
http.Error(w, "invalid request", http.StatusBadRequest)
return PHPIdentitySpec{}, false
}
return spec, true
}
func (a Agent) configurePHPIdentity(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodePHPIdentity(w, r)
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
paths, binary, projectRoot, err := a.phpIdentityEnvironment(spec)
if err != nil {
http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed)
return
}
tempRoot, err := a.preparePHPTempDirectory(ctx, projectRoot, spec.Project.HostName)
if err != nil {
http.Error(w, "cannot prepare isolated PHP temporary directory", http.StatusInternalServerError)
return
}
content := renderPHPIdentityConfig(spec, projectRoot, tempRoot, paths)
if err = writePrivateFile(paths.config, []byte(content)); err != nil {
http.Error(w, "cannot write PHP identity configuration", http.StatusInternalServerError)
return
}
if err = a.command(ctx, "chown", "root:"+spec.Project.HostName, paths.config); err != nil ||
a.command(ctx, "chmod", "0640", paths.config) != nil {
http.Error(w, "cannot secure PHP identity configuration", http.StatusInternalServerError)
return
}
// Validate as the tenant identity, not as root. PHP-FPM opens its configured
// error log even during `-t`; a root validation would leave a root-owned
// file in the tenant runtime directory and can also follow a tenant-created
// symlink with root privileges.
if err = testPHPAsIdentity(ctx, binary, paths.config, spec.Project.HostName); err != nil {
slog.Error("PHP-FPM rejected isolated pool configuration", "site", spec.SiteName, "error", err)
http.Error(w, "PHP-FPM rejected isolated pool configuration", http.StatusPreconditionFailed)
return
}
_ = a.stopPHPIdentityProcess(ctx, paths)
if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil {
slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err)
http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError)
return
}
nginxContent := []byte(renderPHPNginxAdapter(paths.socket))
restore, err := writeManagedFile(paths.nginx, nginxContent)
if err != nil {
_ = a.stopPHPIdentityProcess(ctx, paths)
http.Error(w, "cannot write isolated PHP adapter", http.StatusInternalServerError)
return
}
rollback := func() {
_ = restore()
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
_ = a.stopPHPIdentityProcess(ctx, paths)
}
if err = a.runNginx(ctx, "-t"); err != nil {
slog.Error("nginx rejected isolated PHP adapter", "site", spec.SiteName, "domain", spec.Domain, "error", err)
rollback()
http.Error(w, "Nginx rejected isolated PHP adapter", http.StatusPreconditionFailed)
return
}
if err = a.runNginx(ctx, "-s", "reload"); err != nil {
rollback()
http.Error(w, "cannot reload Nginx for isolated PHP pool", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) startPHPIdentity(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodePHPIdentity(w, r)
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
paths, binary, _, err := a.phpIdentityEnvironment(spec)
if err != nil {
http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed)
return
}
if _, err = os.Stat(paths.config); err != nil {
http.Error(w, "PHP identity has not been configured", http.StatusPreconditionFailed)
return
}
if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil {
slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err)
http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) stopPHPIdentity(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodePHPIdentity(w, r)
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
paths, _, _, err := a.phpIdentityEnvironment(spec)
if err != nil {
http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed)
return
}
if err = a.stopPHPIdentityProcess(ctx, paths); err != nil {
http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) removePHPIdentity(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodePHPIdentity(w, r)
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
paths, siteConfig, err := a.phpIdentityRemovalPaths(spec)
if err != nil {
http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed)
return
}
if err = a.stopPHPIdentityProcess(ctx, paths); err != nil {
http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError)
return
}
var oldNginx []byte
if oldNginx, err = os.ReadFile(paths.nginx); err != nil && !errors.Is(err, os.ErrNotExist) {
http.Error(w, "cannot read isolated PHP adapter", http.StatusInternalServerError)
return
}
if err == nil {
if err = os.Remove(paths.nginx); err != nil {
http.Error(w, "cannot remove isolated PHP adapter", http.StatusInternalServerError)
return
}
if _, statErr := os.Stat(siteConfig); statErr == nil {
if err = a.runNginx(ctx, "-t"); err != nil {
_, _ = writeManagedFile(paths.nginx, oldNginx)
http.Error(w, "Nginx rejected isolated PHP adapter removal", http.StatusPreconditionFailed)
return
}
if err = a.runNginx(ctx, "-s", "reload"); err != nil {
_, _ = writeManagedFile(paths.nginx, oldNginx)
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
http.Error(w, "cannot reload Nginx after PHP adapter removal", http.StatusInternalServerError)
return
}
}
}
for _, target := range []string{paths.config, paths.pid, paths.socket} {
if info, statErr := os.Lstat(target); statErr == nil {
if !info.Mode().IsRegular() && info.Mode()&os.ModeSocket == 0 {
http.Error(w, "unsafe PHP identity state", http.StatusPreconditionFailed)
return
}
_ = os.Remove(target)
}
}
_ = os.Remove(filepath.Dir(paths.pid))
w.WriteHeader(http.StatusOK)
}
func (a Agent) phpIdentityEnvironment(spec PHPIdentitySpec) (phpIdentityPaths, string, string, error) {
projectRoot, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
return phpIdentityPaths{}, "", "", errors.New("project root unavailable")
}
if _, err = physicalRunDirectory(projectRoot, spec.Project.RunPath); err != nil {
return phpIdentityPaths{}, "", "", err
}
stateRoot := strings.TrimSpace(a.PHPStateRoot)
if stateRoot == "" {
stateRoot = "/var/lib/sea-vhost-agent/php"
}
runRoot := strings.TrimSpace(a.PHPRunRoot)
if runRoot == "" {
runRoot = "/run/sea-vhost-php"
}
if !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) {
return phpIdentityPaths{}, "", "", errors.New("invalid PHP identity root")
}
if err = ensurePhysicalDirectory(stateRoot, 0700); err != nil {
return phpIdentityPaths{}, "", "", err
}
if err = os.Chmod(stateRoot, 0711); err != nil {
return phpIdentityPaths{}, "", "", err
}
if err = ensurePhysicalDirectory(runRoot, 0755); err != nil {
return phpIdentityPaths{}, "", "", err
}
version := strings.ReplaceAll(spec.Version, ".", "")
binary := filepath.Join("/www/server/php", version, "sbin/php-fpm")
info, err := os.Lstat(binary)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode()&0111 == 0 {
return phpIdentityPaths{}, "", "", errors.New("PHP-FPM binary unavailable")
}
webPaths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: spec.Domain})
if err != nil || verifySiteExtensionInclude(webPaths.siteConfig, webPaths.siteExtension) != nil {
return phpIdentityPaths{}, "", "", errors.New("managed Nginx site unavailable")
}
key := spec.SiteName
instanceRunRoot := filepath.Join(runRoot, key)
permissionCtx, cancelPermissions := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelPermissions()
if err = ensurePhysicalDirectory(instanceRunRoot, 0770); err != nil ||
a.command(permissionCtx, "chown", "root:"+spec.Project.HostName, instanceRunRoot) != nil ||
a.command(permissionCtx, "chmod", "0770", instanceRunRoot) != nil ||
a.command(permissionCtx, "setfacl", "-m", "u:www:--x,m::rwx,o::---", instanceRunRoot) != nil {
return phpIdentityPaths{}, "", "", errors.New("cannot prepare PHP identity runtime directory")
}
for _, legacyPath := range []string{filepath.Join(runRoot, key+".pid"), filepath.Join(runRoot, key+".sock")} {
if legacyInfo, legacyErr := os.Lstat(legacyPath); legacyErr == nil &&
(legacyInfo.Mode().IsRegular() || legacyInfo.Mode()&os.ModeSocket != 0) {
_ = os.Remove(legacyPath)
}
}
paths := phpIdentityPaths{
config: filepath.Join(stateRoot, key+".conf"),
pid: filepath.Join(instanceRunRoot, "php-fpm.pid"),
socket: filepath.Join(instanceRunRoot, "php-fpm.sock"),
nginx: filepath.Join(filepath.Dir(webPaths.siteExtension), "sea-vhost-php.conf"),
}
return paths, binary, projectRoot, nil
}
func (a Agent) phpIdentityRemovalPaths(spec PHPIdentitySpec) (phpIdentityPaths, string, error) {
stateRoot := strings.TrimSpace(a.PHPStateRoot)
if stateRoot == "" {
stateRoot = "/var/lib/sea-vhost-agent/php"
}
runRoot := strings.TrimSpace(a.PHPRunRoot)
if runRoot == "" {
runRoot = "/run/sea-vhost-php"
}
vhostRoot, err := filepath.Abs(a.NginxVhostRoot)
if err != nil || !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) || !filepath.IsAbs(vhostRoot) {
return phpIdentityPaths{}, "", errors.New("invalid PHP identity path")
}
for _, root := range []string{stateRoot, runRoot, vhostRoot} {
if err = requirePhysicalDirectory(root); err != nil {
return phpIdentityPaths{}, "", err
}
}
extensionRoot := filepath.Join(vhostRoot, "extension", strings.ToLower(spec.Domain))
if err = requirePhysicalDirectory(extensionRoot); err != nil && !errors.Is(err, os.ErrNotExist) {
return phpIdentityPaths{}, "", err
}
paths := phpIdentityPaths{
config: filepath.Join(stateRoot, spec.SiteName+".conf"),
pid: filepath.Join(runRoot, spec.SiteName, "php-fpm.pid"),
socket: filepath.Join(runRoot, spec.SiteName, "php-fpm.sock"),
nginx: filepath.Join(extensionRoot, "sea-vhost-php.conf"),
}
return paths, filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf"), nil
}
func (a Agent) preparePHPTempDirectory(ctx context.Context, projectRoot, hostName string) (string, error) {
if err := ensureProjectRunDirectory(projectRoot, "/.sea-runtime/php"); err != nil {
return "", err
}
tempRoot, err := physicalRunDirectory(projectRoot, "/.sea-runtime/php")
if err != nil {
return "", err
}
fileOwner := strings.TrimSpace(a.FileOwner)
if fileOwner == "" {
fileOwner = "sea-vhost"
}
if err = a.command(ctx, "chown", fileOwner+":"+hostName, tempRoot); err != nil {
return "", err
}
if err = a.command(ctx, "chmod", "0770", tempRoot); err != nil {
return "", err
}
if err = a.command(ctx, "setfacl", "-m", "u:www:---,m::rwx,o::---", tempRoot); err != nil {
return "", err
}
return filepath.ToSlash(tempRoot), nil
}
func renderPHPIdentityConfig(spec PHPIdentitySpec, projectRoot, tempRoot string, paths phpIdentityPaths) string {
children := int(spec.ProcessLimit)
if children > 50 {
children = 50
}
if children < 1 {
children = 1
}
return fmt.Sprintf(`[global]
pid = %s
error_log = %s
daemonize = yes
[%s]
user = %s
group = %s
listen = %s
listen.mode = 0660
pm = ondemand
pm.max_children = %d
pm.process_idle_timeout = 15s
pm.max_requests = 500
request_terminate_timeout = 120s
catch_workers_output = yes
clear_env = no
php_admin_value[pcre.jit] = 0
security.limit_extensions = .php
php_admin_value[open_basedir] = %s/
php_admin_value[sys_temp_dir] = %s
php_admin_value[upload_tmp_dir] = %s
php_admin_value[session.save_path] = %s
`, paths.pid, filepath.ToSlash(filepath.Join(tempRoot, "fpm-error.log")), spec.SiteName, spec.Project.HostName, spec.Project.HostName, paths.socket, children, projectRoot, tempRoot, tempRoot, tempRoot)
}
func renderPHPNginxAdapter(socket string) string {
return fmt.Sprintf(`# Managed by Sea vHost. Local changes will be replaced.
# aaPanel's shared PHP include declares its own regex location later in the
# server block. This equivalent, deliberately distinct expression is loaded
# first from the site's extension directory and therefore selects the private
# per-host socket without creating a duplicate Nginx location.
location ~ ^.+\.php(?:/|$)
{
try_files $uri =404;
fastcgi_pass unix:%s;
fastcgi_index index.php;
include fastcgi.conf;
include pathinfo.conf;
}
`, filepath.ToSlash(socket))
}
func (a Agent) startPHPIdentityProcess(ctx context.Context, binary string, paths phpIdentityPaths, identity string) error {
if a.phpIdentityRunning(ctx, paths) {
return nil
}
_ = os.Remove(paths.pid)
_ = os.Remove(paths.socket)
if err := startPHPAsIdentity(ctx, binary, paths.config, identity); err != nil {
return err
}
for attempt := 0; attempt < 40; attempt++ {
if a.phpIdentityRunning(ctx, paths) {
if info, err := os.Lstat(paths.socket); err == nil && info.Mode()&os.ModeSocket != 0 {
if err = a.command(ctx, "chown", identity+":www", paths.socket); err != nil ||
a.command(ctx, "chmod", "0660", paths.socket) != nil {
return errors.New("cannot publish PHP-FPM socket")
}
return nil
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
return errors.New("PHP-FPM pool did not become ready")
}
func (a Agent) stopPHPIdentityProcess(ctx context.Context, paths phpIdentityPaths) error {
pid, err := readPID(paths.pid)
if errors.Is(err, os.ErrNotExist) {
_ = os.Remove(paths.socket)
return nil
}
if err != nil {
return err
}
if err = a.signalPHPProcess(ctx, paths, "TERM", pid); err != nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil {
return err
}
for attempt := 0; attempt < 50; attempt++ {
if a.signalPHPProcess(ctx, paths, "0", pid) != nil {
_ = os.Remove(paths.pid)
_ = os.Remove(paths.socket)
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
return errors.New("PHP-FPM pool did not stop")
}
func (a Agent) phpIdentityRunning(ctx context.Context, paths phpIdentityPaths) bool {
pid, err := readPID(paths.pid)
return err == nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil
}
func (a Agent) signalPHPProcess(ctx context.Context, paths phpIdentityPaths, signal string, pid int) error {
if a.runCommand != nil {
return a.command(ctx, "kill", "-"+signal, strconv.Itoa(pid))
}
return signalPHPAsIdentity(ctx, paths.config, signal, pid)
}
func readPID(path string) (int, error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, err
}
pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
if err != nil || pid < 2 {
return 0, errors.New("invalid PHP-FPM pid")
}
return pid, nil
}
func writePrivateFile(path string, content []byte) error {
if len(content) > 128<<10 {
return errors.New("private managed file is too large")
}
directory := filepath.Dir(path)
if err := requirePhysicalDirectory(directory); err != nil {
return err
}
temporary, err := os.CreateTemp(directory, ".sea-vhost-php-*")
if err != nil {
return err
}
name := temporary.Name()
defer os.Remove(name)
if err = temporary.Chmod(0600); err == nil {
_, err = temporary.Write(content)
}
if syncErr := temporary.Sync(); err == nil {
err = syncErr
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return err
}
return os.Rename(name, path)
}
@@ -0,0 +1,89 @@
//go:build linux
package isolation
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"sea-vhost/internal/hosting"
"strconv"
"strings"
"syscall"
)
// PID files are written by the unprivileged FPM master. Never send a root
// signal to a PID taken from that file: a host could substitute another PID.
func signalPHPAsIdentity(ctx context.Context, config, signal string, pid int) error {
identity := ""
name := strings.TrimSuffix(filepath.Base(config), ".conf")
if phpSiteNamePattern.MatchString(name) {
identity = strings.Split(name, "_")[0]
} else if config == filepath.Join(pmaStateRoot, "php-fpm.conf") {
identity = pmaIdentity
}
if identity == "" || pid < 2 || (signal != "0" && signal != "TERM") {
return fmt.Errorf("invalid PHP signal identity")
}
out, e := runScheduledIdentity(ctx, identity, "/bin/kill", []string{"-" + signal, strconv.Itoa(pid)}, "/", nil)
if e != nil {
return e
}
if out.ExitCode != 0 {
return fmt.Errorf("PHP process unavailable to its identity")
}
return nil
}
// startPHPAsIdentity changes credentials in the forked child before exec.
// Linux clears the child's ambient capabilities when its UID changes from
// root, so the PHP-FPM master and every worker run without agent privileges.
func startPHPAsIdentity(ctx context.Context, binary, config, identity string) error {
return runPHPAsIdentity(ctx, binary, identity, "--fpm-config", config)
}
func testPHPAsIdentity(ctx context.Context, binary, config, identity string) error {
return runPHPAsIdentity(ctx, binary, identity, "-t", "--fpm-config", config)
}
func runPHPAsIdentity(ctx context.Context, binary, identity string, args ...string) error {
account, err := user.Lookup(identity)
if err != nil {
return fmt.Errorf("lookup PHP identity: %w", err)
}
uid, err := strconv.ParseUint(account.Uid, 10, 32)
if err != nil || uid == 0 {
return fmt.Errorf("invalid PHP identity uid")
}
gid, err := strconv.ParseUint(account.Gid, 10, 32)
if err != nil || gid == 0 {
return fmt.Errorf("invalid PHP identity gid")
}
command := exec.CommandContext(ctx, binary, args...)
command.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"}
if len(args) > 0 {
key := strings.TrimSuffix(filepath.Base(args[len(args)-1]), ".conf")
if phpSiteNamePattern.MatchString(key) {
if raw, e := os.ReadFile(filepath.Join(startupStateRoot, key+".json")); e == nil {
var state hosting.RunnerConfig
if json.Unmarshal(raw, &state) == nil && state.UID == uint32(uid) {
for name, value := range state.Environment {
command.Env = append(command.Env, name+"="+value)
}
}
}
}
}
command.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{
Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)},
}}
output, err := command.CombinedOutput()
if err != nil {
return fmt.Errorf("run PHP-FPM as isolated identity: %w: %s", err, strings.TrimSpace(string(output)))
}
return nil
}
@@ -0,0 +1,20 @@
//go:build !linux
package isolation
import (
"context"
"errors"
)
func signalPHPAsIdentity(context.Context, string, string, int) error {
return errors.New("isolated PHP signals require Linux")
}
func startPHPAsIdentity(context.Context, string, string, string) error {
return errors.New("isolated PHP identities require Linux")
}
func testPHPAsIdentity(context.Context, string, string, string) error {
return errors.New("isolated PHP identities require Linux")
}
+387
View File
@@ -0,0 +1,387 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"mime"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
)
const pmaStateRoot = "/var/lib/sea-vhost-agent/phpmyadmin"
const pmaIdentity = "sea-vhost-pma"
var pmaSetupMu sync.Mutex
type PHPMyAdminRequest struct {
Project ProjectSpec `json:"project"`
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"query"`
Body []byte `json:"body"`
Cookie string `json:"cookie"`
ContentType string `json:"contentType"`
Username string `json:"username"`
Password string `json:"password"`
BaseURI string `json:"baseURI"`
}
type PHPMyAdminResponse struct {
Status int `json:"status"`
Header http.Header `json:"header"`
Body []byte `json:"body"`
}
type PHPMyAdminProxy interface {
PHPMyAdmin(context.Context, PHPMyAdminRequest) (PHPMyAdminResponse, error)
}
func (c *Client) PHPMyAdmin(ctx context.Context, v PHPMyAdminRequest) (PHPMyAdminResponse, error) {
var out PHPMyAdminResponse
e := c.requestLong(ctx, "/v1/database/phpmyadmin", v, &out)
return out, e
}
func (Mock) PHPMyAdmin(context.Context, PHPMyAdminRequest) (PHPMyAdminResponse, error) {
return PHPMyAdminResponse{Status: 200, Header: http.Header{"Content-Type": {"text/html"}}, Body: []byte("phpMyAdmin test")}, nil
}
func validPMAPath(name string) bool {
if name == "" {
return true
}
if path.Clean(name) != name || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\\x00") || strings.Contains(name, "..") || len(name) > 255 {
return false
}
if name == "index.php" || name == "url.php" || name == "js/messages.php" {
return true
}
if strings.HasSuffix(strings.ToLower(name), ".php") {
return false
}
first := strings.Split(name, "/")[0]
ext := strings.ToLower(path.Ext(name))
return (first == "themes" || first == "js" || first == "vendor" || first == "favicon.ico") && map[string]bool{".css": true, ".js": true, ".map": true, ".png": true, ".gif": true, ".jpg": true, ".svg": true, ".ico": true, ".woff": true, ".woff2": true, ".ttf": true}[ext]
}
func (a Agent) phpMyAdmin(w http.ResponseWriter, r *http.Request) {
var q PHPMyAdminRequest
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(&q) != nil || d.Decode(&struct{}{}) != io.EOF || !validUsageSpec(ResourceUsageSpec{Project: q.Project}) || q.Username != q.Project.HostName || len(q.Password) < 1 || len(q.Password) > 256 || !validPMAPath(q.Path) || (q.Method != "GET" && q.Method != "POST" && q.Method != "HEAD") || len(q.Body) > 2<<20 || len(q.Cookie) > 16384 || len(q.Query) > 16384 || strings.ContainsAny(q.ContentType, "\r\n\x00") {
http.Error(w, "invalid database administration request", 400)
return
}
base, e := url.Parse(q.BaseURI)
if e != nil || base.Scheme != "https" || !webDomainPattern.MatchString(base.Hostname()) || base.User != nil || base.RawQuery != "" || base.Fragment != "" || !regexp.MustCompile(`^/api/v1/projects/[1-9][0-9]*/database-admin/$`).MatchString(base.Path) {
http.Error(w, "invalid database administration origin", 400)
return
}
if _, e = a.projectPath(q.Project); e != nil {
http.Error(w, "host unavailable", 412)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 120*time.Second)
defer cancel()
app, socket, e := a.preparePHPMyAdmin(ctx)
if e != nil {
http.Error(w, "phpMyAdmin unavailable; install phpMyAdmin and PHP in aaPanel", 503)
return
}
name := q.Path
if name == "" {
name = "index.php"
}
var out PHPMyAdminResponse
if !strings.HasSuffix(name, ".php") {
root, e := os.OpenRoot(app)
if e != nil {
http.Error(w, "phpMyAdmin unavailable", 503)
return
}
defer root.Close()
file, e := root.Open(name)
if e != nil {
http.NotFound(w, r)
return
}
defer file.Close()
data, e := io.ReadAll(io.LimitReader(file, (2<<20)+1))
if e != nil || len(data) > 2<<20 {
http.Error(w, "asset exceeds limit", 413)
return
}
out = PHPMyAdminResponse{Status: 200, Header: http.Header{"Content-Type": {mime.TypeByExtension(path.Ext(name))}}, Body: data}
} else {
uri := base.Path + name
if q.Query != "" {
uri += "?" + q.Query
}
params := map[string]string{"GATEWAY_INTERFACE": "CGI/1.1", "SERVER_SOFTWARE": "Sea-vHost", "SERVER_PROTOCOL": "HTTP/1.1", "REQUEST_METHOD": q.Method, "SCRIPT_FILENAME": filepath.Join(app, name), "SCRIPT_NAME": base.Path + name, "DOCUMENT_ROOT": app, "REQUEST_URI": uri, "QUERY_STRING": q.Query, "HTTPS": "on", "SERVER_NAME": base.Hostname(), "SERVER_PORT": "443", "HTTP_HOST": base.Host, "REMOTE_ADDR": "127.0.0.1", "CONTENT_TYPE": q.ContentType, "CONTENT_LENGTH": fmt.Sprint(len(q.Body)), "HTTP_COOKIE": q.Cookie, "SVH_DB_USER": q.Username, "SVH_DB_PASSWORD": q.Password, "SVH_PMA_URI": q.BaseURI}
status, header, body, e := callFastCGI(ctx, socket, params, q.Body)
if e != nil {
http.Error(w, "phpMyAdmin response failed or exceeded 2 MiB", 502)
return
}
out = PHPMyAdminResponse{status, header, body}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
}
func (a Agent) preparePHPMyAdmin(ctx context.Context) (string, string, error) {
pmaSetupMu.Lock()
defer pmaSetupMu.Unlock()
app := filepath.Join(pmaStateRoot, "app")
runRoot := "/run/sea-vhost-php/phpmyadmin"
socket := filepath.Join(runRoot, "php-fpm.sock")
if _, e := os.Stat(filepath.Join(app, ".sea-vhost-ready")); e == nil {
if e = securePMAReadPermissions(app); e != nil {
return "", "", e
}
}
if conn, e := (&net.Dialer{Timeout: time.Second}).DialContext(ctx, "unix", socket); e == nil {
conn.Close()
return app, socket, nil
}
if e := ensurePhysicalDirectory(pmaStateRoot, 0711); e != nil {
return "", "", e
}
if e := os.Chmod(pmaStateRoot, 0711); e != nil {
return "", "", e
}
if _, e := os.Stat(filepath.Join(app, ".sea-vhost-ready")); errors.Is(e, fs.ErrNotExist) {
candidates, _ := filepath.Glob("/www/server/phpmyadmin/phpmyadmin_*")
source := ""
for _, candidate := range candidates {
if i, e := os.Lstat(filepath.Join(candidate, "index.php")); e == nil && i.Mode().IsRegular() {
source = candidate
break
}
}
if source == "" {
return "", "", errors.New("phpMyAdmin not installed")
}
staging, e := os.MkdirTemp(pmaStateRoot, ".install-")
if e != nil {
return "", "", e
}
defer os.RemoveAll(staging)
e = filepath.WalkDir(source, func(name string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
relative, e := filepath.Rel(source, name)
if e != nil {
return e
}
if relative == "." {
return nil
}
first := strings.Split(filepath.ToSlash(relative), "/")[0]
if map[string]bool{"setup": true, "examples": true, "tmp": true, ".git": true}[first] {
if entry.IsDir() {
return fs.SkipDir
}
return nil
}
if (filepath.Dir(relative) == "." && strings.HasPrefix(entry.Name(), "config.")) || entry.Type()&os.ModeSymlink != 0 {
return nil
}
dest := filepath.Join(staging, relative)
if entry.IsDir() {
if e = os.Mkdir(dest, 0755); e != nil {
return e
}
return os.Chmod(dest, 0755)
}
info, e := entry.Info()
if e != nil || !info.Mode().IsRegular() {
return errors.New("invalid phpMyAdmin source")
}
if info.Size() > 16<<20 {
return errors.New("phpMyAdmin source file too large")
}
in, e := os.Open(name)
if e != nil {
return e
}
defer in.Close()
out, e := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if e != nil {
return e
}
_, e = io.Copy(out, in)
if e == nil {
e = out.Chmod(0644)
}
ce := out.Close()
if e != nil {
return e
}
return ce
})
if e != nil {
return "", "", e
}
if e = os.WriteFile(filepath.Join(staging, "config.inc.php"), []byte(pmaPHPConfig), 0644); e != nil {
return "", "", e
}
if e = os.WriteFile(filepath.Join(staging, "sea-signon.php"), []byte(pmaSignonPHP), 0644); e != nil {
return "", "", e
}
if e = os.WriteFile(filepath.Join(staging, ".sea-vhost-ready"), []byte("1"), 0644); e != nil {
return "", "", e
}
if e = os.Chmod(staging, 0755); e != nil {
return "", "", e
}
if e = os.Rename(staging, app); e != nil {
return "", "", e
}
if e = securePMAReadPermissions(app); e != nil {
return "", "", e
}
}
if e := a.command(ctx, "id", "-u", pmaIdentity); e != nil {
if e = a.command(ctx, "useradd", "--system", "--user-group", "--no-create-home", "--home-dir", "/nonexistent", "--shell", "/usr/sbin/nologin", pmaIdentity); e != nil {
return "", "", e
}
}
for _, dir := range []string{filepath.Join(pmaStateRoot, "sessions"), filepath.Join(pmaStateRoot, "tmp"), runRoot} {
if e := ensurePhysicalDirectory(dir, 0700); e != nil {
return "", "", e
}
if e := a.command(ctx, "chown", pmaIdentity+":"+pmaIdentity, dir); e != nil {
return "", "", e
}
}
binary := ""
for _, branch := range []string{"82", "83", "84", "81", "80"} {
candidate := filepath.Join("/www/server/php", branch, "sbin/php-fpm")
if i, e := os.Stat(candidate); e == nil && i.Mode().IsRegular() {
binary = candidate
break
}
}
if binary == "" {
return "", "", errors.New("PHP unavailable")
}
conf := filepath.Join(pmaStateRoot, "php-fpm.conf")
content := fmt.Sprintf(`[global]
pid = %s/php-fpm.pid
error_log = %s/fpm-error.log
daemonize = yes
[phpmyadmin]
user = %s
group = %s
listen = %s
listen.mode = 0600
pm = ondemand
pm.max_children = 4
pm.process_idle_timeout = 15s
pm.max_requests = 200
request_terminate_timeout = 120s
catch_workers_output = yes
clear_env = yes
security.limit_extensions = .php
php_admin_value[open_basedir] = %s/:/www/server/php/
php_admin_value[session.save_path] = %s/sessions
php_admin_value[upload_tmp_dir] = %s/tmp
php_admin_value[sys_temp_dir] = %s/tmp
php_admin_value[upload_max_filesize] = 2M
php_admin_value[post_max_size] = 2M
php_admin_value[memory_limit] = 256M
php_admin_flag[display_errors] = off
php_admin_flag[log_errors] = on
php_admin_value[pcre.jit] = 0
php_admin_value[error_log] = %s/php-error.log
`, runRoot, runRoot, pmaIdentity, pmaIdentity, socket, pmaStateRoot, pmaStateRoot, pmaStateRoot, pmaStateRoot, runRoot)
if e := writePrivateFile(conf, []byte(content)); e != nil {
return "", "", e
}
if e := a.command(ctx, "chown", "root:"+pmaIdentity, conf); e != nil {
return "", "", e
}
if e := os.Chmod(conf, 0640); e != nil {
return "", "", e
}
if e := testPHPAsIdentity(ctx, binary, conf, pmaIdentity); e != nil {
return "", "", e
}
if e := startPHPAsIdentity(ctx, binary, conf, pmaIdentity); e != nil {
return "", "", e
}
return app, socket, nil
}
// The agent's restrictive umask must not hide root-owned vendor files from
// the dedicated, unprivileged phpMyAdmin process. Credentials are never files
// in this directory; they are supplied only in private FastCGI parameters.
func securePMAReadPermissions(app string) error {
marker := filepath.Join(app, ".sea-vhost-readable-v2")
if raw, e := os.ReadFile(marker); e == nil && string(raw) == "2" {
return nil
}
if e := requirePhysicalDirectory(app); e != nil {
return e
}
e := filepath.WalkDir(app, func(name string, entry fs.DirEntry, e error) error {
if e != nil {
return e
}
if entry.Type()&os.ModeSymlink != 0 {
return errors.New("phpMyAdmin tree contains a symlink")
}
if entry.IsDir() {
return os.Chmod(name, 0755)
}
info, e := entry.Info()
if e != nil {
return e
}
if !info.Mode().IsRegular() {
return errors.New("invalid phpMyAdmin vendor file")
}
return os.Chmod(name, 0644)
})
if e != nil {
return e
}
return os.WriteFile(marker, []byte("2"), 0644)
}
const pmaPHPConfig = `<?php
$cfg['Servers'][1]['auth_type'] = 'signon';
$cfg['Servers'][1]['SignonScript'] = __DIR__ . '/sea-signon.php';
$cfg['Servers'][1]['host'] = '127.0.0.1';
$cfg['Servers'][1]['port'] = '3306';
$cfg['Servers'][1]['AllowRoot'] = false;
$cfg['Servers'][1]['AllowNoPassword'] = false;
$cfg['Servers'][1]['hide_connection_errors'] = true;
$cfg['AllowArbitraryServer'] = false;
$cfg['ServerDefault'] = 1;
$cfg['PmaAbsoluteUri'] = $_SERVER['SVH_PMA_URI'] ?? '';
$cfg['SignonURL'] = $cfg['PmaAbsoluteUri'];
$cfg['VersionCheck'] = false;
$cfg['SessionSavePath'] = '/var/lib/sea-vhost-agent/phpmyadmin/sessions';
$cfg['TempDir'] = '/var/lib/sea-vhost-agent/phpmyadmin/tmp';
$cfg['CookieSameSite'] = 'Strict';
$cfg['LoginCookieValidity'] = 1800;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
$cfg['ExecTimeLimit'] = 120;
`
const pmaSignonPHP = `<?php
function get_login_credentials($user) {
$name = $_SERVER['SVH_DB_USER'] ?? '';
if (!preg_match('/^sv[a-f0-9]{10}$/D', $name)) { return ['', '']; }
return [$name, $_SERVER['SVH_DB_PASSWORD'] ?? ''];
}
`
@@ -0,0 +1,48 @@
package isolation
import (
"os"
"path/filepath"
"testing"
)
func TestPHPMyAdminCopyReadableWithPrivateAgentUmask(t *testing.T) {
app := t.TempDir()
os.Mkdir(filepath.Join(app, "libraries"), 0700)
file := filepath.Join(app, "libraries", "config.default.php")
os.WriteFile(file, []byte("<?php"), 0600)
if e := securePMAReadPermissions(app); e != nil {
t.Fatal(e)
}
i, e := os.Stat(file)
if e != nil || i.Mode().Perm()&0044 != 0044 {
t.Fatal("unprivileged PHP cannot read copied vendor files")
}
i, _ = os.Stat(filepath.Join(app, "libraries"))
if i.Mode().Perm()&0011 != 0011 {
t.Fatal("vendor directories cannot be traversed")
}
}
func TestPHPMyAdminRouteAllowlist(t *testing.T) {
for _, name := range []string{"", "index.php", "url.php", "js/messages.php", "themes/pmahomme/css/theme.css", "js/vendor/jquery/jquery.min.js", "favicon.ico"} {
if !validPMAPath(name) {
t.Fatalf("valid asset denied %s", name)
}
}
for _, name := range []string{"config.inc.php", "sea-signon.php", "setup/index.php", "examples/signon.php", "../config.inc.php", "vendor/autoload.php", "themes/x.php", "/index.php", "js/../../secret"} {
if validPMAPath(name) {
t.Fatalf("unsafe route allowed %s", name)
}
}
}
func TestScheduleVersionCannotTraverseSDKRoot(t *testing.T) {
for _, v := range []string{"..", "../x", "1.2.3;id", "v1.2.3/../../"} {
if validScheduleVersion("node", v) {
t.Fatalf("accepted %s", v)
}
}
if !validScheduleVersion("php", "8.4") || !validScheduleVersion("python", "3.13.9") || !validScheduleVersion("node", "v24.11.0") {
t.Fatal("valid SDK version rejected")
}
}
@@ -0,0 +1,39 @@
//go:build linux
package isolation
import (
"os"
"strconv"
"strings"
)
func identityMetrics(identity string) (memory, ticks uint64, err error) {
pids, err := identityPIDs(identity)
if err != nil {
return 0, 0, err
}
for _, pid := range pids {
raw, e := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
if e != nil {
continue
}
text := string(raw)
end := strings.LastIndex(text, ")")
if end < 0 {
continue
}
fields := strings.Fields(text[end+1:])
if len(fields) < 22 {
continue
}
user, _ := strconv.ParseUint(fields[11], 10, 64)
system, _ := strconv.ParseUint(fields[12], 10, 64)
rss, _ := strconv.ParseInt(fields[21], 10, 64)
ticks += user + system
if rss > 0 {
memory += uint64(rss) * uint64(os.Getpagesize())
}
}
return memory, ticks, nil
}
@@ -0,0 +1,5 @@
//go:build !linux
package isolation
func identityMetrics(string) (uint64, uint64, error) { return 0, 0, nil }
@@ -0,0 +1,172 @@
//go:build linux
package isolation
import (
"context"
"errors"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
func identityUID(identity string) (uint32, error) {
account, err := user.Lookup(identity)
if err != nil {
return 0, err
}
uid, err := strconv.ParseUint(account.Uid, 10, 32)
if err != nil || uid == 0 {
return 0, errors.New("invalid identity uid")
}
return uint32(uid), nil
}
func identityPIDs(identity string) ([]int, error) {
uid, err := identityUID(identity)
if err != nil {
return nil, err
}
entries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
pids := make([]int, 0)
for _, entry := range entries {
pid, parseErr := strconv.Atoi(entry.Name())
if parseErr != nil || pid <= 1 {
continue
}
data, readErr := os.ReadFile("/proc/" + entry.Name() + "/status")
if readErr != nil {
continue
}
for _, line := range strings.Split(string(data), "\n") {
if !strings.HasPrefix(line, "Uid:") {
continue
}
fields := strings.Fields(line)
if len(fields) >= 2 {
value, _ := strconv.ParseUint(fields[1], 10, 32)
if uint32(value) == uid {
pids = append(pids, pid)
}
}
break
}
}
return pids, nil
}
func countIdentityProcesses(identity string) (uint32, error) {
pids, err := identityPIDs(identity)
return uint32(len(pids)), err
}
func terminateIdentityProcesses(ctx context.Context, identity string) error {
pids, err := identityPIDs(identity)
if err != nil {
return err
}
for _, pid := range pids {
_ = syscall.Kill(pid, syscall.SIGTERM)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(750 * time.Millisecond):
}
pids, err = identityPIDs(identity)
if err != nil {
return err
}
for _, pid := range pids {
if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) {
return killErr
}
}
return nil
}
func runtimeDirectoryPIDs(ctx context.Context, identity, runtimeRoot string) ([]int, error) {
uid, err := identityUID(identity)
if err != nil {
return nil, err
}
runtimeRoot = filepath.Clean(runtimeRoot)
entries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
pids := make([]int, 0)
for _, entry := range entries {
pid, parseErr := strconv.Atoi(entry.Name())
if parseErr != nil || pid <= 1 || pid == os.Getpid() {
continue
}
status, readErr := os.ReadFile("/proc/" + entry.Name() + "/status")
if readErr != nil || !statusHasUID(status, uid) {
continue
}
output, readErr := tenantMaintenanceCommand(ctx, identity, "/usr/bin/readlink", "/proc/"+entry.Name()+"/cwd").Output()
if readErr != nil {
continue
}
cwd := filepath.Clean(strings.TrimSpace(string(output)))
if cwd == runtimeRoot || strings.HasPrefix(cwd, runtimeRoot+string(os.PathSeparator)) {
pids = append(pids, pid)
}
}
return pids, nil
}
func statusHasUID(status []byte, uid uint32) bool {
for _, line := range strings.Split(string(status), "\n") {
if !strings.HasPrefix(line, "Uid:") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
return false
}
value, err := strconv.ParseUint(fields[1], 10, 32)
return err == nil && uint32(value) == uid
}
return false
}
func terminateRuntimeDirectoryProcesses(ctx context.Context, identity, runtimeRoot string) error {
pids, err := runtimeDirectoryPIDs(ctx, identity, runtimeRoot)
if err != nil {
return err
}
for _, pid := range pids {
_ = syscall.Kill(pid, syscall.SIGTERM)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(750 * time.Millisecond):
}
pids, err = runtimeDirectoryPIDs(ctx, identity, runtimeRoot)
if err != nil {
return err
}
for _, pid := range pids {
if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) {
return killErr
}
}
return nil
}
func fileIdentity(info os.FileInfo) uint64 {
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
return stat.Ino
}
return uint64(info.ModTime().UnixNano())
}
@@ -0,0 +1,20 @@
//go:build !linux
package isolation
import (
"context"
"errors"
"os"
)
func countIdentityProcesses(string) (uint32, error) {
return 0, errors.New("process accounting requires Linux")
}
func terminateIdentityProcesses(context.Context, string) error {
return errors.New("process enforcement requires Linux")
}
func terminateRuntimeDirectoryProcesses(context.Context, string, string) error {
return errors.New("runtime process enforcement requires Linux")
}
func fileIdentity(os.FileInfo) uint64 { return 1 }
@@ -0,0 +1,63 @@
//go:build linux
package isolation
import (
"context"
"errors"
"os"
"path/filepath"
"strconv"
"syscall"
"time"
)
func pureFTPDaemonPIDs(binaryPath string) ([]int, error) {
expected, err := filepath.EvalSymlinks(binaryPath)
if err != nil {
return nil, err
}
entries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
pids := make([]int, 0, 2)
for _, entry := range entries {
pid, parseErr := strconv.Atoi(entry.Name())
if parseErr != nil || pid <= 1 || pid == os.Getpid() {
continue
}
executable, readErr := os.Readlink("/proc/" + entry.Name() + "/exe")
if readErr == nil && filepath.Clean(executable) == filepath.Clean(expected) {
pids = append(pids, pid)
}
}
return pids, nil
}
func terminatePureFTPDaemons(ctx context.Context, binaryPath string) error {
pids, err := pureFTPDaemonPIDs(binaryPath)
if err != nil {
return err
}
for _, pid := range pids {
_ = syscall.Kill(pid, syscall.SIGTERM)
}
if len(pids) > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(750 * time.Millisecond):
}
}
pids, err = pureFTPDaemonPIDs(binaryPath)
if err != nil {
return err
}
for _, pid := range pids {
if killErr := syscall.Kill(pid, syscall.SIGKILL); killErr != nil && !errors.Is(killErr, syscall.ESRCH) {
return killErr
}
}
return nil
}
@@ -0,0 +1,7 @@
//go:build !linux
package isolation
import "context"
func terminatePureFTPDaemons(context.Context, string) error { return nil }
@@ -0,0 +1,324 @@
package isolation
import (
"context"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
const maxPythonSourceBytes = 80 << 20
func (a Agent) installPythonRuntime(w http.ResponseWriter, r *http.Request) {
var input PythonRuntimeInstallSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !supportedPythonSourceVersion(input.Version) {
http.Error(w, "invalid Python version", http.StatusBadRequest)
return
}
if err := a.installPythonSource(r.Context(), input.Version); err != nil {
slog.Error("Python source installation failed", "version", input.Version, "error", err)
http.Error(w, "cannot install verified Python source: "+err.Error(), http.StatusPreconditionFailed)
return
}
w.WriteHeader(http.StatusOK)
}
func supportedPythonSourceVersion(version string) bool {
if !pythonManagerVersionPattern.MatchString(version) {
return false
}
parts := strings.Split(version, ".")
minor, err := strconv.Atoi(parts[1])
return err == nil && parts[0] == "3" && minor >= 10 && minor <= 99
}
func (a Agent) installPythonSource(ctx context.Context, version string) error {
managerRoot := a.PythonManagerRoot
if managerRoot == "" {
managerRoot = "/www/server/python_manager/versions"
}
if !filepath.IsAbs(managerRoot) || filepath.Clean(managerRoot) != managerRoot || requirePhysicalDirectory(managerRoot) != nil {
return errors.New("Python manager root is unavailable")
}
resolvedManager, err := filepath.EvalSymlinks(managerRoot)
if err != nil || filepath.Clean(resolvedManager) != managerRoot {
return errors.New("Python manager root contains a symbolic link")
}
finalRoot := filepath.Join(managerRoot, version)
if info, statErr := os.Lstat(finalRoot); statErr == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python version path is unsafe")
}
return a.validateInstalledPython(ctx, finalRoot)
} else if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
buildRoot := a.PythonBuildRoot
if buildRoot == "" {
buildRoot = "/var/lib/sea-vhost-agent/python-builds"
}
if !filepath.IsAbs(buildRoot) || filepath.Clean(buildRoot) != buildRoot {
return errors.New("invalid Python build root")
}
if err = os.MkdirAll(buildRoot, 0700); err != nil {
return err
}
if err = requirePhysicalDirectory(buildRoot); err != nil {
return errors.New("Python build root contains a symbolic link")
}
releaseLock, err := acquirePythonInstallLock(buildRoot, version)
if err != nil {
return err
}
defer releaseLock()
// An earlier request may have finished between the initial existence check
// and lock acquisition. Do not rebuild or overwrite its completed version.
if info, statErr := os.Lstat(finalRoot); statErr == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python version path is unsafe")
}
return a.validateInstalledPython(ctx, finalRoot)
} else if !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
workRoot, err := os.MkdirTemp(buildRoot, "python-"+version+"-")
if err != nil {
return err
}
defer os.RemoveAll(workRoot)
// Check the destination before spending time compiling. On systemd hosts
// the versions directory must be prepared before the agent starts.
stageBase := filepath.Join(managerRoot, ".sea-vhost-stage-"+version+"-"+filepath.Base(workRoot))
if err = os.Mkdir(stageBase, 0700); err != nil {
return fmt.Errorf("Python versions directory is not writable; rerun the node installer to prepare runtime mounts: %w", err)
}
defer os.RemoveAll(stageBase)
archivePath, err := a.downloadVerifiedPythonSource(ctx, workRoot, version)
if err != nil {
return err
}
if err = a.command(ctx, "tar", "-xJf", archivePath, "-C", workRoot); err != nil {
return err
}
sourceRoot := filepath.Join(workRoot, "Python-"+version)
configure := filepath.Join(sourceRoot, "configure")
if info, statErr := os.Stat(configure); statErr != nil || !runtimeExecutable(info) {
return errors.New("verified Python source archive has an invalid layout")
}
if err = a.commandAt(ctx, sourceRoot, configure, "--prefix="+finalRoot, "--with-ensurepip=install"); err != nil {
return err
}
jobs := runtime.NumCPU()
if jobs < 1 {
jobs = 1
} else if jobs > 4 {
jobs = 4
}
if err = a.command(ctx, "make", "-C", sourceRoot, "-j", strconv.Itoa(jobs)); err != nil {
return err
}
if err = a.command(ctx, "make", "-C", sourceRoot, "DESTDIR="+stageBase, "install"); err != nil {
return err
}
stagedRoot := stagedPythonInstallRoot(stageBase, finalRoot)
if info, statErr := os.Lstat(stagedRoot); statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("Python staged installation is invalid")
}
if err = a.normalizeSharedPythonAccess(ctx, stagedRoot); err != nil {
return err
}
if err = os.WriteFile(filepath.Join(stagedRoot, ".sea-vhost-runtime"), []byte(version+"\n"), 0600); err != nil {
return err
}
if err = os.Rename(stagedRoot, finalRoot); err != nil {
return err
}
if err = a.validateInstalledPython(ctx, finalRoot); err != nil {
marker, _ := os.ReadFile(filepath.Join(finalRoot, ".sea-vhost-runtime"))
if strings.TrimSpace(string(marker)) == version {
_ = os.RemoveAll(finalRoot)
}
return err
}
return nil
}
func stagedPythonInstallRoot(stageBase, finalRoot string) string {
relative := strings.TrimPrefix(finalRoot, filepath.VolumeName(finalRoot))
relative = strings.TrimLeft(relative, `/\\`)
return filepath.Join(stageBase, relative)
}
func (a Agent) validateInstalledPython(ctx context.Context, root string) error {
python := filepath.Join(root, "bin", "python3")
resolved, err := filepath.EvalSymlinks(python)
if err != nil || !strings.HasPrefix(filepath.Clean(resolved)+string(os.PathSeparator), filepath.Clean(root)+string(os.PathSeparator)) {
return errors.New("Python interpreter escaped its installation root")
}
info, err := os.Stat(resolved)
if err != nil || !runtimeExecutable(info) {
return errors.New("Python interpreter is unavailable")
}
return a.command(ctx, python, "-c", "import ensurepip,ssl,sqlite3,venv")
}
func (a Agent) downloadVerifiedPythonSource(ctx context.Context, workRoot, version string) (string, error) {
metadataBase := strings.TrimRight(a.PythonMetadataBaseURL, "/")
if metadataBase == "" {
metadataBase = "https://www.python.org/ftp/python"
}
fileName := "Python-" + version + ".tar.xz"
metadataURL := metadataBase + "/" + version + "/" + fileName + ".sigstore"
var bundleBytes []byte
var err error
trustedOfficial := metadataBase == "https://www.python.org/ftp/python"
if trustedOfficial {
bundleBytes, _ = a.readPythonMetadataCache(fileName + ".sigstore")
}
if len(bundleBytes) == 0 {
bundleBytes, err = fetchPythonURL(ctx, metadataURL, 1<<20)
}
if err != nil {
return "", fmt.Errorf("fetch official Python signature metadata: %w", err)
}
expectedDigest, err := pythonSourceDigest(bundleBytes)
if err != nil {
return "", err
}
if trustedOfficial {
a.cachePythonMetadata(fileName+".sigstore", bundleBytes)
if cached, cacheErr := a.readPythonVerificationCache(fileName, maxPythonSourceBytes); cacheErr == nil {
actual := sha256.Sum256(cached)
if subtle.ConstantTimeCompare(actual[:], expectedDigest) != 1 {
return "", errors.New("offline Python source digest mismatch")
}
archivePath := filepath.Join(workRoot, fileName)
if err = os.WriteFile(archivePath, cached, 0600); err != nil {
return "", err
}
return archivePath, nil
}
}
bases := a.PythonSourceBaseURLs
if len(bases) == 0 {
bases = []string{"https://mirrors.huaweicloud.com/python", "https://www.python.org/ftp/python"}
}
var failures []string
for _, base := range bases {
sourceURL := strings.TrimRight(base, "/") + "/" + version + "/" + fileName
archivePath := filepath.Join(workRoot, fileName)
actualDigest, downloadErr := downloadPythonArchive(ctx, sourceURL, archivePath)
if downloadErr == nil && subtle.ConstantTimeCompare(actualDigest, expectedDigest) == 1 {
return archivePath, nil
}
_ = os.Remove(archivePath)
if downloadErr != nil {
failures = append(failures, downloadErr.Error())
} else {
failures = append(failures, "digest mismatch from "+sourceURL)
}
}
return "", fmt.Errorf("no verified Python source mirror succeeded: %s", strings.Join(failures, "; "))
}
func pythonSourceDigest(bundleBytes []byte) ([]byte, error) {
var bundle struct {
MessageSignature struct {
MessageDigest struct {
Algorithm string `json:"algorithm"`
Digest string `json:"digest"`
} `json:"messageDigest"`
} `json:"messageSignature"`
}
if json.Unmarshal(bundleBytes, &bundle) != nil || bundle.MessageSignature.MessageDigest.Algorithm != "SHA2_256" {
return nil, errors.New("official Python signature metadata is invalid")
}
expectedDigest, err := base64.StdEncoding.DecodeString(bundle.MessageSignature.MessageDigest.Digest)
if err != nil || len(expectedDigest) != sha256.Size {
return nil, errors.New("official Python source digest is invalid")
}
return expectedDigest, nil
}
func fetchPythonURL(ctx context.Context, rawURL string, limit int64) ([]byte, error) {
parsed, err := url.Parse(rawURL)
if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" {
return nil, errors.New("invalid source URL")
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, err
}
response, err := (&http.Client{Timeout: 2 * time.Minute}).Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("source returned HTTP %d", response.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, errors.New("source response exceeded size limit")
}
return data, nil
}
func downloadPythonArchive(ctx context.Context, rawURL, destination string) ([]byte, error) {
parsed, err := url.Parse(rawURL)
if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || parsed.Host == "" {
return nil, errors.New("invalid source URL")
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)
if err != nil {
return nil, err
}
response, err := (&http.Client{Timeout: 15 * time.Minute}).Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s returned HTTP %d", parsed.Host, response.StatusCode)
}
file, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return nil, err
}
hash := sha256.New()
written, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(response.Body, maxPythonSourceBytes+1))
closeErr := file.Close()
if copyErr != nil {
return nil, copyErr
}
if closeErr != nil {
return nil, closeErr
}
if written > maxPythonSourceBytes {
return nil, errors.New("Python source archive exceeded size limit")
}
digest := hash.Sum(nil)
slog.Info("downloaded Python source", "version", filepath.Base(destination), "host", parsed.Host, "sha256", hex.EncodeToString(digest))
return digest, nil
}
@@ -0,0 +1,122 @@
package isolation
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestInstallPythonRuntimeUsesVerifiedMirrorAndAtomicDestination(t *testing.T) {
const version = "3.12.15"
archive := []byte("verified CPython test archive")
digest := sha256.Sum256(archive)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/" + version + "/Python-" + version + ".tar.xz.sigstore":
_ = json.NewEncoder(w).Encode(map[string]any{"messageSignature": map[string]any{"messageDigest": map[string]any{"algorithm": "SHA2_256", "digest": base64.StdEncoding.EncodeToString(digest[:])}}})
case "/" + version + "/Python-" + version + ".tar.xz":
_, _ = w.Write(archive)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
managerRoot := filepath.Join(t.TempDir(), "versions")
buildRoot := filepath.Join(t.TempDir(), "builds")
if err := os.MkdirAll(managerRoot, 0755); err != nil {
t.Fatal(err)
}
finalRoot := filepath.Join(managerRoot, version)
commands := make([]string, 0, 5)
agent := Agent{
PythonManagerRoot: managerRoot, PythonBuildRoot: buildRoot,
PythonMetadataBaseURL: server.URL, PythonSourceBaseURLs: []string{server.URL},
runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
switch name {
case "tar":
sourceRoot := filepath.Join(args[len(args)-1], "Python-"+version)
if err := os.MkdirAll(sourceRoot, 0700); err != nil {
return err
}
return os.WriteFile(filepath.Join(sourceRoot, "configure"), []byte("test"), 0755)
case "make":
for _, argument := range args {
if strings.HasPrefix(argument, "DESTDIR=") {
stageBase := strings.TrimPrefix(argument, "DESTDIR=")
python := filepath.Join(stagedPythonInstallRoot(stageBase, finalRoot), "bin", "python3")
if err := os.MkdirAll(filepath.Dir(python), 0755); err != nil {
return err
}
return os.WriteFile(python, []byte("test"), 0755)
}
}
}
return nil
},
}
body, _ := json.Marshal(PythonRuntimeInstallSpec{Version: version})
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/python/install", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("install status = %d, body = %s", response.Code, response.Body.String())
}
if _, err := os.Stat(filepath.Join(finalRoot, "bin", "python3")); err != nil {
t.Fatal(err)
}
joined := strings.Join(commands, "\n")
if !strings.Contains(joined, "--prefix="+finalRoot) || !strings.Contains(joined, "DESTDIR="+managerRoot) {
t.Fatalf("Python build was not confined to managed paths:\n%s", joined)
}
}
func TestInstallPythonRuntimeRejectsUnsupportedBranch(t *testing.T) {
agent := Agent{}
body, _ := json.Marshal(PythonRuntimeInstallSpec{Version: "3.9.25"})
response := httptest.NewRecorder()
agent.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/runtime/python/install", bytes.NewReader(body)))
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", response.Code)
}
}
func TestPythonSourceDigestMismatchCannotReachExtraction(t *testing.T) {
const version = "3.12.15"
digest := sha256.Sum256([]byte("official source"))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".sigstore") {
_ = json.NewEncoder(w).Encode(map[string]any{"messageSignature": map[string]any{"messageDigest": map[string]any{"algorithm": "SHA2_256", "digest": base64.StdEncoding.EncodeToString(digest[:])}}})
return
}
_, _ = w.Write([]byte("tampered source"))
}))
defer server.Close()
managerRoot, buildRoot := t.TempDir(), t.TempDir()
called := false
agent := Agent{
PythonManagerRoot: managerRoot, PythonBuildRoot: buildRoot,
PythonMetadataBaseURL: server.URL, PythonSourceBaseURLs: []string{server.URL},
runCommand: func(context.Context, string, ...string) error { called = true; return nil },
}
if err := agent.installPythonSource(context.Background(), version); err == nil || !strings.Contains(err.Error(), "digest mismatch") {
t.Fatalf("mismatched archive result = %v", err)
}
if called {
t.Fatal("unverified source reached extraction or compilation")
}
if _, err := os.Stat(filepath.Join(managerRoot, version)); !os.IsNotExist(err) {
t.Fatal("unverified source created an installed version")
}
if _, err := os.Stat(filepath.Join(buildRoot, "Python-"+version+".tar.xz")); !os.IsNotExist(err) {
t.Fatal("unverified archive was retained")
}
}
@@ -0,0 +1,35 @@
//go:build linux
package isolation
import (
"errors"
"os"
"path/filepath"
"syscall"
)
// The kernel releases flock when the agent exits, including on a crash. Keep
// the file on disk: unlinking a locked inode would let another request open a
// different inode and acquire a second lock for the same version.
func acquirePythonInstallLock(buildRoot, version string) (func(), error) {
lockPath := filepath.Join(buildRoot, ".install-"+version+".flock")
fd, err := syscall.Open(lockPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0600)
if err != nil {
return nil, err
}
file := os.NewFile(uintptr(fd), lockPath)
info, err := file.Stat()
if err != nil || !info.Mode().IsRegular() {
_ = file.Close()
return nil, errors.New("Python installation lock path is unsafe")
}
if err = syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
_ = file.Close()
if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) {
return nil, errors.New("Python version installation is already running")
}
return nil, err
}
return func() { _ = file.Close() }, nil
}
@@ -0,0 +1,70 @@
//go:build linux
package isolation
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestPythonInstallLockExcludesConcurrentRequests(t *testing.T) {
root := t.TempDir()
release, err := acquirePythonInstallLock(root, "3.12.15")
if err != nil {
t.Fatal(err)
}
t.Cleanup(release)
if second, err := acquirePythonInstallLock(root, "3.12.15"); err == nil {
second()
t.Fatal("a concurrent installation acquired the same version lock")
}
release()
second, err := acquirePythonInstallLock(root, "3.12.15")
if err != nil {
t.Fatalf("released lock could not be reacquired: %v", err)
}
defer second()
}
func TestPythonInstallLockReleasedAfterProcessExit(t *testing.T) {
if root := os.Getenv("SEA_PYTHON_LOCK_TEST_ROOT"); root != "" {
_, err := acquirePythonInstallLock(root, "3.12.15")
if err != nil {
os.Exit(2)
}
// Deliberately skip cleanup to simulate an agent crash.
os.Exit(0)
}
root := t.TempDir()
child := exec.Command(os.Args[0], "-test.run=^TestPythonInstallLockReleasedAfterProcessExit$")
child.Env = append(os.Environ(), "SEA_PYTHON_LOCK_TEST_ROOT="+root)
if output, err := child.CombinedOutput(); err != nil {
t.Fatalf("lock owner failed: %v: %s", err, output)
}
release, err := acquirePythonInstallLock(root, "3.12.15")
if err != nil {
t.Fatalf("exited process left a stale lock: %v", err)
}
defer release()
}
func TestPythonInstallLockRejectsSymlink(t *testing.T) {
root := t.TempDir()
target := filepath.Join(root, "unrelated")
if err := os.WriteFile(target, []byte("untouched"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, filepath.Join(root, ".install-3.12.15.flock")); err != nil {
t.Fatal(err)
}
if release, err := acquirePythonInstallLock(root, "3.12.15"); err == nil {
release()
t.Fatal("symbolic link was accepted as a lock file")
}
data, err := os.ReadFile(target)
if err != nil || string(data) != "untouched" {
t.Fatal("lock acquisition modified the symlink target")
}
}
@@ -0,0 +1,20 @@
//go:build !linux
package isolation
import (
"errors"
"os"
"path/filepath"
)
func acquirePythonInstallLock(buildRoot, version string) (func(), error) {
lockPath := filepath.Join(buildRoot, ".install-"+version+".lock")
if err := os.Mkdir(lockPath, 0700); err != nil {
if errors.Is(err, os.ErrExist) {
return nil, errors.New("Python version installation is already running")
}
return nil, err
}
return func() { _ = os.Remove(lockPath) }, nil
}
@@ -0,0 +1,94 @@
package isolation
import (
"errors"
"io"
"os"
"path/filepath"
)
func (a Agent) pythonMetadataDirectory() string {
if a.PythonMetadataCacheRoot != "" {
return a.PythonMetadataCacheRoot
}
return "/var/lib/sea-vhost-agent/python-metadata"
}
// A cache is software verification material, not a node-side platform ledger.
// It can only be supplied by root (including an offline import of the official
// .sigstore file); unprivileged users and symlinks cannot establish trust.
func (a Agent) readPythonMetadataCache(name string) ([]byte, error) {
data, err := a.readPythonVerificationCache(name, 1<<20)
if err != nil {
return nil, err
}
if _, err = pythonSourceDigest(data); err != nil {
return nil, err
}
return data, nil
}
func (a Agent) readPythonVerificationCache(name string, limit int64) ([]byte, error) {
directory := a.pythonMetadataDirectory()
if filepath.Base(name) != name || requirePhysicalDirectory(directory) != nil {
return nil, errors.New("unsafe metadata cache")
}
info, err := os.Lstat(directory)
if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 {
return nil, errors.New("untrusted metadata cache directory")
}
root, err := os.OpenRoot(directory)
if err != nil {
return nil, err
}
defer root.Close()
info, err = root.Lstat(name)
if err != nil || !info.Mode().IsRegular() || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 || info.Size() > limit {
return nil, errors.New("untrusted metadata cache file")
}
file, err := root.Open(name)
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, errors.New("metadata cache exceeds limit")
}
return data, nil
}
func (a Agent) cachePythonMetadata(name string, data []byte) {
if !canWritePythonMetadataCache() || filepath.Base(name) != name {
return
}
directory := a.pythonMetadataDirectory()
if os.MkdirAll(directory, 0700) != nil || requirePhysicalDirectory(directory) != nil {
return
}
info, err := os.Lstat(directory)
if err != nil || !rootOwnedPythonMetadata(info) || info.Mode().Perm()&0022 != 0 {
return
}
file, err := os.CreateTemp(directory, ".metadata-")
if err != nil {
return
}
temporary := file.Name()
defer os.Remove(temporary)
if file.Chmod(0600) != nil {
file.Close()
return
}
if _, err = file.Write(data); err != nil {
file.Close()
return
}
if file.Close() != nil {
return
}
_ = os.Rename(temporary, filepath.Join(directory, name))
}
@@ -0,0 +1,14 @@
//go:build linux
package isolation
import (
"os"
"syscall"
)
func rootOwnedPythonMetadata(info os.FileInfo) bool {
s, ok := info.Sys().(*syscall.Stat_t)
return ok && s.Uid == 0
}
func canWritePythonMetadataCache() bool { return os.Geteuid() == 0 }
@@ -0,0 +1,85 @@
//go:build linux
package isolation
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"os"
"path/filepath"
"testing"
)
func TestOfflinePythonSourceCacheRequiresOfficialDigest(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("root-owned offline source test")
}
root := t.TempDir()
a := Agent{PythonMetadataCacheRoot: root}
const name = "Python-3.12.15.tar.xz"
source := []byte("verified offline source")
digest := sha256.Sum256(source)
bundle := []byte(fmt.Sprintf(`{"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":%q}}}`, base64.StdEncoding.EncodeToString(digest[:])))
a.cachePythonMetadata(name+".sigstore", bundle)
if err := os.WriteFile(filepath.Join(root, name), source, 0600); err != nil {
t.Fatal(err)
}
archive, err := a.downloadVerifiedPythonSource(context.Background(), t.TempDir(), "3.12.15")
if err != nil {
t.Fatal(err)
}
actual, err := os.ReadFile(archive)
if err != nil || string(actual) != string(source) {
t.Fatal("verified offline source was not staged")
}
if err = os.WriteFile(filepath.Join(root, name), []byte("tampered"), 0600); err != nil {
t.Fatal(err)
}
if _, err = a.downloadVerifiedPythonSource(context.Background(), t.TempDir(), "3.12.15"); err == nil {
t.Fatal("tampered offline source trusted")
}
}
func TestPythonMetadataCacheOnlyAcceptsRootProtectedFiles(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("root-owned offline metadata test")
}
root := t.TempDir()
a := Agent{PythonMetadataCacheRoot: root}
const name = "Python-3.12.15.tar.xz.sigstore"
data := []byte(`{"messageSignature":{"messageDigest":{"algorithm":"SHA2_256","digest":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}}}`)
a.cachePythonMetadata(name, data)
if _, err := a.readPythonMetadataCache(name); err != nil {
t.Fatal(err)
}
if err := os.Chmod(filepath.Join(root, name), 0666); err != nil {
t.Fatal(err)
}
if _, err := a.readPythonMetadataCache(name); err == nil {
t.Fatal("world-writable cache trusted")
}
if err := os.Chmod(filepath.Join(root, name), 0600); err != nil {
t.Fatal(err)
}
if err := os.Chown(filepath.Join(root, name), 65534, 65534); err != nil {
t.Fatal(err)
}
if _, err := a.readPythonMetadataCache(name); err == nil {
t.Fatal("non-root cache trusted")
}
if err := os.Remove(filepath.Join(root, name)); err != nil {
t.Fatal(err)
}
target := filepath.Join(t.TempDir(), "public")
if err := os.WriteFile(target, data, 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, filepath.Join(root, name)); err != nil {
t.Fatal(err)
}
if _, err := a.readPythonMetadataCache(name); err == nil {
t.Fatal("symlink cache trusted")
}
}
@@ -0,0 +1,8 @@
//go:build !linux
package isolation
import "os"
func rootOwnedPythonMetadata(os.FileInfo) bool { return false }
func canWritePythonMetadataCache() bool { return false }
@@ -0,0 +1,347 @@
package isolation
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
type trafficCursor struct {
Month string `json:"month"`
FileID uint64 `json:"fileId"`
Offset int64 `json:"offset"`
Bytes uint64 `json:"bytes"`
}
type trafficState struct {
Version int `json:"version"`
Domains map[string]trafficCursor `json:"domains"`
}
var (
trafficStateMu sync.Mutex
nginxBytesPattern = regexp.MustCompile(`"\s+[0-9]{3}\s+([0-9]+|-)\s`)
nginxDatePattern = regexp.MustCompile(`\[([0-9]{2})/([A-Za-z]{3})/([0-9]{4}):`)
)
func (a Agent) resourceUsage(w http.ResponseWriter, r *http.Request) {
var spec ResourceUsageSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!validUsageSpec(spec) || len(spec.Domains) > 100 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
storage, err := measureProjectStorage(projectRoot)
if err != nil {
http.Error(w, "cannot measure project storage", http.StatusInternalServerError)
return
}
processes, err := countIdentityProcesses(spec.Project.HostName)
if err != nil {
http.Error(w, "cannot count isolated processes", http.StatusInternalServerError)
return
}
bandwidth, err := a.measureBandwidth(spec.Domains, time.Now())
if err != nil {
http.Error(w, "cannot measure site bandwidth", http.StatusInternalServerError)
return
}
ftpBytes, err := a.measureFTPBandwidth(spec.Project.HostName, time.Now())
if err != nil || ftpBytes > math.MaxUint64-bandwidth {
http.Error(w, "cannot measure FTP bandwidth", 500)
return
}
bandwidth += ftpBytes
memory, ticks, err := identityMetrics(spec.Project.HostName)
if err != nil {
http.Error(w, "cannot read process metrics", 412)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ResourceUsage{StorageBytes: storage, BandwidthBytes: bandwidth, ProcessCount: processes, MemoryBytes: memory, CPUTicks: ticks})
}
// measureProjectStorage runs only in the root isolation agent. The API service
// deliberately cannot traverse private runtime directories owned by a host
// identity, so measuring there would let a tenant make quota refresh fail with
// chmod(000). WalkDir does not follow symlinks; only logical entry sizes below
// the already validated physical project root are counted.
func measureProjectStorage(projectRoot string) (uint64, error) {
if err := requirePhysicalDirectory(projectRoot); err != nil {
return 0, err
}
var total uint64
err := filepath.WalkDir(projectRoot, func(_ string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() {
return nil
}
info, err := entry.Info()
if err != nil {
return err
}
size := info.Size()
if size < 0 || uint64(size) > math.MaxUint64-total {
return errors.New("storage usage overflow")
}
total += uint64(size)
return nil
})
if err != nil {
return 0, err
}
return total, nil
}
func (a Agent) terminateProcesses(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decode(w, r)
if !ok {
return
}
projectRoot, err := a.projectPath(spec)
if err != nil || requirePhysicalDirectory(projectRoot) != nil {
http.Error(w, "project root unavailable", http.StatusPreconditionFailed)
return
}
if err = terminateIdentityProcesses(r.Context(), spec.HostName); err != nil {
http.Error(w, "cannot terminate isolated processes", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (a Agent) terminateRuntime(w http.ResponseWriter, r *http.Request) {
var input RuntimeProcessSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!safeName.MatchString(input.Project.HostName) || !validProjectRunPath(input.Project.RunPath) ||
input.Project.TenantID == 0 || input.Project.StorageBytes == 0 || input.Project.ProcessLimit == 0 {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
projectRoot, err := a.projectPath(input.Project)
if err != nil {
http.Error(w, "invalid path", http.StatusBadRequest)
return
}
runtimeRoot, err := physicalRunDirectory(projectRoot, input.Project.RunPath)
if err != nil {
http.Error(w, "unsafe runtime directory", http.StatusPreconditionFailed)
return
}
if err = terminateRuntimeDirectoryProcesses(r.Context(), input.Project.HostName, runtimeRoot); err != nil {
http.Error(w, "cannot terminate isolated runtime processes", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func validUsageSpec(spec ResourceUsageSpec) bool {
if !safeName.MatchString(spec.Project.HostName) || spec.Project.TenantID == 0 ||
spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 || !validProjectRunPath(spec.Project.RunPath) {
return false
}
seen := make(map[string]bool, len(spec.Domains))
for index, domain := range spec.Domains {
domain = strings.ToLower(strings.TrimSpace(domain))
if !webDomainPattern.MatchString(domain) || seen[domain] {
return false
}
seen[domain] = true
spec.Domains[index] = domain
}
return true
}
func (a Agent) measureBandwidth(domains []string, now time.Time) (uint64, error) {
trafficStateMu.Lock()
defer trafficStateMu.Unlock()
statePath := a.UsageStatePath
if statePath == "" {
statePath = "/var/lib/sea-vhost-agent/traffic.json"
}
logRoot := a.NginxLogRoot
if logRoot == "" {
logRoot = "/www/wwwlogs"
}
state, err := loadTrafficState(statePath)
if err != nil {
return 0, err
}
month := now.Format("2006-01")
var total uint64
for _, rawDomain := range domains {
domain := strings.ToLower(strings.TrimSpace(rawDomain))
cursor := state.Domains[domain]
if cursor.Month != month {
cursor.Month = month
cursor.Bytes = 0
}
cursor, err = measureDomainLog(filepath.Join(logRoot, domain+".log"), cursor, month)
if err != nil {
return 0, fmt.Errorf("measure %s: %w", domain, err)
}
state.Domains[domain] = cursor
if cursor.Bytes > math.MaxUint64-total {
return 0, errors.New("bandwidth usage overflow")
}
total += cursor.Bytes
}
if err = saveTrafficState(statePath, state); err != nil {
return 0, err
}
return total, nil
}
func loadTrafficState(path string) (trafficState, error) {
state := trafficState{Version: 1, Domains: map[string]trafficCursor{}}
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return state, nil
}
if err != nil {
return state, err
}
if err = json.Unmarshal(data, &state); err != nil || state.Version != 1 || state.Domains == nil {
return trafficState{}, errors.New("invalid traffic state")
}
return state, nil
}
func saveTrafficState(path string, state trafficState) error {
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
data, err := json.Marshal(state)
if err != nil {
return err
}
temporary, err := os.CreateTemp(filepath.Dir(path), ".traffic-*.tmp")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer os.Remove(temporaryPath)
if err = temporary.Chmod(0600); err == nil {
_, err = temporary.Write(append(data, '\n'))
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return err
}
return os.Rename(temporaryPath, path)
}
func measureDomainLog(path string, cursor trafficCursor, month string) (trafficCursor, error) {
return measureTransferLog(path, cursor, month, nil)
}
func measureTransferLog(path string, cursor trafficCursor, month string, parse func(string) (uint64, bool)) (trafficCursor, error) {
info, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return cursor, nil
}
if err != nil || !info.Mode().IsRegular() {
return cursor, errors.New("site log is not a regular file")
}
currentID := fileIdentity(info)
if cursor.FileID != 0 && cursor.FileID != currentID {
rotated := path + ".1"
if rotatedInfo, statErr := os.Stat(rotated); statErr == nil && rotatedInfo.Mode().IsRegular() && fileIdentity(rotatedInfo) == cursor.FileID {
if err = accumulateTransferLog(rotated, cursor.Offset, month, &cursor, parse); err != nil {
return cursor, err
}
}
cursor.Offset = 0
}
if cursor.FileID == currentID && info.Size() < cursor.Offset {
cursor.Offset = 0 // copytruncate rotation
}
cursor.FileID = currentID
if err = accumulateTransferLog(path, cursor.Offset, month, &cursor, parse); err != nil {
return cursor, err
}
return cursor, nil
}
func accumulateLog(path string, offset int64, month string, cursor *trafficCursor) error {
return accumulateTransferLog(path, offset, month, cursor, nil)
}
func accumulateTransferLog(path string, offset int64, month string, cursor *trafficCursor, parse func(string) (uint64, bool)) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
if _, err = file.Seek(offset, io.SeekStart); err != nil {
return err
}
reader := bufio.NewReaderSize(file, 64<<10)
for {
line, readErr := reader.ReadString('\n')
if errors.Is(readErr, io.EOF) && len(line) > 0 && !strings.HasSuffix(line, "\n") {
// Nginx may still be writing this record. Re-read it from the same
// offset next cycle instead of permanently skipping a partial line.
return nil
}
if len(line) > 0 {
cursor.Offset += int64(len(line))
if parse != nil {
if value, ok := parse(line); ok {
if value > math.MaxUint64-cursor.Bytes {
return errors.New("FTP bandwidth usage overflow")
}
cursor.Bytes += value
}
} else if lineMonth(line) == month {
match := nginxBytesPattern.FindStringSubmatch(line)
if match != nil && match[1] != "-" {
value, parseErr := strconv.ParseUint(match[1], 10, 64)
if parseErr != nil || value > math.MaxUint64-cursor.Bytes {
return errors.New("bandwidth usage overflow")
}
cursor.Bytes += value
}
}
}
if errors.Is(readErr, io.EOF) {
return nil
}
if readErr != nil {
return readErr
}
}
}
func lineMonth(line string) string {
match := nginxDatePattern.FindStringSubmatch(line)
if match == nil {
return ""
}
months := map[string]string{"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"}
return match[3] + "-" + months[match[2]]
}
@@ -0,0 +1,517 @@
package isolation
import (
"context"
"debug/buildinfo"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
)
type RuntimeProbeSpec struct {
Project ProjectSpec `json:"project"`
Runtime string `json:"runtime"`
Version string `json:"version"`
ProjectName string `json:"projectName"`
EntryFile string `json:"entryFile,omitempty"`
Running bool `json:"running"`
}
type RuntimeObservation struct {
InstalledVersion string `json:"installedVersion"`
RunningVersion string `json:"runningVersion,omitempty"`
Healthy bool `json:"healthy"`
Detail string `json:"detail,omitempty"`
}
type PHPMaintenanceSpec struct {
Branch string `json:"branch"`
JobID uint64 `json:"jobId"`
Action string `json:"action"`
}
type PHPState struct {
Version string `json:"version"`
Extensions []string `json:"extensions"`
BackupPath string `json:"backupPath,omitempty"`
}
type RuntimeMaintenance interface {
ProbeRuntime(context.Context, RuntimeProbeSpec) (RuntimeObservation, error)
MaintainPHP(context.Context, PHPMaintenanceSpec) (PHPState, error)
CopyPythonDependencies(context.Context, PanelRuntimeSpec, string) error
}
func (c *Client) ProbeRuntime(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) {
var result RuntimeObservation
err := c.request(ctx, "/v1/runtime/probe", spec, &result)
return result, err
}
func (c *Client) MaintainPHP(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) {
var result PHPState
err := c.requestLong(ctx, "/v1/runtime/php/maintenance", spec, &result)
return result, err
}
func (c *Client) CopyPythonDependencies(ctx context.Context, spec PanelRuntimeSpec, old string) error {
return c.requestLong(ctx, "/v1/runtime/python/dependencies", struct {
Spec PanelRuntimeSpec `json:"spec"`
Previous string `json:"previous"`
}{spec, old}, nil)
}
var exactPHPVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]\.[0-9]{1,4}$`)
var maintenanceHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`)
func maintenanceProjectMatches(host, name string) bool {
return maintenanceHostPattern.MatchString(host) && panelProjectNamePattern.MatchString(name) && (name == host || strings.HasPrefix(name, host+"_"))
}
func phpInstallationState(ctx context.Context, branch string) (PHPState, error) {
if !phpVersionPattern.MatchString(branch) {
return PHPState{}, errors.New("invalid PHP branch")
}
root := filepath.Join("/www/server/php", strings.ReplaceAll(branch, ".", ""))
if requirePhysicalDirectory(root) != nil {
return PHPState{}, errors.New("PHP branch is not installed")
}
cmd := exec.CommandContext(ctx, filepath.Join(root, "bin/php"), "-r", `echo json_encode(["version"=>PHP_VERSION,"extensions"=>get_loaded_extensions()]);`)
cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C"}
data, err := cmd.Output()
if err != nil {
return PHPState{}, fmt.Errorf("read PHP version: %w", err)
}
var state PHPState
if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") {
return state, errors.New("PHP returned invalid version metadata")
}
slices.Sort(state.Extensions)
return state, nil
}
func (a Agent) maintainPHP(w http.ResponseWriter, r *http.Request) {
var spec PHPMaintenanceSpec
if decodeMaintenance(r, &spec) != nil || !phpVersionPattern.MatchString(spec.Branch) || !slices.Contains([]string{"inspect", "backup", "restore", "complete"}, spec.Action) || (spec.Action != "inspect" && spec.JobID == 0) {
http.Error(w, "invalid PHP maintenance request", 400)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
defer cancel()
state, err := a.maintainPHPBranch(ctx, spec)
if err != nil {
http.Error(w, err.Error(), 412)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(state)
}
func decodeMaintenance(r *http.Request, out any) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(out); err != nil {
return err
}
if err := decoder.Decode(&struct{}{}); err != io.EOF {
return errors.New("unexpected trailing JSON")
}
return nil
}
func (a Agent) maintainPHPBranch(ctx context.Context, spec PHPMaintenanceSpec) (PHPState, error) {
if spec.Action == "inspect" {
return phpInstallationState(ctx, spec.Branch)
}
base := a.BackupRoot
if base == "" {
base = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(base) || filepath.Clean(base) != base {
return PHPState{}, errors.New("invalid backup root")
}
branch := strings.ReplaceAll(spec.Branch, ".", "")
root := filepath.Join("/www/server/php", branch)
backup := filepath.Join(base, "runtime", "php", branch, strconv.FormatUint(spec.JobID, 10))
if err := os.MkdirAll(filepath.Dir(backup), 0700); err != nil {
return PHPState{}, err
}
if spec.Action == "backup" {
if info, err := os.Lstat(backup); err == nil {
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return PHPState{}, errors.New("unsafe PHP backup")
}
return readPHPSnapshot(backup, spec.Branch)
}
state, err := phpInstallationState(ctx, spec.Branch)
if err != nil {
return state, err
}
stage, err := os.MkdirTemp(filepath.Dir(backup), ".snapshot-")
if err != nil {
return state, err
}
defer os.RemoveAll(stage)
if err = a.command(ctx, "cp", "-a", "--", root, filepath.Join(stage, "installation")); err != nil {
return state, err
}
state.BackupPath = backup
data, _ := json.Marshal(state)
if err = os.WriteFile(filepath.Join(stage, "manifest.json"), data, 0600); err != nil {
return state, err
}
if err = os.Rename(stage, backup); err != nil {
return state, err
}
return state, nil
}
saved, err := readPHPSnapshot(backup, spec.Branch)
if err != nil {
return saved, err
}
if spec.Action == "complete" {
if err = os.WriteFile(filepath.Join(backup, "retention-start"), []byte(time.Now().UTC().Format(time.RFC3339)), 0600); err != nil {
return saved, err
}
a.prunePHPSnapshots(filepath.Join(base, "runtime", "php"))
return saved, nil
}
if requirePhysicalDirectory(filepath.Join(backup, "installation")) != nil {
return saved, errors.New("PHP snapshot installation unavailable")
}
stage, err := os.MkdirTemp("/www/server/php", ".sea-restore-")
if err != nil {
return saved, err
}
defer os.RemoveAll(stage)
if err = a.command(ctx, "cp", "-a", "--", filepath.Join(backup, "installation"), filepath.Join(stage, "installation")); err != nil {
return saved, err
}
if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "stop"); err != nil {
return saved, err
}
if requirePhysicalDirectory(root) != nil {
return saved, errors.New("unsafe PHP restore destination")
}
failed := filepath.Join(stage, "replaced")
if err = os.Rename(root, failed); err != nil {
return saved, err
}
if err = os.Rename(filepath.Join(stage, "installation"), root); err != nil {
_ = os.Rename(failed, root)
return saved, err
}
if err = a.command(ctx, "/etc/init.d/php-fpm-"+branch, "start"); err != nil {
return saved, err
}
return phpInstallationState(ctx, spec.Branch)
}
// Only finalized Sea vHost snapshots expire. An interrupted task keeps its
// unsealed backup until an administrator resolves that task.
func (a Agent) prunePHPSnapshots(base string) {
branches, err := os.ReadDir(base)
if err != nil {
return
}
for _, branch := range branches {
if !branch.IsDir() || !regexp.MustCompile("^[5-9][0-9]$").MatchString(branch.Name()) {
continue
}
root := filepath.Join(base, branch.Name())
if requirePhysicalDirectory(root) != nil {
continue
}
jobs, err := os.ReadDir(root)
if err != nil {
continue
}
for _, job := range jobs {
if _, err = strconv.ParseUint(job.Name(), 10, 64); err != nil || !job.IsDir() {
continue
}
path := filepath.Join(root, job.Name())
if _, err = readPHPSnapshot(path, branch.Name()[:1]+"."+branch.Name()[1:]); err != nil {
continue
}
info, err := os.Lstat(filepath.Join(path, "retention-start"))
if err != nil || !info.Mode().IsRegular() || time.Since(info.ModTime()) < 14*24*time.Hour {
continue
}
_ = os.RemoveAll(path)
}
}
}
// Expiry runs independently of future updates; unresolved snapshots are never
// sealed and therefore remain available for administrator recovery.
func (a Agent) RunRuntimeBackupExpiry(ctx context.Context) {
base := a.BackupRoot
if base == "" {
base = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(base) || filepath.Clean(base) != base {
return
}
prune := func() { a.prunePHPSnapshots(filepath.Join(base, "runtime", "php")) }
prune()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
prune()
}
}
}
func readPHPSnapshot(backup, branch string) (PHPState, error) {
if requirePhysicalDirectory(backup) != nil {
return PHPState{}, errors.New("PHP snapshot unavailable")
}
data, err := os.ReadFile(filepath.Join(backup, "manifest.json"))
if err != nil {
return PHPState{}, err
}
var state PHPState
if json.Unmarshal(data, &state) != nil || !exactPHPVersionPattern.MatchString(state.Version) || !strings.HasPrefix(state.Version, branch+".") || state.BackupPath != backup {
return state, errors.New("invalid PHP snapshot manifest")
}
return state, nil
}
func (a Agent) probeRuntime(w http.ResponseWriter, r *http.Request) {
var spec RuntimeProbeSpec
if decodeMaintenance(r, &spec) != nil || !maintenanceProjectMatches(spec.Project.HostName, spec.ProjectName) || !validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 {
http.Error(w, "invalid runtime probe", 400)
return
}
result, err := a.probeRuntimeState(r.Context(), spec)
if err != nil {
http.Error(w, err.Error(), 412)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(result)
}
func (a Agent) probeRuntimeState(ctx context.Context, spec RuntimeProbeSpec) (RuntimeObservation, error) {
root, err := a.projectPath(spec.Project)
if err != nil {
return RuntimeObservation{}, err
}
working, err := physicalRunDirectory(root, spec.Project.RunPath)
if err != nil {
return RuntimeObservation{}, err
}
result := RuntimeObservation{}
var executable string
switch spec.Runtime {
case "PHP":
state, err := phpInstallationState(ctx, spec.Version)
if err != nil {
return result, err
}
result.InstalledVersion = state.Version
executable = filepath.Join("/www/server/php", strings.ReplaceAll(spec.Version, ".", ""), "sbin/php-fpm")
if !spec.Running {
result.Detail = "站点已停止,等待启动验证"
return result, nil
}
// Probe the private PID/socket directly; no Nginx config is modified.
runRoot := a.PHPRunRoot
if runRoot == "" {
runRoot = "/run/sea-vhost-php"
}
pid, err := readPID(filepath.Join(runRoot, spec.ProjectName, "php-fpm.pid"))
if err != nil {
return result, err
}
if !processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, false) {
result.Detail = "PHP-FPM 仍在使用旧程序或进程身份不匹配"
return result, nil
}
conn, err := net.DialTimeout("unix", filepath.Join(runRoot, spec.ProjectName, "php-fpm.sock"), time.Second)
if err != nil {
return result, err
}
_ = conn.Close()
result.RunningVersion = state.Version
result.Healthy = true
return result, nil
case "Python":
if !supportedPythonSourceVersion(spec.Version) {
return result, errors.New("invalid Python version")
}
manager := a.PythonManagerRoot
if manager == "" {
manager = "/www/server/python_manager/versions"
}
executable = filepath.Join(manager, spec.Version, "bin/python3")
result.InstalledVersion = spec.Version
case "Node.js":
if !regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`).MatchString(spec.Version) {
return result, errors.New("invalid Node version")
}
executable = filepath.Join("/www/server/nodejs", spec.Version, "bin/node")
result.InstalledVersion = spec.Version
case "Java":
if !regexp.MustCompile(`^(?:jdk-)?[0-9]+(?:\.[0-9]+){0,3}(?:_[0-9]+)?$`).MatchString(spec.Version) {
return result, errors.New("invalid JDK version")
}
executable = filepath.Join("/www/server/java", spec.Version, "bin/java")
if info, err := os.Stat(filepath.Join("/www/server/java", spec.Version)); err == nil && info.Mode().IsRegular() {
executable = filepath.Join("/www/server/java", spec.Version)
}
result.InstalledVersion = spec.Version
case "Go":
if !validExecutablePath(spec.EntryFile) {
return result, errors.New("invalid Go entry")
}
executable = filepath.Join(working, spec.EntryFile)
guard, err := os.OpenRoot(working)
if err != nil {
return result, err
}
defer guard.Close()
entry, err := guard.Open(spec.EntryFile)
if err != nil {
return result, err
}
defer entry.Close()
info, err := buildinfo.Read(entry)
if err != nil {
return result, errors.New("无法读取 Go 二进制编译版本,请上传带有 Go 构建信息的程序")
}
result.InstalledVersion = info.GoVersion
if info.GoVersion != spec.Version {
result.Detail = "二进制尚未使用目标 Go 版本重新编译"
return result, nil
}
default:
return result, errors.New("unsupported runtime probe")
}
if _, err = os.Stat(executable); err != nil {
return result, errors.New("runtime executable unavailable")
}
if !spec.Running {
result.Detail = "站点已停止,等待启动验证"
return result, nil
}
pids, err := identityPIDsForRuntimeProbe(spec.Project.HostName)
if err != nil {
return result, err
}
for _, pid := range pids {
if processUsesExecutable(ctx, pid, spec.Project.HostName, executable, working, true) {
result.RunningVersion = result.InstalledVersion
result.Healthy = true
return result, nil
}
}
result.Detail = "未找到使用目标版本的站点进程"
return result, nil
}
func (a Agent) copyPythonDependencies(w http.ResponseWriter, r *http.Request) {
var input struct {
Spec PanelRuntimeSpec `json:"spec"`
Previous string `json:"previous"`
}
if decodeMaintenance(r, &input) != nil || input.Spec.Runtime != "Python" || !supportedPythonSourceVersion(input.Previous) || !supportedPythonSourceVersion(input.Spec.Version) || !maintenanceProjectMatches(input.Spec.Project.HostName, input.Spec.ProjectName) || input.Spec.Project.TenantID == 0 {
http.Error(w, "invalid Python migration", 400)
return
}
root, err := a.projectPath(input.Spec.Project)
if err != nil {
http.Error(w, "invalid project", 412)
return
}
working, err := physicalRunDirectory(root, input.Spec.Project.RunPath)
if err != nil {
http.Error(w, "unsafe run directory", 412)
return
}
parent := filepath.Join(working, ".sea-runtime/python")
oldPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Previous, "bin/python3")
newPython := filepath.Join(parent, input.Spec.ProjectName+"-"+input.Spec.Version, "bin/python3")
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute)
defer cancel()
manager := a.PythonManagerRoot
if manager == "" {
manager = "/www/server/python_manager/versions"
}
if err = a.repairManagedPythonAccess(ctx, filepath.Join(manager, input.Previous), input.Previous); err != nil {
http.Error(w, "previous shared Python installation is unavailable", 412)
return
}
// Both commands drop UID before executing tenant-controlled venv content.
cmd := tenantMaintenanceCommand(ctx, input.Spec.Project.HostName, oldPython, "-m", "pip", "freeze")
var dependencies cappedDependencyBuffer
cmd.Stdout = &dependencies
err = cmd.Run()
if err != nil {
http.Error(w, "cannot export previous Python dependencies", 412)
return
}
if dependencies.exceeded {
http.Error(w, "Python dependency list too large", 412)
return
}
data := dependencies.data
if strings.TrimSpace(string(data)) != "" {
cmd = pythonDependencyRestoreCommand(ctx, input.Spec.Project.HostName, newPython)
cmd.Stdin = strings.NewReader(string(data))
cmd.Stdout, cmd.Stderr = io.Discard, io.Discard
if installErr := cmd.Run(); installErr != nil {
http.Error(w, "Python dependency restore failed; previous environment retained", 412)
return
}
}
w.WriteHeader(200)
}
const pythonDependencyRestore = `import os,sys,tempfile,subprocess
with tempfile.TemporaryDirectory(prefix=".sea-migrate-",dir=sys.argv[1]) as directory:
requirements=os.path.join(directory,"requirements.txt")
fd=os.open(requirements,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,"wb") as output:
output.write(sys.stdin.buffer.read(1048577))
result=subprocess.run([sys.executable,"-m","pip","install","--disable-pip-version-check","-r",requirements],stdin=subprocess.DEVNULL)
sys.exit(result.returncode)
`
func pythonDependencyRestoreCommand(ctx context.Context, identity, python string) *exec.Cmd {
// A root-created stdin pipe can be read via inherited FD 0, but reopening
// /dev/stdin after dropping UID can fail its inode permission check. Create
// a private requirements file as the tenant instead, and always remove it.
return tenantMaintenanceCommand(ctx, identity, python, "-c", pythonDependencyRestore, filepath.Dir(filepath.Dir(python)))
}
func tenantMaintenanceCommand(ctx context.Context, identity string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "/usr/sbin/runuser", append([]string{"-u", identity, "--"}, args...)...)
// runuser does not remove every inherited environment variable. Never let
// an own-UID helper or tenant-controlled Python read the agent's token.
cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "LANG=C", "PIP_NO_CACHE_DIR=1"}
return cmd
}
type cappedDependencyBuffer struct {
data []byte
exceeded bool
}
func (b *cappedDependencyBuffer) Write(p []byte) (int, error) {
n := len(p)
remaining := (1 << 20) - len(b.data)
if n > remaining {
b.exceeded = true
p = p[:remaining]
}
b.data = append(b.data, p...)
return n, nil
}
@@ -0,0 +1,176 @@
package isolation
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestRuntimeMaintenanceRejectsUntrustedInputs(t *testing.T) {
agent := Agent{InternalToken: "internal-test-token"}
for _, test := range []struct {
route, body string
status int
}{
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}`, 401},
{"/v1/runtime/php/maintenance", `{"branch":"../../etc","action":"restore","jobId":1}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"restore","jobId":0}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"shell","jobId":1}`, 400},
{"/v1/runtime/php/maintenance", `{"branch":"8.4","action":"inspect"}{}`, 400},
{"/v1/runtime/probe", `{"project":{"hostName":"root","tenantId":1,"runPath":"/"},"projectName":"sv0123456789","runtime":"PHP","version":"8.4"}`, 400},
{"/v1/runtime/python/dependencies", `{"spec":{"project":{"hostName":"sv0123456789"},"runtime":"Python","projectName":"../../etc","version":"3.12.15"},"previous":"3.12.0"}`, 400},
} {
r := httptest.NewRequest(http.MethodPost, test.route, bytes.NewBufferString(test.body))
if test.status != 401 {
r.Header.Set("Authorization", "Bearer internal-test-token")
}
w := httptest.NewRecorder()
agent.Handler().ServeHTTP(w, r)
if w.Code != test.status {
t.Fatalf("%s got %d: %s", test.route, w.Code, w.Body.String())
}
}
}
func TestDependencyExportRemainsBounded(t *testing.T) {
var buffer cappedDependencyBuffer
payload := bytes.Repeat([]byte("x"), (1<<20)+100)
n, err := buffer.Write(payload)
if err != nil || n != len(payload) || len(buffer.data) != 1<<20 || !buffer.exceeded {
t.Fatal("untrusted dependency export was not bounded")
}
_, _ = buffer.Write(payload)
if len(buffer.data) != 1<<20 {
t.Fatal("buffer grew beyond its limit")
}
}
func TestTenantMaintenanceDoesNotInheritAgentSecrets(t *testing.T) {
t.Setenv("SEA_INTERNAL_AUTH_TOKEN", "canary-not-for-tenant")
t.Setenv("SEA_PANEL_API_KEY", "canary-not-for-tenant")
cmd := tenantMaintenanceCommand(context.Background(), "sv0123456789", "/usr/bin/stat", "/proc/123/exe")
if len(cmd.Env) == 0 || strings.Contains(strings.Join(cmd.Env, "\n"), "canary") || strings.Contains(strings.Join(cmd.Env, "\n"), "SEA_") {
t.Fatal("tenant command inherited privileged environment")
}
if !strings.Contains(strings.Join(cmd.Args, " "), "-u sv0123456789 -- /usr/bin/stat") {
t.Fatal("tenant command did not drop UID")
}
}
func TestDependencyRestoreDoesNotReopenPrivilegedStdin(t *testing.T) {
cmd := pythonDependencyRestoreCommand(context.Background(), "sv0123456789", "/host/private/venv/bin/python3")
joined := strings.Join(cmd.Args, " ")
if strings.Contains(joined, "/dev/stdin") || !strings.Contains(joined, "sys.stdin.buffer.read") || !strings.Contains(joined, "0o600") || cmd.Args[len(cmd.Args)-1] != filepath.Dir(filepath.Dir("/host/private/venv/bin/python3")) {
t.Fatal("dependency restore must create an own-UID private requirements file")
}
}
func TestProjectACLProtectsNestedRuntimeDirectories(t *testing.T) {
root := t.TempDir()
paths := []string{filepath.Join(root, "public", ".sea-runtime"), filepath.Join(root, "apps", "web", ".sea-runtime")}
for _, path := range paths {
if err := os.MkdirAll(path, 0700); err != nil {
t.Fatal(err)
}
}
var commands []string
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
if err := agent.applyProjectACL(context.Background(), root, "sea-vhost"); err != nil {
t.Fatal(err)
}
if !strings.Contains(strings.Join(commands, "\n"), "-type f -perm /111 -exec setfacl -m u:www:r--,m::rwx,o::---") {
t.Fatal("ACL repair would revoke execution from tenant binaries")
}
for _, path := range paths {
if !strings.Contains(strings.Join(commands, "\n"), "find "+path+" -xdev ( -type d -o -type f ) -exec setfacl -m u:www:---") {
t.Fatalf("nested runtime was not protected: %s", path)
}
}
}
func TestSharedPythonModesAreReadableButNotTenantWritable(t *testing.T) {
root := t.TempDir()
var commands []string
agent := Agent{runCommand: func(_ context.Context, name string, args ...string) error {
commands = append(commands, name+" "+strings.Join(args, " "))
return nil
}}
if err := agent.normalizeSharedPythonAccess(context.Background(), root); err != nil {
t.Fatal(err)
}
joined := strings.Join(commands, "\n")
for _, expected := range []string{"chown -hR root:root " + root, "-type d -exec chmod a+rx,go-w", "-type f -exec chmod a+rX,go-w"} {
if !strings.Contains(joined, expected) {
t.Fatalf("shared interpreter access missing %s", expected)
}
}
if strings.Contains(joined, "chmod -R") || strings.Contains(joined, "find -L") {
t.Fatal("shared interpreter repair must not follow symlinks")
}
}
func TestPythonRepairDoesNotRewriteUnmanagedInstallations(t *testing.T) {
root := t.TempDir()
calls := 0
agent := Agent{runCommand: func(context.Context, string, ...string) error { calls++; return nil }}
if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err != nil || calls != 0 {
t.Fatal("unmanaged interpreter was modified")
}
if err := os.WriteFile(filepath.Join(root, ".sea-vhost-runtime"), []byte("3.12.0"), 0600); err != nil {
t.Fatal(err)
}
if err := agent.repairManagedPythonAccess(context.Background(), root, "3.12.15"); err == nil || calls != 0 {
t.Fatal("mismatched marker accepted")
}
}
func TestSnapshotExpiryPreservesUnresolvedAndRecentBackups(t *testing.T) {
base := t.TempDir()
old := time.Now().Add(-15 * 24 * time.Hour)
for _, test := range []struct {
id string
sealed, stale bool
}{{"1", true, true}, {"2", false, true}, {"3", true, false}} {
root := filepath.Join(base, "runtime", "php", "84", test.id)
if err := os.MkdirAll(root, 0700); err != nil {
t.Fatal(err)
}
manifest, _ := json.Marshal(PHPState{Version: "8.4.25", BackupPath: root})
if err := os.WriteFile(filepath.Join(root, "manifest.json"), manifest, 0600); err != nil {
t.Fatal(err)
}
if test.sealed {
marker := filepath.Join(root, "retention-start")
if err := os.WriteFile(marker, []byte("completed"), 0600); err != nil {
t.Fatal(err)
}
if test.stale {
if err := os.Chtimes(marker, old, old); err != nil {
t.Fatal(err)
}
}
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
Agent{BackupRoot: base}.RunRuntimeBackupExpiry(ctx)
for _, test := range []struct {
id string
removed bool
}{{"1", true}, {"2", false}, {"3", false}} {
_, err := os.Stat(filepath.Join(base, "runtime", "php", "84", test.id))
if os.IsNotExist(err) != test.removed {
t.Fatalf("snapshot %s expiry mismatch: %v", test.id, err)
}
}
}
@@ -0,0 +1,55 @@
//go:build linux
package isolation
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
)
func identityPIDsForRuntimeProbe(identity string) ([]int, error) { return identityPIDs(identity) }
func processUsesExecutable(ctx context.Context, pid int, identity, executable, working string, checkCWD bool) bool {
uid, err := identityUID(identity)
if err != nil {
return false
}
proc := filepath.Join("/proc", strconv.Itoa(pid))
info, err := os.Stat(proc)
if err != nil {
return false
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok || stat.Uid != uid {
return false
}
expected, err := os.Stat(executable)
if err != nil {
return false
}
expectedStat, ok := expected.Sys().(*syscall.Stat_t)
if !ok {
return false
}
// A restricted root agent intentionally lacks CAP_SYS_PTRACE. Inspect the
// process as its own UID, without adding broad process-reading privileges.
actual, err := tenantMaintenanceCommand(ctx, identity, "/usr/bin/stat", "-Lc", "%d:%i", filepath.Join(proc, "exe")).Output()
if err != nil || strings.TrimSpace(string(actual)) != fmt.Sprintf("%d:%d", expectedStat.Dev, expectedStat.Ino) {
return false
}
if checkCWD {
output, err := tenantMaintenanceCommand(ctx, identity, "/usr/bin/readlink", filepath.Join(proc, "cwd")).Output()
if err != nil {
return false
}
cwd := strings.TrimSpace(string(output))
if filepath.Clean(cwd) != filepath.Clean(working) && !strings.HasPrefix(filepath.Clean(cwd)+"/", filepath.Clean(working)+"/") {
return false
}
}
return true
}
@@ -0,0 +1,13 @@
//go:build !linux
package isolation
import (
"context"
"errors"
)
func identityPIDsForRuntimeProbe(string) ([]int, error) {
return nil, errors.New("runtime process verification requires Linux")
}
func processUsesExecutable(context.Context, int, string, string, string, bool) bool { return false }
@@ -0,0 +1,33 @@
package isolation
import (
"context"
"encoding/json"
"io"
"net/http"
"path/filepath"
)
func (c *Client) PruneRuntimeBackups(ctx context.Context) error {
return c.requestLong(ctx, "/v1/runtime/backups/prune", struct{}{}, nil)
}
func (a Agent) pruneRuntimeBackups(w http.ResponseWriter, r *http.Request) {
var input struct{}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF {
http.Error(w, "invalid prune request", 400)
return
}
base := a.BackupRoot
if base == "" {
base = "/www/backup/sea-vhost"
}
if !filepath.IsAbs(base) || filepath.Clean(base) != base {
http.Error(w, "invalid backup root", 500)
return
}
a.prunePHPSnapshots(filepath.Join(base, "runtime", "php"))
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"status":"ok"}`))
}
@@ -0,0 +1,165 @@
package isolation
import (
"context"
"crypto/tls"
"encoding/json"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sea-vhost/internal/hosting"
"strconv"
"strings"
"time"
)
type ScheduleExecutionSpec struct {
Project ProjectSpec `json:"project"`
SiteName string `json:"siteName"`
Kind string `json:"kind"`
Version string `json:"version"`
Target string `json:"target"`
Arguments []string `json:"arguments"`
Environment map[string]string `json:"environment"`
Domain string `json:"domain"`
Port int `json:"port"`
UseHTTPS bool `json:"useHTTPS"`
}
type ScheduleOutput struct {
ExitCode int `json:"exitCode"`
Output string `json:"output"`
Truncated bool `json:"truncated"`
}
type ScheduleExecutor interface {
ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error)
}
func (c *Client) ExecuteSchedule(ctx context.Context, v ScheduleExecutionSpec) (ScheduleOutput, error) {
var out ScheduleOutput
e := c.requestLong(ctx, "/v1/schedule/execute", v, &out)
return out, e
}
func (Mock) ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error) {
return ScheduleOutput{Output: "test task completed"}, nil
}
func (a Agent) executeSchedule(w http.ResponseWriter, r *http.Request) {
var v ScheduleExecutionSpec
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
check := hosting.Startup{}
if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(v.Project.HostName) || !phpSiteNamePattern.MatchString(v.SiteName) || !(v.SiteName == v.Project.HostName || strings.HasPrefix(v.SiteName, v.Project.HostName+"_")) || !validUsageSpec(ResourceUsageSpec{Project: v.Project}) {
http.Error(w, "invalid scheduled task", 400)
return
}
check.Arguments = v.Arguments
check.Environment = v.Environment
delete(check.Environment, "PORT")
if check.Validate() != nil {
http.Error(w, "invalid task parameters", 400)
return
}
root, e := a.projectPath(v.Project)
if e != nil {
http.Error(w, "invalid host root", 412)
return
}
working, e := physicalRunDirectory(root, v.Project.RunPath)
if e != nil {
http.Error(w, "website directory unavailable", 412)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 300*time.Second)
defer cancel()
var out ScheduleOutput
if v.Kind == "url" {
uri, e := url.ParseRequestURI(v.Target)
if e != nil || uri.IsAbs() || uri.Host != "" || !strings.HasPrefix(v.Target, "/") || strings.HasPrefix(v.Target, "//") || !webDomainPattern.MatchString(v.Domain) || v.Port < 1 || v.Port > 65535 {
http.Error(w, "only this website URL is allowed", 400)
return
}
scheme := "http"
if v.UseHTTPS {
scheme = "https"
}
transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(v.Port)))
}, TLSClientConfig: &tls.Config{ServerName: v.Domain, MinVersion: tls.VersionTLS12}}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 300 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
request, e := http.NewRequestWithContext(ctx, "GET", scheme+"://"+v.Domain+v.Target, nil)
if e != nil {
http.Error(w, "invalid task URL", 400)
return
}
response, e := client.Do(request)
if e != nil {
out.ExitCode = 1
out.Output = "请求本站失败"
} else {
body, e := io.ReadAll(io.LimitReader(response.Body, 65537))
response.Body.Close()
out.ExitCode = 0
if e != nil || response.StatusCode < 200 || response.StatusCode >= 300 {
out.ExitCode = 1
}
out.Truncated = len(body) > 65536
if out.Truncated {
body = body[:65536]
}
out.Output = "HTTP " + strconv.Itoa(response.StatusCode) + "\n" + strings.ToValidUTF8(string(body), "�")
}
} else {
if !hosting.ValidRelative(v.Target) || !validScheduleVersion(v.Kind, v.Version) {
http.Error(w, "invalid task script", 400)
return
}
binary := ""
switch v.Kind {
case "php":
binary = filepath.Join("/www/server/php", strings.ReplaceAll(v.Version, ".", ""), "bin/php")
case "python":
binary = filepath.Join("/www/server/python_manager/versions", v.Version, "bin/python3")
case "node":
binary = filepath.Join("/www/server/nodejs", v.Version, "bin/node")
default:
http.Error(w, "unsupported task kind", 400)
return
}
guard, e := os.OpenRoot(working)
if e != nil {
http.Error(w, "task directory unavailable", 412)
return
}
i, e := guard.Lstat(v.Target)
guard.Close()
if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 {
http.Error(w, "script must be a regular website file", 412)
return
}
args := append([]string{filepath.Join(working, v.Target)}, v.Arguments...)
if v.Kind == "php" {
args = append([]string{"-d", "pcre.jit=0", "-d", "opcache.jit=0"}, args...)
} else if v.Kind == "node" {
args = append([]string{"--jitless"}, args...)
}
out, e = runScheduledIdentity(ctx, v.Project.HostName, binary, args, working, v.Environment)
if e != nil {
http.Error(w, "cannot start isolated task", 422)
return
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
}
func validScheduleVersion(kind, version string) bool {
pattern := `^v?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$`
if kind == "php" {
pattern = `^[0-9]{1,2}\.[0-9]{1,2}$`
}
return regexp.MustCompile(pattern).MatchString(version)
}
@@ -0,0 +1,72 @@
//go:build linux
package isolation
import (
"context"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
func runScheduledIdentity(ctx context.Context, identity, binary string, args []string, cwd string, env map[string]string) (ScheduleOutput, error) {
account, e := user.Lookup(identity)
if e != nil {
return ScheduleOutput{}, e
}
uid, e := strconv.ParseUint(account.Uid, 10, 32)
if e != nil || uid == 0 {
return ScheduleOutput{}, syscall.EPERM
}
gid, e := strconv.ParseUint(account.Gid, 10, 32)
if e != nil || gid == 0 {
return ScheduleOutput{}, syscall.EPERM
}
cmd := exec.CommandContext(ctx, binary, args...)
cmd.Dir = cwd
cmd.Env = []string{"PATH=" + filepath.Dir(binary) + ":/usr/bin:/bin", "HOME=/nonexistent", "LANG=C.UTF-8"}
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid), Groups: []uint32{uint32(gid)}}, Setpgid: true, Pdeathsig: syscall.SIGKILL}
cmd.Cancel = func() error {
if cmd.Process != nil {
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = 3 * time.Second
buffer := &scheduleBuffer{}
cmd.Stdout = buffer
cmd.Stderr = buffer
e = cmd.Run()
out := ScheduleOutput{Output: strings.ToValidUTF8(string(buffer.data), "�"), Truncated: buffer.truncated}
if e != nil {
out.ExitCode = 1
if exit, ok := e.(*exec.ExitError); ok {
out.ExitCode = exit.ExitCode()
} else {
return out, e
}
}
return out, nil
}
type scheduleBuffer struct {
data []byte
truncated bool
}
func (b *scheduleBuffer) Write(p []byte) (int, error) {
n := len(p)
if len(b.data)+n > 65536 {
b.truncated = true
p = p[:max(0, 65536-len(b.data))]
}
b.data = append(b.data, p...)
return n, nil
}
@@ -0,0 +1,12 @@
//go:build !linux
package isolation
import (
"context"
"errors"
)
func runScheduledIdentity(context.Context, string, string, []string, string, map[string]string) (ScheduleOutput, error) {
return ScheduleOutput{}, errors.New("requires Linux")
}
@@ -0,0 +1,13 @@
//go:build linux
package isolation
import("context";"fmt";"os";"os/user";"path/filepath";"strconv";"strings";"testing";"time")
func TestScheduledIdentityAndForeignPIDProtection(t *testing.T){
identity:=os.Getenv("SEA_QA_HOST_IDENTITY");if identity==""{t.Skip("managed disposable identity not supplied")};if os.Geteuid()!=0||!managedWebHostPattern.MatchString(identity){t.Fatal("root test with a managed identity required")};account,e:=user.Lookup(identity);if e!=nil{t.Fatal(e)};uid,_:=strconv.Atoi(account.Uid);gid,_:=strconv.Atoi(account.Gid);if uid==0||gid==0{t.Fatal("refusing privileged identity")}
root,e:=os.MkdirTemp("/tmp","sea-vhost-schedule-native-");if e!=nil{t.Fatal(e)};defer os.RemoveAll(root);if e=os.Chown(root,uid,gid);e!=nil{t.Fatal(e)}
out,e:=runScheduledIdentity(context.Background(),identity,"/usr/bin/id",[]string{"-u"},root,nil);if e!=nil||strings.TrimSpace(out.Output)!=account.Uid{t.Fatal("scheduled task did not drop UID",e)}
marker:="$(touch "+filepath.Join(root,"injected")+")";out,e=runScheduledIdentity(context.Background(),identity,"/bin/sh",[]string{"-c",`printf '%s' "$QA_MARKER"`},root,map[string]string{"QA_MARKER":marker});if e!=nil||out.Output!=marker{t.Fatal("environment was not passed literally",e)};if _,e=os.Stat(filepath.Join(root,"injected"));!os.IsNotExist(e){t.Fatal("environment executed as shell")}
ctx,cancel:=context.WithTimeout(context.Background(),100*time.Millisecond);defer cancel();_,_=runScheduledIdentity(ctx,identity,"/bin/sh",[]string{"-c",`(sleep 1; echo escaped > escaped) & wait`},root,nil);time.Sleep(1300*time.Millisecond);if _,e=os.Stat(filepath.Join(root,"escaped"));!os.IsNotExist(e){t.Fatal("timed-out task left a normal descendant running")}
config:="/var/lib/sea-vhost-agent/php/"+identity+".conf";if e=signalPHPAsIdentity(context.Background(),config,"TERM",os.Getpid());e==nil{t.Fatal("unprivileged FPM identity signaled the root test runner")}
fmt.Println("isolated UID, literal environment, process-group timeout and foreign root PID protection passed")
}
@@ -0,0 +1,43 @@
package isolation
import (
"context"
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"sea-vhost/internal/schedulerbridge"
)
type SchedulerBridge interface {
ConfigureSchedulerBridge(context.Context, schedulerbridge.Config) error
}
func (c *Client) ConfigureSchedulerBridge(ctx context.Context, v schedulerbridge.Config) error {
return c.request(ctx, "/v1/scheduler/configure", v, nil)
}
func (Mock) ConfigureSchedulerBridge(context.Context, schedulerbridge.Config) error { return nil }
func (a Agent) configureSchedulerBridge(w http.ResponseWriter, r *http.Request) {
var v schedulerbridge.Config
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || v.Validate() != nil {
http.Error(w, "invalid scheduler identity", 400)
return
}
if e := ensurePhysicalDirectory(filepath.Dir(schedulerbridge.ConfigPath), 0700); e != nil {
http.Error(w, "scheduler directory unavailable", 422)
return
}
raw, _ := json.Marshal(v)
if e := writePrivateFile(schedulerbridge.ConfigPath, raw); e != nil {
http.Error(w, "cannot save scheduler identity", 422)
return
}
if e := os.Chmod(schedulerbridge.ConfigPath, 0600); e != nil {
http.Error(w, "cannot secure scheduler identity", 422)
return
}
w.WriteHeader(200)
}
@@ -0,0 +1,229 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"sea-vhost/internal/hosting"
"strings"
"time"
)
type WebsiteSpec struct {
Project ProjectSpec `json:"project"`
SiteName string `json:"siteName"`
Domain string `json:"domain"`
Runtime string `json:"runtime"`
Settings hosting.WebsiteSettings `json:"settings"`
}
type SiteLogSpec struct {
Project ProjectSpec `json:"project"`
SiteName string `json:"siteName"`
Domain string `json:"domain"`
Kind string `json:"kind"`
Lines int `json:"lines"`
Search string `json:"search"`
}
type SiteLog struct {
Available bool `json:"available"`
Lines []string `json:"lines"`
Truncated bool `json:"truncated"`
}
type SiteOperations interface {
ConfigureWebsite(context.Context, WebsiteSpec) error
ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error)
}
func (c *Client) ConfigureWebsite(ctx context.Context, v WebsiteSpec) error {
return c.request(ctx, "/v1/site/settings", v, nil)
}
func (c *Client) ReadSiteLog(ctx context.Context, v SiteLogSpec) (SiteLog, error) {
var out SiteLog
e := c.request(ctx, "/v1/site/log", v, &out)
return out, e
}
func (Mock) ConfigureWebsite(context.Context, WebsiteSpec) error { return nil }
func (Mock) ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error) {
return SiteLog{Available: true, Lines: []string{}}, nil
}
func (a Agent) configureWebsite(w http.ResponseWriter, r *http.Request) {
var v WebsiteSpec
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || v.Settings.Validate() != nil {
http.Error(w, "invalid website settings", 400)
return
}
if v.Runtime != "PHP" && v.Settings.Rewrite != "none" {
http.Error(w, "rewrite templates require PHP", 422)
return
}
paths, e := a.webProtectionPaths(WebProtectionSpec{Project: v.Project, Domain: v.Domain})
if e != nil || verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension) != nil {
http.Error(w, "managed site unavailable", 412)
return
}
raw, e := os.ReadFile(paths.siteConfig)
root, _ := a.projectPath(v.Project)
if e != nil || !strings.Contains(string(raw), root) {
http.Error(w, "website does not match host root", 412)
return
}
content := regexp.MustCompile(`(?m)^[ \t]*index\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(string(raw), "")
content = regexp.MustCompile(`(?m)^[ \t]*error_page\s+(?:404|503)\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(content, "")
restoreMain, e := writeManagedFile(paths.siteConfig, []byte(content))
if e != nil {
http.Error(w, "cannot stage website config", 412)
return
}
restoreSettings, e := writeManagedFile(filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-site.conf"), []byte(renderWebsite(v.Settings)))
if e != nil {
restoreMain()
http.Error(w, "cannot stage settings", 412)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if a.runNginx(ctx, "-t") != nil || a.runNginx(ctx, "-s", "reload") != nil {
restoreSettings()
restoreMain()
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
http.Error(w, "Nginx rejected settings; previous config restored", 422)
return
}
w.WriteHeader(200)
}
func renderWebsite(v hosting.WebsiteSettings) string {
var b strings.Builder
b.WriteString("# Managed by Sea vHost\nindex " + strings.Join(v.Index, " ") + ";\n")
if v.Error404 != "" {
fmt.Fprintf(&b, "error_page 404 /%s;\n", v.Error404)
}
if v.Error503 != "" {
fmt.Fprintf(&b, "error_page 503 /%s;\n", v.Error503)
}
if v.ForceHTTPS {
b.WriteString("set $svh_https_redirect 0;\nif ($scheme = http) { set $svh_https_redirect 1; }\nif ($uri ~ ^/\\.well-known/acme-challenge/) { set $svh_https_redirect 0; }\nif ($svh_https_redirect = 1) { return 301 https://$host$request_uri; }\n")
}
if v.Maintenance {
exclude := "^/(?:\\.well-known/acme-challenge/"
if v.Error503 != "" {
exclude += "|" + regexp.QuoteMeta(v.Error503) + "$"
}
exclude += ")"
fmt.Fprintf(&b, "if ($uri !~ %s) { return 503; }\n", exclude)
}
if v.RedirectURL != "" {
fmt.Fprintf(&b, "if ($uri !~ ^/\\.well-known/acme-challenge/) { return %d %s; }\n", v.RedirectCode, v.RedirectURL)
}
switch v.Rewrite {
case "wordpress", "laravel":
b.WriteString("location / { try_files $uri $uri/ /index.php?$query_string; }\n")
case "thinkphp":
b.WriteString("location / { try_files $uri $uri/ /index.php?s=$uri&$args; }\n")
case "spa":
b.WriteString("location / { try_files $uri $uri/ /index.html; }\n")
}
return b.String()
}
var logBearer = regexp.MustCompile(`(?i)(authorization["' :=]+)(?:bearer|basic) +[^\s,;"']+`)
var logSecret = regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)(["' :=]+)([^\s&,;"']+)`)
func (a Agent) readSiteLog(w http.ResponseWriter, r *http.Request) {
var v SiteLogSpec
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || len(v.Search) > 200 {
http.Error(w, "invalid log request", 400)
return
}
root, e := a.projectPath(v.Project)
if e != nil || requirePhysicalDirectory(root) != nil {
http.Error(w, "host unavailable", 412)
return
}
dir := a.NginxLogRoot
if dir == "" {
dir = "/www/wwwlogs"
}
name := v.Domain + ".log"
switch v.Kind {
case "access":
case "error":
name = v.Domain + ".error.log"
case "runtime":
dir = root
name = ".sea-runtime/logs/" + v.SiteName + ".log"
case "php":
dir = root
name = ".sea-runtime/php/fpm-error.log"
default:
http.Error(w, "invalid log kind", 400)
return
}
result, e := tailSiteLog(dir, name, v.Lines, v.Search)
if e != nil {
http.Error(w, "cannot safely read site log", 422)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}
func tailSiteLog(dir, name string, lines int, search string) (SiteLog, error) {
out := SiteLog{Lines: []string{}}
if lines < 1 || lines > 1000 {
lines = 200
}
root, e := os.OpenRoot(dir)
if e != nil {
return out, e
}
defer root.Close()
i, e := root.Lstat(name)
if errors.Is(e, os.ErrNotExist) {
return out, nil
}
if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 {
return out, errors.New("unsafe log")
}
f, e := root.Open(name)
if e != nil {
return out, e
}
defer f.Close()
size := i.Size()
offset := int64(0)
if size > 256<<10 {
offset = size - (256 << 10)
out.Truncated = true
}
f.Seek(offset, io.SeekStart)
raw, e := io.ReadAll(io.LimitReader(f, 256<<10))
if e != nil {
return out, e
}
text := strings.ToValidUTF8(string(raw), "�")
all := strings.Split(strings.TrimSuffix(text, "\n"), "\n")
if offset > 0 && len(all) > 0 {
all = all[1:]
}
for _, line := range all {
if search == "" || strings.Contains(strings.ToLower(line), strings.ToLower(search)) {
out.Lines = append(out.Lines, logSecret.ReplaceAllString(logBearer.ReplaceAllString(line, "${1}[REDACTED]"), "${1}${2}[REDACTED]"))
}
}
if len(out.Lines) > lines {
out.Lines = out.Lines[len(out.Lines)-lines:]
out.Truncated = true
}
out.Available = true
return out, nil
}
+143
View File
@@ -0,0 +1,143 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"os/user"
"path/filepath"
"regexp"
"sea-vhost/internal/hosting"
"strconv"
"strings"
)
const startupStateRoot = "/var/lib/sea-vhost-agent/startup"
type StartupSpec struct {
Project ProjectSpec `json:"project"`
SiteName string `json:"siteName"`
Runtime string `json:"runtime"`
Version string `json:"version"`
Port int `json:"port"`
Config hosting.Startup `json:"config"`
}
type StartupManager interface {
ConfigureStartup(context.Context, StartupSpec) error
}
func (c *Client) ConfigureStartup(ctx context.Context, v StartupSpec) error {
return c.request(ctx, "/v1/site/startup", v, nil)
}
func (Mock) ConfigureStartup(context.Context, StartupSpec) error { return nil }
func (a Agent) configureStartup(w http.ResponseWriter, r *http.Request) {
var v StartupSpec
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || v.Config.Validate() != nil || !regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$`).MatchString(v.Version) {
http.Error(w, "invalid startup settings", 400)
return
}
if e := a.prepareStartup(r.Context(), v); e != nil {
http.Error(w, "cannot prepare safe application launcher", 422)
return
}
w.WriteHeader(200)
}
func (a Agent) prepareStartup(ctx context.Context, v StartupSpec) error {
if v.SiteName != v.Project.HostName && !strings.HasPrefix(v.SiteName, v.Project.HostName+"_") {
return errors.New("site identity mismatch")
}
root, e := a.projectPath(v.Project)
if e != nil {
return e
}
working, e := physicalRunDirectory(root, v.Project.RunPath)
if e != nil {
return e
}
cwd := working
if v.Config.WorkDir != "." && v.Config.WorkDir != "" {
cwd, e = physicalRunDirectory(root, filepath.ToSlash(filepath.Join(v.Project.RunPath, v.Config.WorkDir)))
if e != nil {
return e
}
}
account, e := user.Lookup(v.Project.HostName)
if e != nil {
return e
}
uid, e := strconv.ParseUint(account.Uid, 10, 32)
if e != nil || uid == 0 {
return errors.New("invalid uid")
}
entry := filepath.Join(working, v.Config.EntryFile)
var binary string
var args []string
switch v.Runtime {
case "PHP":
binary = filepath.Join("/www/server/php", strings.ReplaceAll(v.Version, ".", ""), "bin/php")
case "Node.js":
binary = filepath.Join("/www/server/nodejs", v.Version, "bin/npm")
args = []string{"run", "start", "--"}
case "Python":
binary = filepath.Join(working, ".sea-runtime/python", v.SiteName+"-"+v.Version, "bin/python3")
args = []string{entry}
case "Go":
binary = entry
case "Java":
binary = filepath.Join("/www/server/java", v.Version, "bin/java")
args = []string{"-jar", entry, "--server.port=" + strconv.Itoa(v.Port)}
default:
return errors.New("invalid runtime")
}
if i, e := os.Stat(binary); e != nil || !i.Mode().IsRegular() || i.Mode()&0111 == 0 {
return errors.New("runtime executable not found")
}
args = append(args, v.Config.Arguments...)
if e = ensureProjectRunDirectory(root, "/.sea-runtime/logs"); e != nil {
return e
}
logdir, e := physicalRunDirectory(root, "/.sea-runtime/logs")
if e != nil {
return e
}
if e = a.command(ctx, "chown", a.fileServiceOwner()+":"+v.Project.HostName, logdir); e != nil {
return e
}
if e = a.command(ctx, "chmod", "0770", logdir); e != nil {
return e
}
if e = a.command(ctx, "setfacl", "-m", "u:www:---,m::rwx,o::---", logdir); e != nil {
return e
}
if e = ensurePhysicalDirectory(startupStateRoot, 0711); e != nil {
return e
}
if e = os.Chmod(startupStateRoot, 0711); e != nil {
return e
}
config := hosting.RunnerConfig{UID: uint32(uid), HostName: v.Project.HostName, Binary: binary, Arguments: args, Environment: v.Config.Environment, WorkDir: cwd, LogDir: logdir, SiteName: v.SiteName}
if config.Environment == nil {
config.Environment = map[string]string{}
}
config.Environment["PORT"] = strconv.Itoa(v.Port)
raw, _ := json.Marshal(config)
file := filepath.Join(startupStateRoot, v.SiteName+".json")
if e = writePrivateFile(file, raw); e != nil {
return e
}
if e = a.command(ctx, "chown", "root:"+v.Project.HostName, file); e != nil {
return e
}
return a.command(ctx, "chmod", "0640", file)
}
func (a Agent) fileServiceOwner() string {
if a.FileOwner != "" {
return a.FileOwner
}
return "sea-vhost"
}
@@ -0,0 +1,203 @@
package isolation
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
var trafficPolicyMu sync.Mutex
var ftpAltLogLine = regexp.MustCompile(`(?mi)^\s*AltLog\s+[^\r\n]*`)
func (a Agent) configureTrafficLimits(w http.ResponseWriter, r *http.Request) {
var spec TrafficLimitSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Mbps > 10000 || !validUsageSpec(ResourceUsageSpec{Project: spec.Project, Domains: spec.Domains}) || len(spec.Domains) > 100 {
http.Error(w, "invalid traffic policy", 400)
return
}
root, err := a.projectPath(spec.Project)
if err != nil || requirePhysicalDirectory(root) != nil {
http.Error(w, "managed project root unavailable", 412)
return
}
trafficPolicyMu.Lock()
defer trafficPolicyMu.Unlock()
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
if err = a.applyTrafficLimits(ctx, spec); err != nil {
http.Error(w, "cannot enforce traffic policy: "+err.Error(), 412)
return
}
w.WriteHeader(200)
}
func (a Agent) trafficLimitStatePath(host string) (string, error) {
path := a.UsageStatePath
if path == "" {
path = "/var/lib/sea-vhost-agent/traffic.json"
}
dir := filepath.Join(filepath.Dir(path), "limits")
if err := os.MkdirAll(dir, 0700); err != nil {
return "", err
}
if err := requirePhysicalDirectory(dir); err != nil {
return "", err
}
return filepath.Join(dir, host+".json"), nil
}
func (a Agent) applyTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error {
var restore []func() error
changed := false
rollback := func() {
for _, f := range restore {
_ = f()
}
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
}
for _, domain := range spec.Domains {
paths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: domain})
if err != nil {
rollback()
return err
}
if err = verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension); err != nil {
rollback()
return err
}
target := filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-rate.conf")
content := []byte("# Managed Sea vHost HTTP rate: per request, not aggregate host speed.\nlimit_rate " + strconv.FormatUint(uint64(spec.Mbps)*125000, 10) + ";\nlimit_rate_after 0;\nproxy_ignore_headers X-Accel-Limit-Rate;\nfastcgi_ignore_headers X-Accel-Limit-Rate;\n")
old, err := os.ReadFile(target)
if err == nil && bytes.Equal(old, content) {
continue
}
undo, err := writeManagedFile(target, content)
if err != nil {
rollback()
return err
}
restore = append(restore, undo)
changed = true
}
if changed {
if err := a.runNginx(ctx, "-t"); err != nil {
rollback()
return errors.New("Nginx rejected bandwidth limit")
}
if err := a.runNginx(ctx, "-s", "reload"); err != nil {
rollback()
return err
}
}
statePath, err := a.trafficLimitStatePath(spec.Project.HostName)
if err != nil {
return err
}
var previous struct {
Mbps uint32 `json:"mbps"`
Applied bool `json:"applied"`
}
if info, err := os.Lstat(statePath); err == nil {
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("unsafe traffic policy state")
}
data, err := os.ReadFile(statePath)
if err != nil {
return err
}
_ = json.Unmarshal(data, &previous)
}
if !previous.Applied || previous.Mbps != spec.Mbps {
binary := a.PurePWBinary
if binary == "" {
binary = "/www/server/pure-ftpd/bin/pure-pw"
}
rate := ""
if spec.Mbps > 0 {
rate = strconv.FormatUint(uint64(spec.Mbps)*125000/1024, 10)
}
if err = a.command(ctx, binary, "usermod", spec.Project.HostName, "-t", rate, "-T", rate, "-m"); err != nil {
return errors.New("cannot set FTP account transfer limit")
}
data, _ := json.Marshal(map[string]any{"mbps": spec.Mbps, "applied": true})
if err = writeSecureFile(statePath, data, 0600); err != nil {
return err
}
}
return a.ensureFTPTransferLog(ctx)
}
func (a Agent) ftpTransferLogPath() string {
if a.FTPLogPath != "" {
return a.FTPLogPath
}
return "/www/wwwlogs/sea-vhost-ftp.log"
}
func (a Agent) ensureFTPTransferLog(ctx context.Context) error {
configPath := a.PureFTPConfig
if configPath == "" {
configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf"
}
info, err := os.Lstat(configPath)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("unsafe FTP configuration")
}
content, err := os.ReadFile(configPath)
if err != nil {
return err
}
logPath := a.ftpTransferLogPath()
if !filepath.IsAbs(logPath) || strings.ContainsAny(logPath, "\r\n\x00 ") {
return errors.New("invalid FTP transfer log path")
}
wanted := []byte("AltLog stats:" + logPath)
matches := ftpAltLogLine.FindAll(content, -1)
if len(matches) == 1 && bytes.Equal(bytes.TrimSpace(matches[0]), wanted) {
return nil
}
if requirePhysicalDirectory(filepath.Dir(logPath)) != nil {
return errors.New("FTP log directory unavailable")
}
if existing, err := os.Lstat(logPath); err == nil {
if !existing.Mode().IsRegular() || existing.Mode()&os.ModeSymlink != 0 {
return errors.New("unsafe FTP log")
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if len(matches) > 0 {
backup := configPath + ".sea-vhost-before-stats"
if _, err = os.Lstat(backup); errors.Is(err, os.ErrNotExist) {
if err = writeSecureFile(backup, content, 0600); err != nil {
return err
}
}
}
updated := ftpAltLogLine.ReplaceAll(content, nil)
updated = append(bytes.TrimRight(updated, "\r\n"), '\n')
updated = append(updated, wanted...)
updated = append(updated, '\n')
if err = writeSecureFile(configPath, updated, info.Mode().Perm()); err != nil {
return err
}
if err = a.restartPureFTP(ctx, configPath); err != nil {
_ = writeSecureFile(configPath, content, info.Mode().Perm())
_ = a.restartPureFTP(ctx, configPath)
return errors.New("cannot activate FTP transfer log")
}
return nil
}
@@ -0,0 +1,360 @@
package isolation
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
const globalWebProtectionConfig = `# Managed by Sea vHost. Local changes will be replaced.
limit_req_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip:10m rate=20r/s;
limit_conn_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip_conn:10m;
`
const siteWebProtectionConfig = `# Managed by Sea vHost. Local changes will be replaced.
limit_req zone=sea_vhost_per_ip burst=60 nodelay;
limit_req_status 429;
limit_conn sea_vhost_per_ip_conn 40;
limit_conn_status 429;
client_max_body_size 64m;
client_body_timeout 30s;
client_header_timeout 15s;
send_timeout 60s;
disable_symlinks if_not_owner from=$document_root;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
if ($request_method ~* ^(TRACE|TRACK)$) { return 405; }
location ~* "(^|/)\.(?!well-known(?:/|$))" { return 404; }
location ~* "\.(?:env|ini|log|sql|sqlite|bak|old|orig|swp)$" { return 404; }
location ~* "(^|/)(?:composer\.(?:json|lock)|package(?:-lock)?\.json|yarn\.lock|pnpm-lock\.yaml|requirements(?:-[^/]+)?\.txt|Pipfile(?:\.lock)?|go\.(?:mod|sum)|pom\.xml|build\.gradle(?:\.kts)?)$" { return 404; }
`
var (
managedWebHostPattern = regexp.MustCompile(`^sv[a-f0-9]{10}$`)
webDomainPattern = regexp.MustCompile(`^(?i:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$`)
)
type managedFileSnapshot struct {
existed bool
content []byte
}
func (a Agent) decodeWebProtection(w http.ResponseWriter, r *http.Request) (WebProtectionSpec, bool) {
var spec WebProtectionSpec
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF ||
!managedWebHostPattern.MatchString(spec.Project.HostName) || !webDomainPattern.MatchString(spec.Domain) ||
spec.Project.TenantID == 0 || spec.Project.TenantID > 9_999_999_999 || spec.Project.StorageBytes == 0 ||
spec.Project.ProcessLimit == 0 || spec.Project.ProcessLimit > 100_000 {
http.Error(w, "invalid request", http.StatusBadRequest)
return WebProtectionSpec{}, false
}
return spec, true
}
func (a Agent) applyWebProtection(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodeWebProtection(w, r)
if !ok {
return
}
paths, err := a.webProtectionPaths(spec)
if err != nil {
http.Error(w, "web protection path is unavailable", http.StatusPreconditionFailed)
return
}
if err = verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension); err != nil {
http.Error(w, "aaPanel site extension include is unavailable", http.StatusPreconditionFailed)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err = verifyGlobalWebProtection(paths.globalConfig); err != nil {
http.Error(w, "global web protection is missing or invalid", http.StatusPreconditionFailed)
return
}
challenge, err := httpChallengeConfig(paths.challengeRoot)
if err != nil {
http.Error(w, "invalid challenge root", http.StatusPreconditionFailed)
return
}
restoreSite, err := writeManagedFile(paths.siteExtension, []byte(siteWebProtectionConfig+challenge))
if err != nil {
http.Error(w, "cannot write site web protection", http.StatusInternalServerError)
return
}
rollback := func() {
_ = restoreSite()
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
}
if err = a.runNginx(ctx, "-t"); err != nil {
slog.Error("nginx rejected site web protection", "domain", spec.Domain, "error", err)
rollback()
http.Error(w, "nginx rejected web protection configuration", http.StatusPreconditionFailed)
return
}
if err = a.runNginx(ctx, "-s", "reload"); err != nil {
rollback()
http.Error(w, "cannot reload nginx", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func verifyGlobalWebProtection(path string) error {
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 128<<10 {
return errors.New("unsafe global web protection file")
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
normalized := strings.ReplaceAll(string(content), "\r\n", "\n")
if normalized != globalWebProtectionConfig {
return errors.New("global web protection content mismatch")
}
return nil
}
func (a Agent) removeWebProtection(w http.ResponseWriter, r *http.Request) {
spec, ok := a.decodeWebProtection(w, r)
if !ok {
return
}
paths, err := a.webProtectionPaths(spec)
if err != nil {
http.Error(w, "web protection path is unavailable", http.StatusPreconditionFailed)
return
}
info, err := os.Lstat(paths.siteExtension)
if errors.Is(err, os.ErrNotExist) {
w.WriteHeader(http.StatusOK)
return
}
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "unsafe site web protection file", http.StatusPreconditionFailed)
return
}
content, err := os.ReadFile(paths.siteExtension)
if err != nil || len(content) > 128<<10 {
http.Error(w, "cannot read site web protection", http.StatusInternalServerError)
return
}
if err = os.Remove(paths.siteExtension); err != nil {
http.Error(w, "cannot remove site web protection", http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
restore := func() { _, _ = writeManagedFile(paths.siteExtension, content) }
if err = a.runNginx(ctx, "-t"); err != nil {
restore()
http.Error(w, "nginx rejected protection removal", http.StatusPreconditionFailed)
return
}
if err = a.runNginx(ctx, "-s", "reload"); err != nil {
restore()
_ = a.runNginx(ctx, "-t")
_ = a.runNginx(ctx, "-s", "reload")
http.Error(w, "cannot reload nginx", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type protectionPaths struct {
globalConfig, siteConfig, siteExtension, projectRoot, challengeRoot string
}
func (a Agent) webProtectionPaths(spec WebProtectionSpec) (protectionPaths, error) {
projectRoot, err := a.projectPath(spec.Project)
if err != nil {
return protectionPaths{}, err
}
if err = requirePhysicalDirectory(projectRoot); err != nil {
return protectionPaths{}, err
}
runPath := spec.Project.RunPath
if runPath == "" {
runPath = "/"
}
challengeRoot, err := physicalRunDirectory(projectRoot, runPath)
if err != nil {
return protectionPaths{}, err
}
vhostRoot, err := filepath.Abs(a.NginxVhostRoot)
if err != nil || !filepath.IsAbs(vhostRoot) {
return protectionPaths{}, errors.New("invalid nginx vhost root")
}
if err = requirePhysicalDirectory(vhostRoot); err != nil {
return protectionPaths{}, err
}
extensionRoot := filepath.Join(vhostRoot, "extension")
if err = ensurePhysicalDirectory(extensionRoot, 0755); err != nil {
return protectionPaths{}, err
}
domainRoot := filepath.Join(extensionRoot, strings.ToLower(spec.Domain))
if err = ensurePhysicalDirectory(domainRoot, 0755); err != nil {
return protectionPaths{}, err
}
return protectionPaths{
projectRoot: projectRoot,
challengeRoot: challengeRoot,
globalConfig: filepath.Join(vhostRoot, "sea-vhost-security-global.conf"),
siteConfig: filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf"),
siteExtension: filepath.Join(domainRoot, "sea-vhost-security.conf"),
}, nil
}
func verifySiteExtensionInclude(siteConfig, extension string) error {
info, err := os.Lstat(siteConfig)
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 2<<20 {
return errors.New("unsafe aaPanel site config")
}
content, err := os.ReadFile(siteConfig)
if err != nil {
return err
}
expected := filepath.ToSlash(filepath.Dir(extension)) + "/*.conf"
if !strings.Contains(filepath.ToSlash(string(content)), expected) {
return errors.New("site config does not include the managed extension directory")
}
return nil
}
func ensurePhysicalDirectory(path string, mode os.FileMode) error {
if err := requirePhysicalDirectory(filepath.Dir(path)); err != nil {
return err
}
if err := os.Mkdir(path, mode); err != nil && !errors.Is(err, os.ErrExist) {
return err
}
return requirePhysicalDirectory(path)
}
func requirePhysicalDirectory(path string) error {
info, err := os.Lstat(path)
if err != nil {
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return errors.New("path is not a physical directory")
}
return nil
}
func writeManagedFile(path string, content []byte) (func() error, error) {
if len(content) > 128<<10 {
return nil, errors.New("managed file is too large")
}
snapshot := managedFileSnapshot{}
info, err := os.Lstat(path)
if err == nil {
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Size() > 128<<10 {
return nil, errors.New("managed file target is unsafe")
}
snapshot.existed = true
snapshot.content, err = os.ReadFile(path)
if err != nil {
return nil, err
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
directory := filepath.Dir(path)
if err = requirePhysicalDirectory(directory); err != nil {
return nil, err
}
temporary, err := os.CreateTemp(directory, ".sea-vhost-security-*")
if err != nil {
return nil, err
}
temporaryName := temporary.Name()
defer os.Remove(temporaryName)
if err = temporary.Chmod(0644); err == nil {
_, err = temporary.Write(content)
}
if syncErr := temporary.Sync(); err == nil {
err = syncErr
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return nil, err
}
if err = os.Rename(temporaryName, path); err != nil {
return nil, err
}
restore := func() error {
if !snapshot.existed {
return os.Remove(path)
}
_, restoreErr := writeManagedFileWithoutSnapshot(path, snapshot.content)
return restoreErr
}
return restore, nil
}
func writeManagedFileWithoutSnapshot(path string, content []byte) (string, error) {
directory := filepath.Dir(path)
temporary, err := os.CreateTemp(directory, ".sea-vhost-restore-*")
if err != nil {
return "", err
}
name := temporary.Name()
defer os.Remove(name)
if err = temporary.Chmod(0644); err == nil {
_, err = temporary.Write(content)
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err == nil {
err = os.Rename(name, path)
}
return path, err
}
func (a Agent) runNginx(ctx context.Context, args ...string) error {
binary := strings.TrimSpace(a.NginxBinary)
if !filepath.IsAbs(binary) || filepath.Base(binary) != "nginx" {
return errors.New("invalid nginx binary")
}
if a.runCommand != nil {
return a.runCommand(ctx, binary, args...)
}
if err := command(ctx, binary, args...); err != nil {
return fmt.Errorf("nginx %s: %w", strings.Join(args, " "), err)
}
return nil
}
func httpChallengeConfig(root string) (string, error) {
if !filepath.IsAbs(root) || strings.ContainsAny(filepath.ToSlash(root), "$;{}\r\n\x00\"\\") {
return "", errors.New("unsafe ACME root")
}
return fmt.Sprintf(`
# ACME tokens use the same physical run directory as aaPanel issuance and renewal, including proxied sites.
location ^~ /.well-known/acme-challenge/ {
root %q;
default_type text/plain;
disable_symlinks on;
limit_except GET { deny all; }
try_files $uri =404;
}
`, filepath.ToSlash(root)), nil
}