generated from projectsesame/envoy-extproc-payloadlimit-demo-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anti-replay.go
237 lines (193 loc) · 4.68 KB
/
anti-replay.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
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"slices"
"strconv"
"sync"
"time"
typev3 "github.com/envoyproxy/go-control-plane/envoy/type/v3"
ep "github.com/wrossmorrow/envoy-extproc-sdk-go"
)
const (
kSign = "sign"
kNonce = "nonce"
kTimeSpan = "timespan"
kTimeStamp = "timestamp"
)
type antiReplayRequestProcessor struct {
opts *ep.ProcessingOptions
timeSpan int64
noncePool *ttlSet
}
func (s *antiReplayRequestProcessor) GetName() string {
return "anti-replay"
}
func (s *antiReplayRequestProcessor) GetOptions() *ep.ProcessingOptions {
return s.opts
}
func (s *antiReplayRequestProcessor) ProcessRequestHeaders(ctx *ep.RequestContext, headers ep.AllHeaders) error {
return ctx.ContinueRequest()
}
func extract(m map[string]any, k string) string {
vv, ok := m[k]
if ok {
return vv.(string)
}
return ""
}
func (s *antiReplayRequestProcessor) ProcessRequestBody(ctx *ep.RequestContext, body []byte) error {
cancel := func(code int32) error {
return ctx.CancelRequest(code, map[string]ep.HeaderValue{}, typev3.StatusCode_name[code])
}
var unstructure map[string]any
err := json.Unmarshal(body, &unstructure)
if err != nil {
log.Printf("parse the request is failed: %v", err.Error())
return cancel(400)
}
timestamp, _ := strconv.ParseInt(extract(unstructure, kTimeStamp), 10, 64)
now := time.Now().Unix()
if timestamp < now-s.timeSpan || timestamp > now+s.timeSpan {
log.Printf("the timestamp is expired")
return cancel(403)
}
nonce := extract(unstructure, kNonce)
if s.noncePool.exists(nonce) {
log.Printf("the nonce has been used")
return cancel(403)
}
s.noncePool.put(nonce)
var (
keys []string
m = map[string]string{}
sign string
)
for k, v := range unstructure {
val := v.(string)
if len(val) != 0 {
if k != kSign {
keys = append(keys, k)
m[k] = val
} else {
sign = val
}
}
}
slices.Sort(keys)
buf := &bytes.Buffer{}
for _, k := range keys {
buf.WriteString(fmt.Sprintf("%s=%s&", k, m[k]))
}
buf.Truncate(buf.Len() - 1)
raw := buf.Bytes()
hash := md5.Sum(raw)
md5Hex := hex.EncodeToString(hash[:])
if sign != md5Hex {
log.Printf("verify the sign is failed. raw: %s, want: %x actual: %s", string(raw), md5Hex, sign)
return cancel(403)
}
return ctx.ContinueRequest()
}
func (s *antiReplayRequestProcessor) ProcessRequestTrailers(ctx *ep.RequestContext, trailers ep.AllHeaders) error {
return ctx.ContinueRequest()
}
func (s *antiReplayRequestProcessor) ProcessResponseHeaders(ctx *ep.RequestContext, headers ep.AllHeaders) error {
return ctx.ContinueRequest()
}
func (s *antiReplayRequestProcessor) ProcessResponseBody(ctx *ep.RequestContext, body []byte) error {
return ctx.ContinueRequest()
}
func (s *antiReplayRequestProcessor) ProcessResponseTrailers(ctx *ep.RequestContext, trailers ep.AllHeaders) error {
return ctx.ContinueRequest()
}
func (s *antiReplayRequestProcessor) Init(opts *ep.ProcessingOptions, nonFlagArgs []string) error {
s.opts = opts
s.timeSpan = 15 * 60
var i int
nArgs := len(nonFlagArgs)
for ; i < nArgs-1; i++ {
if nonFlagArgs[i] == kTimeSpan {
break
}
}
if i == nArgs {
log.Printf("the argument: 'timespan' is missing, use the default.\n")
} else {
timeSpan, _ := strconv.ParseInt(nonFlagArgs[i+1], 10, 64)
if timeSpan == 0 {
log.Printf("parse the value for parameter: 'timespan' is failed,use the default.\n")
} else {
s.timeSpan = timeSpan
log.Printf("the timespan is: %d.\n", s.timeSpan)
}
}
s.noncePool = newTTLSet(s.timeSpan)
go s.noncePool.evictExpired()
return nil
}
func (s *antiReplayRequestProcessor) Finish() {
s.noncePool.finish()
}
type ttlSet struct {
mu sync.Mutex
pool map[string]int64
timeSpan int64
chEvict chan struct{}
done chan struct{}
}
func newTTLSet(timeSpan int64) *ttlSet {
return &ttlSet{
pool: map[string]int64{},
chEvict: make(chan struct{}),
done: make(chan struct{}),
timeSpan: timeSpan,
}
}
func (c *ttlSet) put(v string) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.existsLocked(v) {
c.pool[v] = time.Now().Unix()
}
}
func (c *ttlSet) evictExpired() {
defer close(c.done)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-c.chEvict:
return
case <-ticker.C:
now := time.Now().Unix()
c.mu.Lock()
for k, v := range c.pool {
if v < now-c.timeSpan {
delete(c.pool, k)
}
}
c.mu.Unlock()
}
}
}
func (c *ttlSet) existsLocked(v string) bool {
_, ok := c.pool[v]
return ok
}
func (c *ttlSet) exists(v string) bool {
if len(v) == 0 {
return true
}
c.mu.Lock()
defer c.mu.Unlock()
return c.existsLocked(v)
}
func (c *ttlSet) finish() {
close(c.chEvict)
<-c.done
}