-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebui_api.go
More file actions
266 lines (232 loc) · 8.1 KB
/
Copy pathwebui_api.go
File metadata and controls
266 lines (232 loc) · 8.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
/*
File: webui_api.go
Version: 1.5.0
Updated: 22-Jun-2026 15:36 CEST
Description:
JSON API endpoints for the sdproxy web UI.
Extracted from webui.go.
Changes:
1.5.0 - [SECURITY/FIX] Addressed a Memory Exhaustion (OOM) vector against the
`/api/set` endpoint natively. Deployed `http.MaxBytesReader` to strictly
cap authenticated streams to 32KB, ensuring malicious users or compromised
tokens cannot freeze the router's memory allocations organically.
1.4.0 - [FEAT] Implemented `handleApiGroups` endpoint to securely return
pre-rendered HTML payloads for the Desktop and Mobile group layouts,
driving the seamless AJAX refresh feature in the Web UI natively.
1.3.0 - [SECURITY/FIX] Eliminated a Slow-Read Denial of Service vulnerability
against the `/api/logs` streaming endpoint. Dynamically injected an
`http.ResponseController` to lift the `WriteTimeout` bounds strictly
for authenticated SSE clients, enabling the global DoH multiplexer
to enforce rigorous Drop-Deadlines securely against attackers.
*/
package main
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
// handleApiSet handles AJAX group-mode updates from the radio-click JS.
func handleApiSet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if !isAuthed(r) {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "unauthorized"})
return
}
if r.Method != http.MethodPost {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "method not allowed"})
return
}
// [SECURITY/FIX] Enforce strict payload boundaries on authenticated API endpoints natively.
// Prevents users or compromised tokens from executing memory exhaustion (OOM) attacks
// by transmitting massive arbitrary payloads to the group assignment form parser.
r.Body = http.MaxBytesReader(w, r.Body, 32*1024)
r.ParseForm()
group := r.FormValue("group")
mode := strings.ToUpper(r.FormValue("mode"))
durStr := r.FormValue("duration")
dur, _ := strconv.Atoi(durStr)
if group == "" {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "missing group"})
return
}
valid := map[string]bool{"DEFAULT": true, "LOG": true, "ALLOW": true, "FREE": true, "BLOCK": true, "CANCEL_TIMER": true}
if !valid[mode] {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "invalid mode"})
return
}
resultingMode := SetGroupOverride(group, mode, dur)
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "group": group, "mode": resultingMode, "duration": dur})
}
// handleApiStats returns a JSON StatsSnapshot. Auth required.
func handleApiStats(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(GetStats())
}
// handleApiReset completely zeroes out all analytical stats and histories. Auth required.
func handleApiReset(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ResetStats()
WebUILogStreamer.Clear()
SaveLogs() // Flushes blank slate cleanly over disk remnants
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
}
// handleApiLogs sends the live log stream over Server-Sent Events. Auth required.
// Reads ?limit=N from the query string to determine how many history lines to send.
func handleApiLogs(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
limitStr := r.URL.Query().Get("limit")
limit := 500 // Increased default to 500 to ensure clicked UI elements have historical context
if limitStr != "" {
if parsed, err := strconv.Atoi(limitStr); err == nil {
limit = parsed
}
}
if limit < 10 {
limit = 10
}
if limit > logRingSize {
limit = logRingSize
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
// [SECURITY/FIX] Disable WriteTimeout specifically for this SSE stream so
// long-lived active socket connections aren't aggressively severed by the
// global DoH Slow-Read HTTP server safeguards natively.
rc := http.NewResponseController(w)
_ = rc.SetWriteDeadline(time.Time{})
ch := make(chan string, limit)
WebUILogStreamer.mu.Lock()
count := len(WebUILogStreamer.ring)
if count > limit {
count = limit
}
history := make([]string, 0, count)
if len(WebUILogStreamer.ring) < logRingSize {
history = append(history, WebUILogStreamer.ring[len(WebUILogStreamer.ring)-count:]...)
} else {
startIdx := (WebUILogStreamer.ringIdx + logRingSize - count) % logRingSize
if startIdx < WebUILogStreamer.ringIdx {
history = append(history, WebUILogStreamer.ring[startIdx:WebUILogStreamer.ringIdx]...)
} else {
history = append(history, WebUILogStreamer.ring[startIdx:]...)
history = append(history, WebUILogStreamer.ring[:WebUILogStreamer.ringIdx]...)
}
}
WebUILogStreamer.clients[ch] = struct{}{}
WebUILogStreamer.mu.Unlock()
for _, line := range history {
for _, part := range strings.Split(line, "\n") {
fmt.Fprintf(w, "data: %s\n", part)
}
fmt.Fprintf(w, "\n")
}
flusher.Flush()
ctx := r.Context()
for {
select {
case <-ctx.Done():
WebUILogStreamer.mu.Lock()
delete(WebUILogStreamer.clients, ch)
WebUILogStreamer.mu.Unlock()
return
case line := <-ch:
for _, part := range strings.Split(line, "\n") {
fmt.Fprintf(w, "data: %s\n", part)
}
fmt.Fprintf(w, "\n")
flusher.Flush()
}
}
}
// RulesResponse encapsulates custom rules and available groups.
type RulesResponse struct {
Rules []CustomRule `json:"rules"`
Groups []string `json:"groups"`
}
func handleApiRulesGet(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
groups := []string{"global"}
for g := range cfg.Groups {
groups = append(groups, g)
}
sort.Strings(groups[1:])
resp := RulesResponse{
Rules: GetRules(),
Groups: groups,
}
json.NewEncoder(w).Encode(resp)
}
func handleApiRulesSet(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var newRules []CustomRule
// [SECURITY/FIX] Enforce 1MB payload boundary natively via MaxBytesReader to prevent
// memory exhaustion (OOM) attacks from authenticated sessions.
r.Body = http.MaxBytesReader(w, r.Body, 1*1024*1024)
if err := json.NewDecoder(r.Body).Decode(&newRules); err != nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"ok": false, "error": "invalid payload"})
return
}
SetRules(newRules)
SaveRules()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
}
// handleApiCacheGet dumps the live cache entries securely natively. Auth required.
func handleApiCacheGet(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(DumpCache())
}
// handleApiGroups returns pre-rendered HTML payloads for the Desktop and Mobile group layouts.
func handleApiGroups(w http.ResponseWriter, r *http.Request) {
if !isAuthed(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
desk, mob := buildGroupsHTML()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"desktop": desk,
"mobile": mob,
})
}