250 lines
9.2 KiB
Go
250 lines
9.2 KiB
Go
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)
|
|
}
|