672 lines
27 KiB
Go
672 lines
27 KiB
Go
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
|
|
}
|