// Package webserver renders and applies nginx configuration for managed sites. // // Design rule: a site's server block is generated once and never rewritten by // regular expressions. Every feature (ssl, limits, headers, proxy, waf) lives // in its own numbered fragment so enabling or disabling it is a file write, // which keeps rollbacks trivial. package webserver import ( "fmt" "path/filepath" "sort" "strconv" "strings" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" ) // Render is the set of file mutations needed to make a site match its row. type Render struct { Files map[string][]byte Remove []string // Keep lists files that are only created when they do not exist yet. The // rewrite and ACME snippets are operator owned: rendering a site must // never replace them (a restart used to wipe every saved rewrite rule). Keep []string } func (r *Render) add(path, content string) { if r.Files == nil { r.Files = map[string][]byte{} } r.Files[path] = []byte(content) } func (r *Render) del(path string) { r.Remove = append(r.Remove, path) } func (r *Render) keep(path string) { r.Keep = append(r.Keep, path) } // RenderSite computes every configuration file of a site. The global WAF // configuration is passed in so the renderer stays pure and unit testable. func RenderSite(cfg *config.Config, s *store.Site, waf WAFConfig) *Render { r := &Render{} ext := cfg.ExtensionDir(s.Slug) domains := s.Domains if len(domains) == 0 { domains = []string{"_"} } serverName := strings.Join(domains, " ") // Application sites still listen on 80; a PHP/static site can opt into a // dedicated public port (phpMyAdmin is exposed on 16520 this way). httpPort := 80 if s.Options.ListenPort > 0 { httpPort = s.Options.ListenPort } var b strings.Builder b.WriteString("# managed by MiaoPanel - manual changes are overwritten\n") gateway := gatewayMode(s, waf) if s.SSLEnabled && s.Options.HTTPSRedirect { // A dedicated HTTP server block is the only loop free way to redirect. // The ACME location must stay reachable, otherwise renewals fail once // force-HTTPS is enabled. fmt.Fprintf(&b, "server {\n listen %d;\n server_name %s;\n", httpPort, serverName) fmt.Fprintf(&b, " location ^~ /.well-known/acme-challenge/ {\n root %s;\n default_type text/plain;\n }\n", s.Root) b.WriteString(" location / { return 301 https://$host$request_uri; }\n}\n\n") } b.WriteString("server {\n") if s.SSLEnabled { if !s.Options.HTTPSRedirect { // Keep serving plain HTTP so ACME challenges and existing HTTP // links keep working; both listeners share one server block. fmt.Fprintf(&b, " listen %d;\n", httpPort) } b.WriteString(" listen 443 ssl http2;\n") b.WriteString(" ssl_certificate " + filepath.Join(cfg.Nginx.CertDir, s.Slug, "fullchain.pem") + ";\n") b.WriteString(" ssl_certificate_key " + filepath.Join(cfg.Nginx.CertDir, s.Slug, "privkey.pem") + ";\n") } else { // For application sites Port is the upstream port, never the public // listener: nginx must own the public port and proxy to 127.0.0.1:Port. fmt.Fprintf(&b, " listen %d;\n", httpPort) } fmt.Fprintf(&b, " server_name %s;\n", serverName) fmt.Fprintf(&b, " root %s;\n", s.Root) b.WriteString(" index " + indexFor(s) + ";\n") b.WriteString(" client_max_body_size 100m;\n\n") fmt.Fprintf(&b, " include %s;\n", filepath.Join(cfg.Nginx.VhostDir, "common", "sensitive.conf")) if gateway { // The edge keeps TLS, L1 rules, IP control and headers. Everything that // touches the request (php, proxy, rewrite, anti-leech, custom) moves // to the loopback origin so the gateway can inspect it first. for _, frag := range edgeFragments(s, waf) { fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, frag)) } fmt.Fprintf(&b, " include %s;\n", cfg.WellKnownPath(s.Slug)) b.WriteString("\n location / {\n") fmt.Fprintf(&b, " proxy_pass http://%s;\n", waf.GatewayAddr) b.WriteString(" proxy_http_version 1.1;\n") b.WriteString(" proxy_set_header Host $host;\n") b.WriteString(" proxy_set_header X-Real-IP $remote_addr;\n") b.WriteString(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n") b.WriteString(" proxy_set_header X-Forwarded-Proto $scheme;\n") fmt.Fprintf(&b, " proxy_set_header X-MP-Site %s;\n", s.Slug) fmt.Fprintf(&b, " proxy_set_header X-MP-Origin 127.0.0.1:%d;\n", s.Options.GatewayPort) b.WriteString(" proxy_set_header X-MP-Proxy 1;\n") b.WriteString(" proxy_set_header Upgrade $http_upgrade;\n") b.WriteString(" proxy_set_header Connection $connection_upgrade;\n") b.WriteString(" proxy_connect_timeout 10s;\n") b.WriteString(" proxy_read_timeout 300s;\n") b.WriteString(" proxy_send_timeout 300s;\n") b.WriteString(" proxy_request_buffering on;\n") b.WriteString(" client_max_body_size 100m;\n") b.WriteString(" }\n\n") } else { fmt.Fprintf(&b, " include %s/*.conf;\n", ext) fmt.Fprintf(&b, " include %s;\n", cfg.WellKnownPath(s.Slug)) fmt.Fprintf(&b, " include %s;\n\n", cfg.RewritePath(s.Slug)) } fmt.Fprintf(&b, " access_log %s mp_main;\n", filepath.Join(cfg.SiteLogDir(s.Slug), "access.log")) fmt.Fprintf(&b, " error_log %s warn;\n", filepath.Join(cfg.SiteLogDir(s.Slug), "error.log")) b.WriteString("}\n") r.add(cfg.SiteConfPath(s.Slug), b.String()) // 10-ssl.conf --------------------------------------------------------- if s.SSLEnabled { var ssl strings.Builder ssl.WriteString("# TLS hardening\n") ssl.WriteString("ssl_protocols TLSv1.2 TLSv1.3;\n") ssl.WriteString("ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;\n") ssl.WriteString("ssl_prefer_server_ciphers off;\n") ssl.WriteString("ssl_session_cache shared:MPSSL:20m;\nssl_session_timeout 1d;\nssl_session_tickets off;\n") ssl.WriteString("ssl_stapling on;\nssl_stapling_verify on;\n") if s.Options.HSTS { ssl.WriteString(`add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;` + "\n") } r.add(filepath.Join(ext, "10-ssl.conf"), ssl.String()) } else { r.del(filepath.Join(ext, "10-ssl.conf")) } // 30-limit.conf ------------------------------------------------------- if s.Options.ConnPerIP > 0 || s.Options.ConnPerServer > 0 || s.Options.LimitRate > 0 { var lim strings.Builder lim.WriteString("# connection and bandwidth limits\n") if s.Options.ConnPerIP > 0 { fmt.Fprintf(&lim, "limit_conn mp_conn %d;\n", s.Options.ConnPerIP) } if s.Options.ConnPerServer > 0 { fmt.Fprintf(&lim, "limit_conn mp_srv %d;\n", s.Options.ConnPerServer) } if s.Options.LimitRate > 0 { fmt.Fprintf(&lim, "limit_rate %dk;\n", s.Options.LimitRate) } r.add(filepath.Join(ext, "30-limit.conf"), lim.String()) } else { r.del(filepath.Join(ext, "30-limit.conf")) } // 35-waf.conf --------------------------------------------------------- if waf.active(s) { r.add(filepath.Join(ext, "35-waf.conf"), wafFragment(s, waf)) } else { r.del(filepath.Join(ext, "35-waf.conf")) } // 40-headers.conf ----------------------------------------------------- if s.Options.SecurityHead { var h strings.Builder h.WriteString("# security response headers\n") h.WriteString("add_header X-Content-Type-Options nosniff always;\n") h.WriteString("add_header X-Frame-Options SAMEORIGIN always;\n") h.WriteString("add_header Referrer-Policy strict-origin-when-cross-origin always;\n") h.WriteString("add_header Permissions-Policy \"geolocation=(), microphone=(), camera=()\" always;\n") r.add(filepath.Join(ext, "40-headers.conf"), h.String()) } else { r.del(filepath.Join(ext, "40-headers.conf")) } // 50-ip.conf ---------------------------------------------------------- if s.Options.IPMode != "" && len(s.Options.IPList) > 0 { var ip strings.Builder ip.WriteString("# ip access control\n") switch s.Options.IPMode { case "allow": for _, v := range s.Options.IPList { fmt.Fprintf(&ip, "allow %s;\n", v) } ip.WriteString("deny all;\n") case "deny": for _, v := range s.Options.IPList { fmt.Fprintf(&ip, "deny %s;\n", v) } } r.add(filepath.Join(ext, "50-ip.conf"), ip.String()) } else { r.del(filepath.Join(ext, "50-ip.conf")) } // 60-anti-leech.conf -------------------------------------------------- if s.Options.AntiLeak { hosts := s.Options.AntiLeakHosts if len(hosts) == 0 { hosts = s.Domains } var al strings.Builder al.WriteString("# anti leech\nlocation ~* \\.(gif|jpg|jpeg|png|bmp|webp|svg|ico|mp4|flv|swf)$ {\n") al.WriteString(" expires 30d;\n access_log /dev/null;\n") fmt.Fprintf(&al, " valid_referers none blocked %s;\n", strings.Join(hosts, " ")) al.WriteString(" if ($invalid_referer) { return 403; }\n}\n") r.add(filepath.Join(ext, "60-anti-leech.conf"), al.String()) } else { r.del(filepath.Join(ext, "60-anti-leech.conf")) } // 70-proxy.conf ------------------------------------------------------- if isApp(s.Kind) { r.add(filepath.Join(ext, "70-proxy.conf"), proxyFragment(s)) } else { r.del(filepath.Join(ext, "70-proxy.conf")) } if s.Kind == "php" { r.add(filepath.Join(ext, "20-php.conf"), phpFragment(s, cfg)) } else { r.del(filepath.Join(ext, "20-php.conf")) } // 90-custom.conf ------------------------------------------------------ if strings.TrimSpace(s.Options.Custom) != "" { r.add(filepath.Join(ext, "90-custom.conf"), "# user custom\n"+s.Options.Custom+"\n") } else { r.del(filepath.Join(ext, "90-custom.conf")) } // Loopback origin for the deep inspection gateway. It carries the request // handling directives that must run after inspection; the public block only // terminates TLS and proxies to the gateway. if gateway { r.add(cfg.OriginConfPath(s.Slug), originConf(cfg, s, serverName)) } else { r.del(cfg.OriginConfPath(s.Slug)) } // Files that must exist so that includes never fail, but whose content // belongs to the operator (rewrite rules, ACME challenge files). They are // only written when absent; Apply skips them when they already exist. r.addIfMissing(cfg.RewritePath(s.Slug), "# rewrite rules (editable)\n") r.keep(cfg.RewritePath(s.Slug)) r.addIfMissing(cfg.WellKnownPath(s.Slug), "# acme challenge include\n") r.keep(cfg.WellKnownPath(s.Slug)) sort.Strings(r.Remove) return r } func gatewayMode(s *store.Site, waf WAFConfig) bool { return waf.Gateway && waf.GatewayAddr != "" && s.Options.GatewayPort > 0 && waf.active(s) } // edgeFragments lists the fragments safe to keep in front of the gateway. func edgeFragments(s *store.Site, waf WAFConfig) []string { var out []string if s.SSLEnabled { out = append(out, "10-ssl.conf") } if s.Options.ConnPerIP > 0 || s.Options.ConnPerServer > 0 || s.Options.LimitRate > 0 { out = append(out, "30-limit.conf") } if waf.active(s) { out = append(out, "35-waf.conf") } if s.Options.SecurityHead { out = append(out, "40-headers.conf") } if s.Options.IPMode != "" && len(s.Options.IPList) > 0 { out = append(out, "50-ip.conf") } return out } func originConf(cfg *config.Config, s *store.Site, serverName string) string { ext := cfg.ExtensionDir(s.Slug) var b strings.Builder b.WriteString("# managed by MiaoPanel - loopback origin behind the WAF gateway\n") b.WriteString("server {\n") fmt.Fprintf(&b, " listen 127.0.0.1:%d;\n", s.Options.GatewayPort) fmt.Fprintf(&b, " server_name %s;\n", serverName) fmt.Fprintf(&b, " root %s;\n", s.Root) fmt.Fprintf(&b, " index %s;\n", indexFor(s)) b.WriteString(" client_max_body_size 100m;\n") b.WriteString(" access_log off;\n") fmt.Fprintf(&b, " error_log %s warn;\n\n", filepath.Join(cfg.SiteLogDir(s.Slug), "error.log")) fmt.Fprintf(&b, " include %s;\n", filepath.Join(cfg.Nginx.VhostDir, "common", "sensitive.conf")) if s.Kind == "php" { fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "20-php.conf")) } if isApp(s.Kind) { fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "70-proxy.conf")) } else { b.WriteString(" location / {\n try_files $uri $uri/ =404;\n }\n") } if s.Options.AntiLeak { fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "60-anti-leech.conf")) } if strings.TrimSpace(s.Options.Custom) != "" { fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "90-custom.conf")) } fmt.Fprintf(&b, " include %s;\n", cfg.RewritePath(s.Slug)) b.WriteString("}\n") return b.String() } func (r *Render) addIfMissing(path, content string) { if _, ok := r.Files[path]; !ok { r.add(path, content) } } func indexFor(s *store.Site) string { switch s.Kind { case "php": return "index.php index.html index.htm" case "go", "node", "proxy": return "index.html index.htm" default: return "index.html index.htm" } } func isApp(kind string) bool { return kind == "go" || kind == "node" || kind == "proxy" } func upstreamOf(s *store.Site) string { if s.Upstream != "" { return s.Upstream } port := s.Port if port == 0 { port = 80 } return "http://127.0.0.1:" + strconv.Itoa(port) } func proxyFragment(s *store.Site) string { var b strings.Builder b.WriteString("# application upstream\n") b.WriteString("location / {\n") fmt.Fprintf(&b, " proxy_pass %s;\n", upstreamOf(s)) b.WriteString(" proxy_http_version 1.1;\n") b.WriteString(" proxy_set_header Host $host;\n") b.WriteString(" proxy_set_header X-Real-IP $remote_addr;\n") b.WriteString(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n") b.WriteString(" proxy_set_header X-Forwarded-Proto $scheme;\n") b.WriteString(" proxy_set_header Upgrade $http_upgrade;\n") b.WriteString(" proxy_set_header Connection $connection_upgrade;\n") b.WriteString(" proxy_connect_timeout 10s;\n") b.WriteString(" proxy_read_timeout 300s;\n") b.WriteString(" proxy_send_timeout 300s;\n") b.WriteString(" client_max_body_size 100m;\n") b.WriteString("}\n") return b.String() } func phpFragment(s *store.Site, cfg *config.Config) string { ver := s.PHPVersion if ver == "" { ver = "8.2" } sock := "/run/php/php" + ver + "-fpm.sock" if fileExists("/tmp/php-cgi-" + ver + ".sock") { sock = "/tmp/php-cgi-" + ver + ".sock" } else if !fileExists(sock) && fileExists("/run/php-fpm/www.sock") { // Remi (RHEL) uses a single php-fpm socket instead of per-version paths. sock = "/run/php-fpm/www.sock" } var b strings.Builder b.WriteString("# php-fpm (params are inlined so no distro include is required)\n") b.WriteString("location ~ [^/]\\.php(/|$) {\n") b.WriteString(" try_files $uri =404;\n") fmt.Fprintf(&b, " fastcgi_pass unix:%s;\n", sock) b.WriteString(" fastcgi_index index.php;\n") b.WriteString(" fastcgi_read_timeout 300s;\n") b.WriteString(" fastcgi_buffer_size 64k;\n") b.WriteString(" fastcgi_buffers 8 64k;\n") b.WriteString(" fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n") b.WriteString(" fastcgi_param PATH_INFO $fastcgi_path_info;\n") b.WriteString(fastcgiParams) b.WriteString("}\n") b.WriteString("location ~ /\\.(?!well-known).* { deny all; }\n") return b.String() } // fastcgiParams mirrors the CGI contract php-fpm expects. They are emitted // inline so the panel never depends on a distribution specific include file. const fastcgiParams = ` fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param REQUEST_SCHEME $scheme; fastcgi_param HTTPS $https if_not_empty; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; ` // sensitiveFiles is the shared block included by every site. const sensitiveFiles = `# managed by MiaoPanel - shared hardening location ~* (\.user\.ini|\.htaccess|\.htpasswd|\.env.*|\.gitignore|\.DS_Store|\.swp|\.swo|\.bak|\.old|\.log|\.sql(\.gz)?|docker-compose\.ya?ml|Dockerfile|go\.mod|go\.sum|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.(json|lock)|\.project)$ { return 404; } location ~* /(\.git|\.svn|\.idea|\.vscode|\.ssh|node_modules|vendor/bundle)/ { return 404; } location ^~ /.mp-trash/ { deny all; } # Panel owned helper files inside a document root (.mp-start.sh, upload # temporary files) must never be served. location ~ /\.mp- { deny all; } location ^~ /.well-known/acme-challenge/ { allow all; } `