This repository has been archived by the owner on Oct 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconnfilter.go
371 lines (337 loc) · 10.9 KB
/
connfilter.go
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/jackc/pgx/v4"
"github.com/maxsupermanhd/lac/v2"
)
var (
rejectContactMsg = "You can contact Autohoster administration to appeal or get additional information: https://wz2100-autohost.net/about#contact\\n\\n"
)
// approve approvespec reject ban
func joinCheck(inst *instance, ip string, name string, pubkey []byte, pubkeyB64 string) (jd joinDispatch, action joinCheckActionLevel, reason string) {
jd.Issued = time.Now()
jd.Messages = []string{}
jd.AllowChat = true
action = joinCheckActionLevelApprove
// stage 1 adolf/spam protection
if stringContainsSlices(strings.ToLower(name), tryCfgGetD(tryGetSliceStringGen("blacklist", "name"), []string{}, inst.cfgs...)) {
ecode, err := DbLogAction("%d [adolfmeasures] Join name %s triggered adolf suppression system, ip was %s", inst.Id, name, ip)
if err != nil {
inst.logger.Printf("Failed to log action in database: %s", err.Error())
}
return jd, joinCheckActionLevelBan, "You were banned from joining Autohoster.\\n" +
"Ban reason: 4.1.7. Any manifestations of Nazism, nationalism, incitement " +
"of interracial, interethnic, interfaith discord and hostility, " +
"calls for the overthrow of the government by force.\\n\\n" + rejectContactMsg +
"Event ID: " + ecode
}
// stage 2 ban check
var (
account *int
banid *int
banissued *time.Time
banexpires *time.Time
banexpired *bool
banreason *string
forbids_joining *bool
forbids_playing *bool
forbids_chatting *bool
)
err := dbpool.QueryRow(context.Background(), `select
identities.account, bans.id, time_issued, time_expires, coalesce(time_expires < now(), 'false'), reason, forbids_joining, forbids_playing, forbids_chatting
from identities
left outer join bans on bans.identity = identities.id or bans.account = identities.account
where
identities.hash = encode(sha256($1), 'hex')
order by time_expires desc
limit 1`, pubkey).Scan(&account, &banid, &banissued, &banexpires, &banexpired, &banreason, &forbids_joining, &forbids_playing, &forbids_chatting)
if err != nil {
if !errors.Is(err, pgx.ErrNoRows) {
inst.logger.Printf("Failed to request bans from database: %s", err.Error())
}
}
if banid != nil {
if banexpired != nil && !*banexpired {
if *forbids_joining {
banexpiresstr := "never"
if banexpires != nil {
banexpiresstr = (*banexpires).String()
}
return jd, joinCheckActionLevelReject, "You were banned from joining Autohoster.\\n" +
"Ban reason: " + *banreason + "\\n\\n" + rejectContactMsg +
"Ban issued: " + (*banissued).String() + "\\n" +
"Ban expires: " + banexpiresstr + "\\n" +
"Event ID: M-" + strconv.Itoa(*banid)
}
if *forbids_chatting {
jd.Messages = append(jd.Messages, "You are banned from chatting in this room (ban ID: M-"+strconv.Itoa(*banid)+")")
jd.AllowChat = false
}
if *forbids_playing {
jd.Messages = append(jd.Messages, "You are banned from participating in this game (ban ID: M-"+strconv.Itoa(*banid)+")")
action = joinCheckActionLevelApproveSpec
}
}
}
// stage 3 isp check
if account == nil && !tryCfgGetD(tryGetBoolGen("allowNonLinkedHide"), false, inst.cfgs...) {
rsp, err := ISPchecker.Lookup(ip)
if err != nil {
inst.logger.Printf("Failed to lookup ISP: %s", err.Error())
} else {
isAsnBanned := checkASNbanned(rsp.ASN, inst.cfgs)
if rsp.IsProxy || isAsnBanned {
ecode, err := DbLogAction("%d [antiproxy] join attempt from %q did not pass isp checks: proxy %v asnban %v (ip was %v)", inst.Id, name, rsp.IsProxy, isAsnBanned, ip)
if err != nil {
inst.logger.Printf("Failed to log action in database: %s", err.Error())
}
return jd, joinCheckActionLevelReject, "You were rejected from joining Autohoster.\\n" +
"Reason: 2.1.1. Disruption or other interference with the system with or without defined purpose.\\n\\n" +
"If you believe it is a mistake, feel free to contact us: https://wz2100-autohost.net/about#contact\\n\\n" +
"Please provide event ID: " + ecode + " with your request."
}
}
}
// stage 4 check room prefs
allowNonLinkedJoin := tryCfgGetD(tryGetBoolGen("allowNonLinkedJoin"), true, inst.cfgs...)
if !allowNonLinkedJoin {
if account == nil {
return jd, joinCheckActionLevelReject, "You can not join this game.\\n\\n" +
"You must join with linked player identity. Link one at:\\n" +
"https://wz2100-autohost.net/wzlinkcheck\\n\\n" +
"Do not bother admins/moderators about this."
}
}
allowNonLinkedPlay := tryCfgGetD(tryGetBoolGen("allowNonLinkedPlay"), true, inst.cfgs...)
if !allowNonLinkedPlay {
if account == nil {
jd.Messages = append(jd.Messages, "You are not allowed to participate in this game due to being not registered")
action = joinCheckActionLevelApproveSpec
}
}
allowNonLinkedChat := tryCfgGetD(tryGetBoolGen("allowNonLinkedChat"), true, inst.cfgs...)
if !allowNonLinkedChat {
if account == nil {
jd.Messages = append(jd.Messages, "You are not allowed to chat in this room due to being not registered")
jd.Messages = append(jd.Messages, "Link your identity on https://wz2100-autohost.net/wzlinkcheck")
jd.AllowChat = false
}
}
// stage 5 rate limit checks
asThrCnt := tryCfgGetD(tryGetIntGen("antiSpamThresholdCount"), 3, inst.cfgs...)
asThrDur := tryCfgGetD(tryGetIntGen("antiSpamThresholdDuration"), 3*24, inst.cfgs...)
if asThrCnt > 0 {
rateLimitCounter := 0
dbpool.QueryRow(context.Background(), `select
count(g.id)
from games as g
join players as p on p.game = g.id
join identities as i on p.identity = i.id
left join accounts as a on i.account = a.id
where g.game_time < 60000 and g.time_started + $1::interval > now() and (i.pkey = $2 or a.id = coalesce($3, -1))`, fmt.Sprintf("%d hours", asThrDur), pubkey, account).Scan(&rateLimitCounter)
if rateLimitCounter >= asThrCnt {
if action == joinCheckActionLevelApprove {
jd.Messages = append(jd.Messages, "You were automatically rate limited for leaving the game early. Do not contact admins/moderators about this, they will not help you")
action = joinCheckActionLevelApproveSpec
}
}
}
// stage 6 moved out check
if joincheckWasMovedOutGlobal.present(pubkeyB64, inst.Id) {
if action == joinCheckActionLevelApprove {
jd.Messages = append(jd.Messages, "You not allowed to participate in the game because moderator moved you out earlier")
action = joinCheckActionLevelApproveSpec
}
}
// stage 7 ip based mute
if account == nil {
if checkIPMatchesConfigs(inst, ip, "ipmute") {
jd.AllowChat = false
}
}
// stage 7 ip based playfilter
if account == nil {
if checkIPMatchesConfigs(inst, ip, "ipnoplay") {
if action == joinCheckActionLevelApprove {
action = joinCheckActionLevelApproveSpec
}
}
}
// stage 6 terminated account
var terminated bool
dbpool.QueryRow(context.Background(), `select terminated
from accounts as a
join identities as i on i.account = a.id
where i.pkey = $1`, pubkey).Scan(&terminated)
if terminated {
if action == joinCheckActionLevelApprove {
jd.Messages = append(jd.Messages, "You not allowed to participate in the game because your account was terminated. Contact administration for more details.")
action = joinCheckActionLevelApproveSpec
}
}
inst.logger.Printf("connfilter resolved key %v nljoin %v (acc %v) nlplay %v (action %v) nlchat %v (allowed %v)",
pubkeyB64,
allowNonLinkedJoin, account,
allowNonLinkedPlay, action,
allowNonLinkedChat, jd.AllowChat,
)
return jd, action, ""
}
func checkIPMatchesConfigs(inst *instance, ip string, confpath ...string) bool {
clip := net.ParseIP(ip)
if clip == nil {
inst.logger.Printf("ipmatch invalid ip %q", ip)
return false
}
ipmatchs := map[string]bool{}
for i := len(inst.cfgs) - 1; i >= 0; i-- {
o, ok := inst.cfgs[i].GetKeys(confpath...)
if !ok {
continue
}
for _, k := range o {
s, ok := inst.cfgs[i].GetBool(append(confpath, k)...)
if !ok {
continue
}
if !s {
delete(ipmatchs, k)
} else {
ipmatchs[k] = s
}
}
}
for kip, v := range ipmatchs {
if !v {
continue
}
_, pnt, err := net.ParseCIDR(kip)
if err != nil {
inst.logger.Printf("ipmatch ip %q is not in CIDR notation: %s", kip, err)
continue
}
if pnt == nil {
inst.logger.Printf("ipmatch ip %q has no network after parsing", kip)
continue
}
if pnt.Contains(clip) {
inst.logger.Printf("ipmatch applied to client %q with rule %q", ip, kip)
return true
}
}
return false
}
type joinCheckActionLevel int
const (
joinCheckActionLevelApprove = iota
joinCheckActionLevelApproveSpec
joinCheckActionLevelReject
joinCheckActionLevelBan
)
func (l joinCheckActionLevel) String() string {
switch l {
case joinCheckActionLevelApprove:
return "joinCheckActionLevelApprove"
case joinCheckActionLevelApproveSpec:
return "joinCheckActionLevelApproveSpec"
case joinCheckActionLevelReject:
return "joinCheckActionLevelReject"
case joinCheckActionLevelBan:
return "joinCheckActionLevelBan"
default:
return "unknown?!"
}
}
type joincheckWasMovedOut struct {
m map[string][]int64
lock sync.Mutex
}
var joincheckWasMovedOutGlobal = joincheckWasMovedOut{
m: map[string][]int64{},
lock: sync.Mutex{},
}
func (j *joincheckWasMovedOut) _cleanup() {
keys := make([]string, 0, len(j.m))
for k := range j.m {
keys = append(keys, k)
}
for _, k := range keys {
v := j.m[k]
nv := slices.DeleteFunc(v, func(vv int64) bool {
return !isInstanceInLobby(vv)
})
if len(nv) == 0 {
delete(j.m, k)
continue
}
j.m[k] = nv
}
}
func (j *joincheckWasMovedOut) add(identity string, instance int64) {
j.lock.Lock()
defer j.lock.Unlock()
j._cleanup()
r, ok := j.m[identity]
if ok {
j.m[identity] = append(r, instance)
return
}
j.m[identity] = []int64{instance}
}
func (j *joincheckWasMovedOut) remove(identity string, instance int64) {
j.lock.Lock()
defer j.lock.Unlock()
j._cleanup()
r, ok := j.m[identity]
if ok {
if len(r) == 1 {
if r[0] == instance {
delete(j.m, identity)
}
} else {
j.m[identity] = slices.DeleteFunc(r, func(rr int64) bool {
return rr == instance
})
}
}
}
func (j *joincheckWasMovedOut) present(identity string, instance int64) bool {
j.lock.Lock()
defer j.lock.Unlock()
j._cleanup()
r, ok := j.m[identity]
if !ok {
return false
}
return slices.Contains(r, instance)
}
func checkASNbanned(asn string, cfgs []lac.Conf) bool {
for _, c := range cfgs {
sl, ok := c.GetSliceString("bannedASNs")
if ok {
if stringContainsSlices(asn, sl) {
return true
}
}
}
return false
}
func pubkeyDiscovery(pubkey []byte) {
tag, err := dbpool.Exec(context.Background(), `update identities set pkey = $1 where hash = encode(sha256($1), 'hex') and pkey is null`, pubkey)
if err != nil {
log.Printf("Key discovery query failed: %s", err.Error())
return
}
if !tag.Update() || tag.RowsAffected() > 1 {
log.Printf("Something went horribly wrong in key discovery, tag: %s", tag)
}
}