-
Notifications
You must be signed in to change notification settings - Fork 289
/
state.go
210 lines (184 loc) · 4.94 KB
/
state.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
package server
import (
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/cbeuw/Cloak/internal/server/usermanager"
"github.com/sirupsen/logrus"
"io/ioutil"
"net"
"strings"
"sync"
"time"
gmux "github.com/gorilla/mux"
)
type rawConfig struct {
ProxyBook map[string][]string
BindAddr []string
BypassUID [][]byte
RedirAddr string
PrivateKey string
AdminUID string
DatabasePath string
StreamTimeout int
CncMode bool
}
// State type stores the global state of the program
type State struct {
BindAddr []net.Addr
ProxyBook map[string]net.Addr
Now func() time.Time
AdminUID []byte
Timeout time.Duration
BypassUID map[[16]byte]struct{}
staticPv crypto.PrivateKey
RedirAddr net.Addr
usedRandomM sync.RWMutex
usedRandom map[[32]byte]int64
Panel *userPanel
LocalAPIRouter *gmux.Router
}
func InitState(nowFunc func() time.Time) (*State, error) {
ret := &State{
Now: nowFunc,
BypassUID: make(map[[16]byte]struct{}),
ProxyBook: map[string]net.Addr{},
usedRandom: map[[32]byte]int64{},
}
go ret.UsedRandomCleaner()
return ret, nil
}
// ParseConfig parses the config (either a path to json or the json itself as argument) into a State variable
func (sta *State) ParseConfig(conf string) (err error) {
var content []byte
var preParse rawConfig
content, errPath := ioutil.ReadFile(conf)
if errPath != nil {
errJson := json.Unmarshal(content, &preParse)
if errJson != nil {
return errors.New("Failed to read/unmarshal configuration, path is invalid or " + errJson.Error())
}
} else {
errJson := json.Unmarshal(content, &preParse)
if errJson != nil {
return errors.New("Failed to read configuration file: " + errJson.Error())
}
}
if preParse.CncMode {
//TODO: implement command & control mode
} else {
manager, err := usermanager.MakeLocalManager(preParse.DatabasePath)
if err != nil {
return err
}
sta.Panel = MakeUserPanel(manager)
sta.LocalAPIRouter = manager.Router
}
if preParse.StreamTimeout == 0 {
sta.Timeout = time.Duration(300) * time.Second
} else {
sta.Timeout = time.Duration(preParse.StreamTimeout) * time.Second
}
redirAddr := preParse.RedirAddr
colonSep := strings.Split(redirAddr, ":")
if len(colonSep) != 0 {
if len(colonSep) == 2 {
logrus.Error("If RedirAddr contains a port number, please remove it.")
redirAddr = colonSep[0]
} else {
if strings.Contains(redirAddr, "[") {
logrus.Error("If RedirAddr contains a port number, please remove it.")
redirAddr = strings.TrimRight(redirAddr, "]:"+colonSep[len(colonSep)-1])
redirAddr = strings.TrimPrefix(redirAddr, "[")
}
}
}
sta.RedirAddr, err = net.ResolveIPAddr("ip", redirAddr)
if err != nil {
return fmt.Errorf("unable to resolve RedirAddr: %v. ", err)
}
for _, addr := range preParse.BindAddr {
bindAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return err
}
sta.BindAddr = append(sta.BindAddr, bindAddr)
}
for name, pair := range preParse.ProxyBook {
name = strings.ToLower(name)
if len(pair) != 2 {
return fmt.Errorf("invalid proxy endpoint and address pair for %v: %v", name, pair)
}
network := strings.ToLower(pair[0])
switch network {
case "tcp":
addr, err := net.ResolveTCPAddr("tcp", pair[1])
if err != nil {
return err
}
sta.ProxyBook[name] = addr
continue
case "udp":
addr, err := net.ResolveUDPAddr("udp", pair[1])
if err != nil {
return err
}
sta.ProxyBook[name] = addr
continue
}
}
pvBytes, err := base64.StdEncoding.DecodeString(preParse.PrivateKey)
if err != nil {
return errors.New("Failed to decode private key: " + err.Error())
}
var pv [32]byte
copy(pv[:], pvBytes)
sta.staticPv = &pv
adminUID, err := base64.StdEncoding.DecodeString(preParse.AdminUID)
if err != nil {
return errors.New("Failed to decode AdminUID: " + err.Error())
}
sta.AdminUID = adminUID
var arrUID [16]byte
for _, UID := range preParse.BypassUID {
copy(arrUID[:], UID)
sta.BypassUID[arrUID] = struct{}{}
}
copy(arrUID[:], adminUID)
sta.BypassUID[arrUID] = struct{}{}
return nil
}
// IsBypass checks if a UID is a bypass user
func (sta *State) IsBypass(UID []byte) bool {
var arrUID [16]byte
copy(arrUID[:], UID)
_, exist := sta.BypassUID[arrUID]
return exist
}
const TIMESTAMP_TOLERANCE = 180 * time.Second
const CACHE_CLEAN_INTERVAL = 12 * time.Hour
// UsedRandomCleaner clears the cache of used random fields every CACHE_CLEAN_INTERVAL
func (sta *State) UsedRandomCleaner() {
for {
time.Sleep(CACHE_CLEAN_INTERVAL)
now := sta.Now()
sta.usedRandomM.Lock()
for key, t := range sta.usedRandom {
if time.Unix(t, 0).Before(now.Add(TIMESTAMP_TOLERANCE)) {
delete(sta.usedRandom, key)
}
}
sta.usedRandomM.Unlock()
}
}
func (sta *State) registerRandom(r []byte) bool {
var random [32]byte
copy(random[:], r)
sta.usedRandomM.Lock()
_, used := sta.usedRandom[random]
sta.usedRandom[random] = sta.Now().Unix()
sta.usedRandomM.Unlock()
return used
}