-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
authglinet.go
113 lines (91 loc) · 2.14 KB
/
authglinet.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
package home
import (
"bytes"
"encoding/binary"
"io"
"net"
"net/http"
"os"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghio"
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/log"
)
// GLMode - enable GL-Inet compatibility mode
var GLMode bool
var glFilePrefix = "/tmp/gl_token_"
const (
glTokenTimeoutSeconds = 3600
glCookieName = "Admin-Token"
)
func glProcessRedirect(w http.ResponseWriter, r *http.Request) bool {
if !GLMode {
return false
}
// redirect to gl-inet login
host, _, _ := net.SplitHostPort(r.Host)
url := "http://" + host
log.Debug("Auth: redirecting to %s", url)
http.Redirect(w, r, url, http.StatusFound)
return true
}
func glProcessCookie(r *http.Request) bool {
if !GLMode {
return false
}
glCookie, glerr := r.Cookie(glCookieName)
if glerr != nil {
return false
}
log.Debug("Auth: GL cookie value: %s", glCookie.Value)
if glCheckToken(glCookie.Value) {
return true
}
log.Info("Auth: invalid GL cookie value: %s", glCookie)
return false
}
func glCheckToken(sess string) bool {
tokenName := glFilePrefix + sess
_, err := os.Stat(tokenName)
if err != nil {
log.Error("os.Stat: %s", err)
return false
}
tokenDate := glGetTokenDate(tokenName)
now := uint32(time.Now().UTC().Unix())
return now <= (tokenDate + glTokenTimeoutSeconds)
}
// MaxFileSize is a maximum file length in bytes.
const MaxFileSize = 1024 * 1024
func glGetTokenDate(file string) uint32 {
f, err := os.Open(file)
if err != nil {
log.Error("os.Open: %s", err)
return 0
}
defer func() {
derr := f.Close()
if derr != nil {
log.Error("glinet: closing file: %s", err)
}
}()
fileReader, err := aghio.LimitReader(f, MaxFileSize)
if err != nil {
log.Error("creating limited reader: %s", err)
return 0
}
var dateToken uint32
// This use of ReadAll is now safe, because we limited reader.
bs, err := io.ReadAll(fileReader)
if err != nil {
log.Error("reading token: %s", err)
return 0
}
buf := bytes.NewBuffer(bs)
err = binary.Read(buf, aghos.NativeEndian, &dateToken)
if err != nil {
log.Error("decoding token: %s", err)
return 0
}
return dateToken
}