-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunder.go
More file actions
309 lines (263 loc) · 6.49 KB
/
under.go
File metadata and controls
309 lines (263 loc) · 6.49 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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/mitchellh/go-ps"
_ "github.com/go-sql-driver/mysql"
)
type Config struct {
Domain string
ApiKey string
DbName string
DbUser string
DbPassword string
RuleID string
RulesetID string
}
type app struct {
conf Config
maxLoad float64
minLoad float64
maxProcs int
loadFile string
zoneId string
client *http.Client
baseURL string // override for testing; defaults to cloudflare base
}
func (a *app) loadConfig(fn string) error {
f, err := os.Open(fn)
if err != nil {
return err
}
defer f.Close()
return json.NewDecoder(f).Decode(&a.conf)
}
func loadAvg(text string) ([]float64, error) {
var res []float64
fields := strings.Fields(text)
if len(fields) < 4 {
return nil, errors.New("empty number")
}
for i, field := range fields {
f, err := strconv.ParseFloat(field, 64)
if err != nil {
return nil, err
}
res = append(res, f)
if i >= 2 {
break
}
}
return res, nil
}
func (a *app) init() error {
zoneResp, err := a.NewRequest("GET", a.baseURL+"/zones", nil)
if err != nil {
return err
}
resp, err := a.client.Do(zoneResp)
if err != nil {
return err
}
defer resp.Body.Close()
var data struct {
Result []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"result"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return err
}
for _, z := range data.Result {
if z.Name == a.conf.Domain {
a.zoneId = z.ID
return nil
}
}
return errors.New("zone ID not found for domain " + a.conf.Domain)
}
func countProcesses(pattern string) (int, error) {
procs, err := ps.Processes()
if err != nil {
return 0, err
}
n := 0
for _, proc := range procs {
if proc.Executable() == pattern {
n++
}
}
return n, nil
}
func (a *app) NewRequest(method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+a.conf.ApiKey)
req.Header.Set("Content-Type", "application/json")
return req, nil
}
// getRuleState fetches the current enabled state of the rule
func (a *app) getRuleState() (bool, error) {
url := fmt.Sprintf(a.baseURL+"/zones/%s/rulesets/%s",
a.zoneId, a.conf.RulesetID)
req, err := a.NewRequest("GET", url, nil)
if err != nil {
return false, err
}
resp, err := a.client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return false, fmt.Errorf("Cloudflare API returned HTTP %d: %s", resp.StatusCode, respBody)
}
var data struct {
Result struct {
Rules []struct {
ID string `json:"id"`
Enabled bool `json:"enabled"`
} `json:"rules"`
} `json:"result"`
}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return false, err
}
for _, rule := range data.Result.Rules {
if rule.ID == a.conf.RuleID {
return rule.Enabled, nil
}
}
return false, errors.New("rule not found in ruleset")
}
func (a *app) setRuleEnabled(enable bool) error {
// Check current state only when we need to make a change
currentState, err := a.getRuleState()
if err != nil {
log.Printf("Warning: could not fetch current rule state: %v", err)
log.Println("Proceeding with rule update anyway...")
} else if currentState == enable {
return nil
}
url := fmt.Sprintf(a.baseURL+"/zones/%s/rulesets/%s/rules/%s", a.zoneId, a.conf.RulesetID, a.conf.RuleID)
payload := map[string]any{
"action": "managed_challenge",
"description": "Bot check",
"enabled": enable,
"expression": "http.request.uri.path contains \"/articles/\" and http.request.method eq \"GET\" and not cf.client.bot and not http.cookie contains \"wordpress_logged_in\"",
}
body, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := a.NewRequest("PATCH", url, bytes.NewBuffer(body))
if err != nil {
return err
}
resp, err := a.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("Cloudflare API returned HTTP %d: %s", resp.StatusCode, respBody)
}
log.Printf("Successfully %s bot check rule", map[bool]string{true: "enabled", false: "disabled"}[enable])
return nil
}
func newApp() *app {
return &app{
client: http.DefaultClient,
baseURL: "https://api.cloudflare.com/client/v4",
}
}
func main() {
a := newApp()
log.SetFlags(log.LstdFlags)
cf := flag.String("config", "/etc/botCheck.conf", "config file")
flag.Float64Var(&a.maxLoad, "maxLoad", 4.5, "max load before enabling bot check rule")
flag.Float64Var(&a.minLoad, "minLoad", 1.0, "disable bot check rule if load is this low")
flag.IntVar(&a.maxProcs, "maxProc", 20, "max number of lsphp processes we allow to run")
flag.StringVar(&a.loadFile, "loadFile", "/proc/loadavg", "location of loadavg proc file")
flag.Parse()
if err := a.loadConfig(*cf); err != nil {
log.Fatalln(err)
}
if err := a.init(); err != nil {
log.Fatalln(err)
}
a.doIt()
}
func (a *app) doIt() {
text, err := os.ReadFile(a.loadFile)
if err != nil {
log.Fatalln(err)
}
la, err := loadAvg(string(text))
if err != nil {
log.Fatalln(err)
}
err = a.checkDb()
if err != nil {
log.Println("cannot connect to db:", err)
log.Println("enabling Cloudflare bot check rule due to DB failure")
err := a.setRuleEnabled(true)
if err != nil {
log.Fatalln("Failed to enable bot check rule:", err)
}
return
}
lsphpCount, err := countProcesses("lsphp")
if err != nil {
log.Println("Warning: could not count lsphp processes:", err)
} else {
if lsphpCount > a.maxProcs {
log.Println("lsphp count:", lsphpCount, "- enabling bot check rule")
err := a.setRuleEnabled(true)
if err != nil {
log.Fatalln("Failed to enable bot check rule:", err)
}
return
}
}
if la[0] >= a.maxLoad {
log.Println("Load average is", la, "enabling bot check rule")
err := a.setRuleEnabled(true)
if err != nil {
log.Fatalln("Failed to enable bot check rule:", err)
}
return
}
if allBelow(la, a.minLoad) {
// log.Println("Load average is below threshold, disabling bot check rule")
err := a.setRuleEnabled(false)
if err != nil {
log.Fatalln("Below threshold but failed to disable bot check rule:", err)
}
return
}
}
func allBelow(a []float64, x float64) bool {
for _, v := range a {
if v >= x {
return false
}
}
return true
}