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 = `