361 lines
11 KiB
Go
361 lines
11 KiB
Go
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
|
|
}
|