miaopanel
1// Package webserver renders and applies nginx configuration for managed sites.
2//
3// Design rule: a site's server block is generated once and never rewritten by
4// regular expressions. Every feature (ssl, limits, headers, proxy, waf) lives
5// in its own numbered fragment so enabling or disabling it is a file write,
6// which keeps rollbacks trivial.
7package webserver
8
9import (
10 "fmt"
11 "path/filepath"
12 "sort"
13 "strconv"
14 "strings"
15
16 "github.com/miaopanel/miaopanel/internal/config"
17 "github.com/miaopanel/miaopanel/internal/store"
18)
19
20// Render is the set of file mutations needed to make a site match its row.
21type Render struct {
22 Files map[string][]byte
23 Remove []string
24 // Keep lists files that are only created when they do not exist yet. The
25 // rewrite and ACME snippets are operator owned: rendering a site must
26 // never replace them (a restart used to wipe every saved rewrite rule).
27 Keep []string
28}
29
30func (r *Render) add(path, content string) {
31 if r.Files == nil {
32 r.Files = map[string][]byte{}
33 }
34 r.Files[path] = []byte(content)
35}
36
37func (r *Render) del(path string) {
38 r.Remove = append(r.Remove, path)
39}
40
41func (r *Render) keep(path string) {
42 r.Keep = append(r.Keep, path)
43}
44
45// RenderSite computes every configuration file of a site. The global WAF
46// configuration is passed in so the renderer stays pure and unit testable.
47func RenderSite(cfg *config.Config, s *store.Site, waf WAFConfig) *Render {
48 r := &Render{}
49 ext := cfg.ExtensionDir(s.Slug)
50 domains := s.Domains
51 if len(domains) == 0 {
52 domains = []string{"_"}
53 }
54 serverName := strings.Join(domains, " ")
55 // Application sites still listen on 80; a PHP/static site can opt into a
56 // dedicated public port (phpMyAdmin is exposed on 16520 this way).
57 httpPort := 80
58 if s.Options.ListenPort > 0 {
59 httpPort = s.Options.ListenPort
60 }
61
62 var b strings.Builder
63 b.WriteString("# managed by MiaoPanel - manual changes are overwritten\n")
64 gateway := gatewayMode(s, waf)
65 if s.SSLEnabled && s.Options.HTTPSRedirect {
66 // A dedicated HTTP server block is the only loop free way to redirect.
67 // The ACME location must stay reachable, otherwise renewals fail once
68 // force-HTTPS is enabled.
69 fmt.Fprintf(&b, "server {\n listen %d;\n server_name %s;\n", httpPort, serverName)
70 fmt.Fprintf(&b, " location ^~ /.well-known/acme-challenge/ {\n root %s;\n default_type text/plain;\n }\n", s.Root)
71 b.WriteString(" location / { return 301 https://$host$request_uri; }\n}\n\n")
72 }
73 b.WriteString("server {\n")
74 if s.SSLEnabled {
75 if !s.Options.HTTPSRedirect {
76 // Keep serving plain HTTP so ACME challenges and existing HTTP
77 // links keep working; both listeners share one server block.
78 fmt.Fprintf(&b, " listen %d;\n", httpPort)
79 }
80 b.WriteString(" listen 443 ssl http2;\n")
81 b.WriteString(" ssl_certificate " + filepath.Join(cfg.Nginx.CertDir, s.Slug, "fullchain.pem") + ";\n")
82 b.WriteString(" ssl_certificate_key " + filepath.Join(cfg.Nginx.CertDir, s.Slug, "privkey.pem") + ";\n")
83 } else {
84 // For application sites Port is the upstream port, never the public
85 // listener: nginx must own the public port and proxy to 127.0.0.1:Port.
86 fmt.Fprintf(&b, " listen %d;\n", httpPort)
87 }
88 fmt.Fprintf(&b, " server_name %s;\n", serverName)
89 fmt.Fprintf(&b, " root %s;\n", s.Root)
90 b.WriteString(" index " + indexFor(s) + ";\n")
91 b.WriteString(" client_max_body_size 100m;\n\n")
92 fmt.Fprintf(&b, " include %s;\n", filepath.Join(cfg.Nginx.VhostDir, "common", "sensitive.conf"))
93 if gateway {
94 // The edge keeps TLS, L1 rules, IP control and headers. Everything that
95 // touches the request (php, proxy, rewrite, anti-leech, custom) moves
96 // to the loopback origin so the gateway can inspect it first.
97 for _, frag := range edgeFragments(s, waf) {
98 fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, frag))
99 }
100 fmt.Fprintf(&b, " include %s;\n", cfg.WellKnownPath(s.Slug))
101 b.WriteString("\n location / {\n")
102 fmt.Fprintf(&b, " proxy_pass http://%s;\n", waf.GatewayAddr)
103 b.WriteString(" proxy_http_version 1.1;\n")
104 b.WriteString(" proxy_set_header Host $host;\n")
105 b.WriteString(" proxy_set_header X-Real-IP $remote_addr;\n")
106 b.WriteString(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n")
107 b.WriteString(" proxy_set_header X-Forwarded-Proto $scheme;\n")
108 fmt.Fprintf(&b, " proxy_set_header X-MP-Site %s;\n", s.Slug)
109 fmt.Fprintf(&b, " proxy_set_header X-MP-Origin 127.0.0.1:%d;\n", s.Options.GatewayPort)
110 b.WriteString(" proxy_set_header X-MP-Proxy 1;\n")
111 b.WriteString(" proxy_set_header Upgrade $http_upgrade;\n")
112 b.WriteString(" proxy_set_header Connection $connection_upgrade;\n")
113 b.WriteString(" proxy_connect_timeout 10s;\n")
114 b.WriteString(" proxy_read_timeout 300s;\n")
115 b.WriteString(" proxy_send_timeout 300s;\n")
116 b.WriteString(" proxy_request_buffering on;\n")
117 b.WriteString(" client_max_body_size 100m;\n")
118 b.WriteString(" }\n\n")
119 } else {
120 fmt.Fprintf(&b, " include %s/*.conf;\n", ext)
121 fmt.Fprintf(&b, " include %s;\n", cfg.WellKnownPath(s.Slug))
122 fmt.Fprintf(&b, " include %s;\n\n", cfg.RewritePath(s.Slug))
123 }
124 fmt.Fprintf(&b, " access_log %s mp_main;\n", filepath.Join(cfg.SiteLogDir(s.Slug), "access.log"))
125 fmt.Fprintf(&b, " error_log %s warn;\n", filepath.Join(cfg.SiteLogDir(s.Slug), "error.log"))
126 b.WriteString("}\n")
127 r.add(cfg.SiteConfPath(s.Slug), b.String())
128
129 // 10-ssl.conf ---------------------------------------------------------
130 if s.SSLEnabled {
131 var ssl strings.Builder
132 ssl.WriteString("# TLS hardening\n")
133 ssl.WriteString("ssl_protocols TLSv1.2 TLSv1.3;\n")
134 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")
135 ssl.WriteString("ssl_prefer_server_ciphers off;\n")
136 ssl.WriteString("ssl_session_cache shared:MPSSL:20m;\nssl_session_timeout 1d;\nssl_session_tickets off;\n")
137 ssl.WriteString("ssl_stapling on;\nssl_stapling_verify on;\n")
138 if s.Options.HSTS {
139 ssl.WriteString(`add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;` + "\n")
140 }
141 r.add(filepath.Join(ext, "10-ssl.conf"), ssl.String())
142 } else {
143 r.del(filepath.Join(ext, "10-ssl.conf"))
144 }
145
146 // 30-limit.conf -------------------------------------------------------
147 if s.Options.ConnPerIP > 0 || s.Options.ConnPerServer > 0 || s.Options.LimitRate > 0 {
148 var lim strings.Builder
149 lim.WriteString("# connection and bandwidth limits\n")
150 if s.Options.ConnPerIP > 0 {
151 fmt.Fprintf(&lim, "limit_conn mp_conn %d;\n", s.Options.ConnPerIP)
152 }
153 if s.Options.ConnPerServer > 0 {
154 fmt.Fprintf(&lim, "limit_conn mp_srv %d;\n", s.Options.ConnPerServer)
155 }
156 if s.Options.LimitRate > 0 {
157 fmt.Fprintf(&lim, "limit_rate %dk;\n", s.Options.LimitRate)
158 }
159 r.add(filepath.Join(ext, "30-limit.conf"), lim.String())
160 } else {
161 r.del(filepath.Join(ext, "30-limit.conf"))
162 }
163
164 // 35-waf.conf ---------------------------------------------------------
165 if waf.active(s) {
166 r.add(filepath.Join(ext, "35-waf.conf"), wafFragment(s, waf))
167 } else {
168 r.del(filepath.Join(ext, "35-waf.conf"))
169 }
170
171 // 40-headers.conf -----------------------------------------------------
172 if s.Options.SecurityHead {
173 var h strings.Builder
174 h.WriteString("# security response headers\n")
175 h.WriteString("add_header X-Content-Type-Options nosniff always;\n")
176 h.WriteString("add_header X-Frame-Options SAMEORIGIN always;\n")
177 h.WriteString("add_header Referrer-Policy strict-origin-when-cross-origin always;\n")
178 h.WriteString("add_header Permissions-Policy \"geolocation=(), microphone=(), camera=()\" always;\n")
179 r.add(filepath.Join(ext, "40-headers.conf"), h.String())
180 } else {
181 r.del(filepath.Join(ext, "40-headers.conf"))
182 }
183
184 // 50-ip.conf ----------------------------------------------------------
185 if s.Options.IPMode != "" && len(s.Options.IPList) > 0 {
186 var ip strings.Builder
187 ip.WriteString("# ip access control\n")
188 switch s.Options.IPMode {
189 case "allow":
190 for _, v := range s.Options.IPList {
191 fmt.Fprintf(&ip, "allow %s;\n", v)
192 }
193 ip.WriteString("deny all;\n")
194 case "deny":
195 for _, v := range s.Options.IPList {
196 fmt.Fprintf(&ip, "deny %s;\n", v)
197 }
198 }
199 r.add(filepath.Join(ext, "50-ip.conf"), ip.String())
200 } else {
201 r.del(filepath.Join(ext, "50-ip.conf"))
202 }
203
204 // 60-anti-leech.conf --------------------------------------------------
205 if s.Options.AntiLeak {
206 hosts := s.Options.AntiLeakHosts
207 if len(hosts) == 0 {
208 hosts = s.Domains
209 }
210 var al strings.Builder
211 al.WriteString("# anti leech\nlocation ~* \\.(gif|jpg|jpeg|png|bmp|webp|svg|ico|mp4|flv|swf)$ {\n")
212 al.WriteString(" expires 30d;\n access_log /dev/null;\n")
213 fmt.Fprintf(&al, " valid_referers none blocked %s;\n", strings.Join(hosts, " "))
214 al.WriteString(" if ($invalid_referer) { return 403; }\n}\n")
215 r.add(filepath.Join(ext, "60-anti-leech.conf"), al.String())
216 } else {
217 r.del(filepath.Join(ext, "60-anti-leech.conf"))
218 }
219
220 // 70-proxy.conf -------------------------------------------------------
221 if isApp(s.Kind) {
222 r.add(filepath.Join(ext, "70-proxy.conf"), proxyFragment(s))
223 } else {
224 r.del(filepath.Join(ext, "70-proxy.conf"))
225 }
226 if s.Kind == "php" {
227 r.add(filepath.Join(ext, "20-php.conf"), phpFragment(s, cfg))
228 } else {
229 r.del(filepath.Join(ext, "20-php.conf"))
230 }
231
232 // 90-custom.conf ------------------------------------------------------
233 if strings.TrimSpace(s.Options.Custom) != "" {
234 r.add(filepath.Join(ext, "90-custom.conf"), "# user custom\n"+s.Options.Custom+"\n")
235 } else {
236 r.del(filepath.Join(ext, "90-custom.conf"))
237 }
238
239 // Loopback origin for the deep inspection gateway. It carries the request
240 // handling directives that must run after inspection; the public block only
241 // terminates TLS and proxies to the gateway.
242 if gateway {
243 r.add(cfg.OriginConfPath(s.Slug), originConf(cfg, s, serverName))
244 } else {
245 r.del(cfg.OriginConfPath(s.Slug))
246 }
247
248 // Files that must exist so that includes never fail, but whose content
249 // belongs to the operator (rewrite rules, ACME challenge files). They are
250 // only written when absent; Apply skips them when they already exist.
251 r.addIfMissing(cfg.RewritePath(s.Slug), "# rewrite rules (editable)\n")
252 r.keep(cfg.RewritePath(s.Slug))
253 r.addIfMissing(cfg.WellKnownPath(s.Slug), "# acme challenge include\n")
254 r.keep(cfg.WellKnownPath(s.Slug))
255
256 sort.Strings(r.Remove)
257 return r
258}
259
260func gatewayMode(s *store.Site, waf WAFConfig) bool {
261 return waf.Gateway && waf.GatewayAddr != "" && s.Options.GatewayPort > 0 && waf.active(s)
262}
263
264// edgeFragments lists the fragments safe to keep in front of the gateway.
265func edgeFragments(s *store.Site, waf WAFConfig) []string {
266 var out []string
267 if s.SSLEnabled {
268 out = append(out, "10-ssl.conf")
269 }
270 if s.Options.ConnPerIP > 0 || s.Options.ConnPerServer > 0 || s.Options.LimitRate > 0 {
271 out = append(out, "30-limit.conf")
272 }
273 if waf.active(s) {
274 out = append(out, "35-waf.conf")
275 }
276 if s.Options.SecurityHead {
277 out = append(out, "40-headers.conf")
278 }
279 if s.Options.IPMode != "" && len(s.Options.IPList) > 0 {
280 out = append(out, "50-ip.conf")
281 }
282 return out
283}
284
285func originConf(cfg *config.Config, s *store.Site, serverName string) string {
286 ext := cfg.ExtensionDir(s.Slug)
287 var b strings.Builder
288 b.WriteString("# managed by MiaoPanel - loopback origin behind the WAF gateway\n")
289 b.WriteString("server {\n")
290 fmt.Fprintf(&b, " listen 127.0.0.1:%d;\n", s.Options.GatewayPort)
291 fmt.Fprintf(&b, " server_name %s;\n", serverName)
292 fmt.Fprintf(&b, " root %s;\n", s.Root)
293 fmt.Fprintf(&b, " index %s;\n", indexFor(s))
294 b.WriteString(" client_max_body_size 100m;\n")
295 b.WriteString(" access_log off;\n")
296 fmt.Fprintf(&b, " error_log %s warn;\n\n", filepath.Join(cfg.SiteLogDir(s.Slug), "error.log"))
297 fmt.Fprintf(&b, " include %s;\n", filepath.Join(cfg.Nginx.VhostDir, "common", "sensitive.conf"))
298 if s.Kind == "php" {
299 fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "20-php.conf"))
300 }
301 if isApp(s.Kind) {
302 fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "70-proxy.conf"))
303 } else {
304 b.WriteString(" location / {\n try_files $uri $uri/ =404;\n }\n")
305 }
306 if s.Options.AntiLeak {
307 fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "60-anti-leech.conf"))
308 }
309 if strings.TrimSpace(s.Options.Custom) != "" {
310 fmt.Fprintf(&b, " include %s;\n", filepath.Join(ext, "90-custom.conf"))
311 }
312 fmt.Fprintf(&b, " include %s;\n", cfg.RewritePath(s.Slug))
313 b.WriteString("}\n")
314 return b.String()
315}
316
317func (r *Render) addIfMissing(path, content string) {
318 if _, ok := r.Files[path]; !ok {
319 r.add(path, content)
320 }
321}
322
323func indexFor(s *store.Site) string {
324 switch s.Kind {
325 case "php":
326 return "index.php index.html index.htm"
327 case "go", "node", "proxy":
328 return "index.html index.htm"
329 default:
330 return "index.html index.htm"
331 }
332}
333
334func isApp(kind string) bool { return kind == "go" || kind == "node" || kind == "proxy" }
335
336func upstreamOf(s *store.Site) string {
337 if s.Upstream != "" {
338 return s.Upstream
339 }
340 port := s.Port
341 if port == 0 {
342 port = 80
343 }
344 return "http://127.0.0.1:" + strconv.Itoa(port)
345}
346
347func proxyFragment(s *store.Site) string {
348 var b strings.Builder
349 b.WriteString("# application upstream\n")
350 b.WriteString("location / {\n")
351 fmt.Fprintf(&b, " proxy_pass %s;\n", upstreamOf(s))
352 b.WriteString(" proxy_http_version 1.1;\n")
353 b.WriteString(" proxy_set_header Host $host;\n")
354 b.WriteString(" proxy_set_header X-Real-IP $remote_addr;\n")
355 b.WriteString(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n")
356 b.WriteString(" proxy_set_header X-Forwarded-Proto $scheme;\n")
357 b.WriteString(" proxy_set_header Upgrade $http_upgrade;\n")
358 b.WriteString(" proxy_set_header Connection $connection_upgrade;\n")
359 b.WriteString(" proxy_connect_timeout 10s;\n")
360 b.WriteString(" proxy_read_timeout 300s;\n")
361 b.WriteString(" proxy_send_timeout 300s;\n")
362 b.WriteString(" client_max_body_size 100m;\n")
363 b.WriteString("}\n")
364 return b.String()
365}
366
367func phpFragment(s *store.Site, cfg *config.Config) string {
368 ver := s.PHPVersion
369 if ver == "" {
370 ver = "8.2"
371 }
372 sock := "/run/php/php" + ver + "-fpm.sock"
373 if fileExists("/tmp/php-cgi-" + ver + ".sock") {
374 sock = "/tmp/php-cgi-" + ver + ".sock"
375 } else if !fileExists(sock) && fileExists("/run/php-fpm/www.sock") {
376 // Remi (RHEL) uses a single php-fpm socket instead of per-version paths.
377 sock = "/run/php-fpm/www.sock"
378 }
379 var b strings.Builder
380 b.WriteString("# php-fpm (params are inlined so no distro include is required)\n")
381 b.WriteString("location ~ [^/]\\.php(/|$) {\n")
382 b.WriteString(" try_files $uri =404;\n")
383 fmt.Fprintf(&b, " fastcgi_pass unix:%s;\n", sock)
384 b.WriteString(" fastcgi_index index.php;\n")
385 b.WriteString(" fastcgi_read_timeout 300s;\n")
386 b.WriteString(" fastcgi_buffer_size 64k;\n")
387 b.WriteString(" fastcgi_buffers 8 64k;\n")
388 b.WriteString(" fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n")
389 b.WriteString(" fastcgi_param PATH_INFO $fastcgi_path_info;\n")
390 b.WriteString(fastcgiParams)
391 b.WriteString("}\n")
392 b.WriteString("location ~ /\\.(?!well-known).* { deny all; }\n")
393 return b.String()
394}
395
396// fastcgiParams mirrors the CGI contract php-fpm expects. They are emitted
397// inline so the panel never depends on a distribution specific include file.
398const fastcgiParams = ` fastcgi_param QUERY_STRING $query_string;
399 fastcgi_param REQUEST_METHOD $request_method;
400 fastcgi_param CONTENT_TYPE $content_type;
401 fastcgi_param CONTENT_LENGTH $content_length;
402 fastcgi_param SCRIPT_NAME $fastcgi_script_name;
403 fastcgi_param REQUEST_URI $request_uri;
404 fastcgi_param DOCUMENT_URI $document_uri;
405 fastcgi_param DOCUMENT_ROOT $document_root;
406 fastcgi_param SERVER_PROTOCOL $server_protocol;
407 fastcgi_param REQUEST_SCHEME $scheme;
408 fastcgi_param HTTPS $https if_not_empty;
409 fastcgi_param GATEWAY_INTERFACE CGI/1.1;
410 fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
411 fastcgi_param REMOTE_ADDR $remote_addr;
412 fastcgi_param REMOTE_PORT $remote_port;
413 fastcgi_param SERVER_ADDR $server_addr;
414 fastcgi_param SERVER_PORT $server_port;
415 fastcgi_param SERVER_NAME $server_name;
416`
417
418// sensitiveFiles is the shared block included by every site.
419const sensitiveFiles = `# managed by MiaoPanel - shared hardening
420location ~* (\.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)$ {
421 return 404;
422}
423location ~* /(\.git|\.svn|\.idea|\.vscode|\.ssh|node_modules|vendor/bundle)/ {
424 return 404;
425}
426location ^~ /.mp-trash/ {
427 deny all;
428}
429# Panel owned helper files inside a document root (.mp-start.sh, upload
430# temporary files) must never be served.
431location ~ /\.mp- {
432 deny all;
433}
434location ^~ /.well-known/acme-challenge/ {
435 allow all;
436}
437`