-
Notifications
You must be signed in to change notification settings - Fork 4
/
dp.go
88 lines (73 loc) · 2.44 KB
/
dp.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
package mewld_web
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"net/http"
"slices"
"strconv"
"time"
"github.com/anti-raid/splashtail/webserver/state"
)
// Ported from https://github.com/InfinityBotList/sysmanage-web/blob/main/plugins/authdp/mw.go
func DpAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-DP-Host") == "" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. X-DP-Host header not found. Not running under deployproxy?"))
return
}
if r.Header.Get("X-DP-UserID") == "" {
// User is not authenticated
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. Not running under deployproxy?"))
return
}
// User is allowed, set constants.UserIdHeader to user id for other plugins to use it
r.Header.Set("X-User-ID", r.Header.Get("X-DP-UserID"))
// Check if user is allowed
if len(globalConfig.AllowedIDS) > 0 && !slices.Contains(globalConfig.AllowedIDS, r.Header.Get("X-DP-UserID")) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. User not allowed to access this site."))
return
}
// User is possibly allowed
if r.Header.Get("X-DP-Signature") == "" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. X-DP-Signature header not found."))
return
}
// Check for X-DP-Timestamp
if r.Header.Get("X-DP-Timestamp") == "" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. X-DP-Timestamp header not found."))
return
}
ts := r.Header.Get("X-DP-Timestamp")
// Validate DP-Secret next
if state.Config.Meta.DPSecret != "" {
h := hmac.New(sha512.New, []byte(state.Config.Meta.DPSecret))
h.Write([]byte(ts))
h.Write([]byte(r.Header.Get("X-DP-UserID")))
hexed := hex.EncodeToString(h.Sum(nil))
if r.Header.Get("X-DP-Signature") != hexed {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. Signature from deployproxy mismatch"))
return
}
}
// Check if timestamp is valid
timestamp, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. X-DP-Timestamp is not a valid integer."))
return
}
if time.Now().Unix()-timestamp > 10 {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized. X-DP-Timestamp is too old."))
return
}
next.ServeHTTP(w, r)
})
}