-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebui.go
More file actions
332 lines (293 loc) · 11.1 KB
/
webui.go
File metadata and controls
332 lines (293 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
File: webui.go
Version: 1.48.0 (Split)
Updated: 2026-04-18 12:05 CEST
Description:
Password-protected single-page web admin interface for sdproxy.
This file handles the HTTP server initialization, session authentication,
and embedded static assets.
Logic has been modularized into:
- webui_api.go (JSON endpoints)
- webui_html.go (HTML UI rendering)
- webui_state.go (Group override state)
- webui_logs.go (Live log streaming)
Changes:
1.48.0 - [SECURITY] Added comprehensive HTTP Security Response Headers (CSP, X-Frame-Options,
X-Content-Type-Options, Referrer-Policy, Permissions-Policy) to webUIMiddleware to
protect the browser context against XSS, clickjacking, and MIME-sniffing exploits.
1.47.0 - [FEAT] Integrated support for explicitly opting-out of the complete
Web UI via `cfg.WebUI.Enabled` false, halting API servers immediately.
1.46.0 - [LOGGING] Introduced extensive and debounced logging around WebUI
login attempts, successes, failures, and IP-lockouts, enabling
administrators to track brute-force attacks via standard logs.
*/
package main
import (
"crypto/rand"
"crypto/tls"
"encoding/hex"
"log"
"net"
"net/http"
"net/netip"
"strings"
"sync"
"time"
_ "embed"
)
// ---------------------------------------------------------------------------
// Embedded Static Assets
// ---------------------------------------------------------------------------
// uiScript is the minimal inline JS for the admin page.
// Compiled directly into the binary via go:embed for zero-I/O runtime performance.
//go:embed web/static/script.js
var uiScript string
// css is the complete inline stylesheet for every page the web UI renders.
// Compiled directly into the binary via go:embed.
//go:embed web/static/style.css
var css string
// ---------------------------------------------------------------------------
// Session management
// ---------------------------------------------------------------------------
const cookieName = "sdp_sess"
var (
sessToken string
sessExp time.Time
sessMu sync.Mutex
)
// newSession generates a fresh random 32-byte hex session token with an
// 8-hour expiry. One active session at a time — previous token is invalidated.
func newSession() string {
b := make([]byte, 32)
_, _ = rand.Read(b)
tok := hex.EncodeToString(b)
sessMu.Lock()
sessToken = tok
sessExp = time.Now().Add(8 * time.Hour)
sessMu.Unlock()
return tok
}
// isAuthed checks the request cookie against the current session token.
// Also allows stateless token-based authentication for robust /api/stats access.
func isAuthed(r *http.Request) bool {
// API Token Check (for /api/stats robust access)
if cfg.WebUI.APIToken != "" {
authHdr := r.Header.Get("Authorization")
if strings.HasPrefix(authHdr, "Bearer ") {
if authHdr[7:] == cfg.WebUI.APIToken {
return true
}
}
if r.URL.Query().Get("token") == cfg.WebUI.APIToken {
return true
}
}
c, err := r.Cookie(cookieName)
if err != nil {
return false
}
sessMu.Lock()
ok := c.Value == sessToken && sessToken != "" && time.Now().Before(sessExp)
sessMu.Unlock()
return ok
}
// ---------------------------------------------------------------------------
// HTTP server
// ---------------------------------------------------------------------------
// webUIMiddleware enforces HTTP Security Headers, HTTPS Redirection, and
// IP/Subnet-based ACLs. It also enforces Brute-Force mitigation, seamlessly
// blackholing locked-out IPs.
func webUIMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// ---------------------------------------------------------------------------
// Security Response Headers
// ---------------------------------------------------------------------------
// Protects the admin interface against Clickjacking, MIME-sniffing, XSS, and Data Exfiltration.
// Note: CSP 'unsafe-inline' is structurally required here because all UI components,
// stylesheets, and scripts are embedded natively within the Go binary templates.
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self';")
w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=(), payment=()")
// HSTS (Strict-Transport-Security)
if r.TLS != nil {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
// ---------------------------------------------------------------------------
// IP Identification for ACL and Brute-Force Lockout
// ---------------------------------------------------------------------------
ipStr, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ipStr = r.RemoteAddr // fallback to raw string if no port is present
}
// ---------------------------------------------------------------------------
// Brute-Force Lockout Check (Public Resolver Hardening)
// ---------------------------------------------------------------------------
// If an IP is currently locked out due to too many failed login attempts, we
// drop the connection entirely without interacting. By panicking with
// http.ErrAbortHandler, we instruct the underlying Go net/http server to
// abruptly sever the TCP connection without returning any HTTP headers or body.
loginStatesMu.Lock()
if state, exists := loginStates[ipStr]; exists && cfg.WebUI.LoginRatelimit.Enabled && state.attempts >= cfg.WebUI.LoginRatelimit.MaxAttempts {
if time.Now().After(state.lockoutExpires) {
// Lockout period has naturally expired; reset the attempts counter.
state.attempts = 0
log.Printf("[WEBUI] SECURITY: IP %s lockout expired. Access restored.", ipStr)
} else {
// Debounce the silent-drop log to once every 10 seconds per IP to prevent log floods.
if time.Since(state.lastDropLog) > 10*time.Second {
state.lastDropLog = time.Now()
log.Printf("[WEBUI] SECURITY: Silently dropping connection from %s (IP is locked out until %s)", ipStr, state.lockoutExpires.Format("15:04:05"))
}
loginStatesMu.Unlock()
// Silently drop the connection. This satisfies the requirement to "just drop
// the connection all together at connect-time, do not interact at all".
panic(http.ErrAbortHandler)
}
}
loginStatesMu.Unlock()
// ---------------------------------------------------------------------------
// HTTPS Redirection
// ---------------------------------------------------------------------------
if cfg.WebUI.ForceHTTPS && r.TLS == nil {
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
httpsPort := "443"
if len(cfg.WebUI.ListenHTTPS) > 0 {
_, p, _ := net.SplitHostPort(cfg.WebUI.ListenHTTPS[0])
if p != "" {
httpsPort = p
}
} else if len(cfg.Server.ListenDoH) > 0 {
_, p, _ := net.SplitHostPort(cfg.Server.ListenDoH[0])
if p != "" {
httpsPort = p
}
}
targetHost := host
if httpsPort != "443" {
targetHost = net.JoinHostPort(host, httpsPort)
}
targetURL := "https://" + targetHost + r.URL.RequestURI()
http.Redirect(w, r, targetURL, http.StatusMovedPermanently)
return
}
// ---------------------------------------------------------------------------
// Access Control List (ACL) Check
// ---------------------------------------------------------------------------
if err == nil && hasWebUIACL {
if addr, err := netip.ParseAddr(ipStr); err == nil {
addr = addr.Unmap()
// Deny rules take precedence over allow lists
for _, p := range webUIACLDeny {
if p.Contains(addr) {
http.Error(w, "Forbidden - ACL Deny", http.StatusForbidden)
return
}
}
// Allow rules verify boundary
if len(webUIACLAllow) > 0 {
allowed := false
for _, p := range webUIACLAllow {
if p.Contains(addr) {
allowed = true
break
}
}
if !allowed {
http.Error(w, "Forbidden - ACL Block", http.StatusForbidden)
return
}
}
}
}
next(w, r)
}
}
// WebUIMux is exported so server.go can safely multiplex Web UI routes onto DoH listeners.
var WebUIMux *http.ServeMux
// StartWebUI starts the admin HTTP/HTTPS servers. No-op when cfg.WebUI.Enabled is false.
func StartWebUI(tlsConf *tls.Config) {
if !cfg.WebUI.Enabled {
log.Println("[WEBUI] Disabled via config (webui.enabled: false).")
return
}
if cfg.WebUI.Password == "" {
log.Println("[WEBUI] No password configured — web UI disabled.")
return
}
WebUIMux = http.NewServeMux()
WebUIMux.HandleFunc("/", webUIMiddleware(handleRoot))
WebUIMux.HandleFunc("/login", webUIMiddleware(handleLogin))
WebUIMux.HandleFunc("/logout", webUIMiddleware(handleLogout))
WebUIMux.HandleFunc("/set", webUIMiddleware(handleSet))
WebUIMux.HandleFunc("/api/set", webUIMiddleware(handleApiSet))
WebUIMux.HandleFunc("/api/stats", webUIMiddleware(handleApiStats))
WebUIMux.HandleFunc("/api/reset", webUIMiddleware(handleApiReset))
WebUIMux.HandleFunc("/api/logs", webUIMiddleware(handleApiLogs))
// Resolve HTTP listeners
httpAddrs := cfg.WebUI.ListenHTTP
if len(httpAddrs) == 0 && cfg.WebUI.Listen != "" {
httpAddrs = []string{cfg.WebUI.Listen}
}
if len(httpAddrs) == 0 && len(cfg.WebUI.ListenHTTPS) == 0 {
httpAddrs = []string{"127.0.0.1:8080"}
}
// Dedicated HTTP servers
for _, addr := range httpAddrs {
addr := addr
go func() {
srv := &http.Server{
Addr: addr,
Handler: WebUIMux,
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 5 * time.Second, // Hardened
WriteTimeout: 5 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 4096,
}
log.Printf("[WEBUI] Admin UI (HTTP) at http://%s", addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[WEBUI] HTTP Server error on %s: %v", addr, err)
}
}()
}
// Dedicated HTTPS servers
for _, addr := range cfg.WebUI.ListenHTTPS {
addr := addr
// Check if DoH is already listening on this exact address
isDoH := false
for _, dAddr := range cfg.Server.ListenDoH {
if dAddr == addr {
isDoH = true
break
}
}
if isDoH {
log.Printf("[WEBUI] Admin UI (HTTPS) multiplexed natively on DoH listener at https://%s", addr)
continue
}
go func() {
// Restrict ALPN to HTTP-only tokens to avoid DoT/DoQ conflicts if reused
uiTLS := tlsConf.Clone()
uiTLS.NextProtos = []string{"h2", "http/1.1"}
srv := &http.Server{
Addr: addr,
Handler: WebUIMux,
TLSConfig: uiTLS,
ReadTimeout: 5 * time.Second,
ReadHeaderTimeout: 5 * time.Second, // Hardened
WriteTimeout: 5 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 4096,
}
log.Printf("[WEBUI] Admin UI (HTTPS) at https://%s", addr)
if err := srv.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
log.Printf("[WEBUI] HTTPS Server error on %s: %v", addr, err)
}
}()
}
}