-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathauthtables.go
305 lines (246 loc) · 6.76 KB
/
authtables.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
package main
import (
"encoding/json"
"fmt"
log "github.com/Sirupsen/logrus"
"gopkg.in/redis.v4"
"io/ioutil"
"net/http"
"regexp"
"time"
)
//Main
func main() {
//First time online, load historical data for bloom
loadRecords()
//Configure log Loglevel
//Announce that we're running
log.Info("AuthTables is running.")
//Add routes, then open a webserver
http.HandleFunc("/add", addRequest)
http.HandleFunc("/check", checkRequest)
http.HandleFunc("/reset", resetRequest)
log.Error(http.ListenAndServe(":8080", nil))
}
func getRecordHashesFromRecord(rec Record) (recordhashes RecordHashes) {
rh := RecordHashes{
uid: []byte(c.Shard + rec.Uid),
uidMID: []byte(fmt.Sprintf(c.Shard + "%s:%s", rec.Uid, rec.Mid)),
uidIP: []byte(fmt.Sprintf(c.Shard + "%s:%s", rec.Uid, rec.Ip)),
uidALL: []byte(fmt.Sprintf(c.Shard + "%s:%s:%s", rec.Uid, rec.Ip, rec.Mid)),
ipMID: []byte(fmt.Sprintf(c.Shard + "%s:%s", rec.Ip, rec.Mid)),
midIP: []byte(fmt.Sprintf(c.Shard + "%s:%s", rec.Mid, rec.Ip)),
}
return rh
}
func check(rec Record) (b bool) {
//We've received a request to /check and now
//we need to see if it's suspicious or not.
//Create []byte Strings for bloom
rh := getRecordHashesFromRecord(rec)
//These is ip:mid and mid:ip, useful for `key`
//commands hunting for other bad guys. This May
//be a separate db, sharded elsewhere in the future.
//Example: `key 1.1.1.1:*` will reveal new machine ID's
//seen on this host.
//This may include evil data, which is why we don't attach to a user.
writeRecord(rh.ipMID)
writeRecord(rh.midIP)
//Do we have it in bloom?
//if filter.Test([]byte(r.URL.Path[1:])) {
if filter.Test(rh.uidALL) {
//We've seen everything about this user before. MachineID, IP, and user.
log.WithFields(log.Fields{
"uid": rec.Uid,
"mid": rec.Mid,
"ip": rec.Ip,
}).Debug("Known user information.")
//Write Everything.
//defer writeUserRecord(rh)
return true
} else if (filter.Test(rh.uidMID)) || (filter.Test(rh.uidIP)) {
log.WithFields(log.Fields{
"uid": rec.Uid,
"mid": rec.Mid,
"ip": rec.Ip,
}).Debug("Authentication is partially within graph. Expanding graph.")
defer writeUserRecord(rh)
return true
} else if !(filter.Test(rh.uid)) {
log.WithFields(log.Fields{
"uid": rec.Uid,
"mid": rec.Mid,
"ip": rec.Ip,
}).Debug("New user. Creating graph")
defer writeUserRecord(rh)
return true
} else {
log.WithFields(log.Fields{
"uid": rec.Uid,
"mid": rec.Mid,
"ip": rec.Ip,
}).Info("Suspicious authentication.")
return false
}
}
func isStringSane(s string) (b bool) {
matched, err := regexp.MatchString("^[A-Za-z0-9.]{0,60}$", s)
if err != nil {
fmt.Println(err)
}
return matched
}
func isRecordSane(r Record) (b bool) {
return (isStringSane(r.Mid) && isStringSane(r.Ip) && isStringSane(r.Uid))
}
func sanitizeError() {
log.Warn("Bad data received. Sanitize fields in application before sending to remove this message.")
}
func requestToJSON(r *http.Request) (m Record) {
//Get our body from the request (which should be JSON)
err := r.ParseForm()
if err != nil {
fmt.Println("error:", err)
log.Warn("Trouble parsing the form from the request")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("error:", err)
log.Warn("Trouble reading JSON from request")
}
//Cast our JSON body content to prepare for Unmarshal
clientAuthdata := []byte(body)
//Decode some JSON and get it into our Record struct
var rec Record
err = json.Unmarshal(clientAuthdata, &rec)
if err != nil {
log.Warn("Trouble with Unmarhal of JSON received from client.")
}
return rec
}
//Main routing handlers
func addRequest(w http.ResponseWriter, r *http.Request) {
var m Record
m = requestToJSON(r)
if isRecordSane(m) {
log.WithFields(log.Fields{
"uid": m.Uid,
"mid": m.Mid,
"ip": m.Ip,
}).Debug("Adding user.")
if add(m) {
fmt.Fprint(w, "ADD")
} else {
fmt.Fprint(w, "ADD")
log.Error("Something went wrong adding user.")
} //Currently we fail open.
} else {
sanitizeError()
}
}
func add(rec Record) (b bool) {
//JSON record is sent to /add, we add all of it to bloom.
rh := getRecordHashesFromRecord(rec)
defer writeUserRecord(rh)
return true
}
func resetRequest(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "RESET")
defer loadRecords()
}
func checkRequest(w http.ResponseWriter, r *http.Request) {
var m Record
m = requestToJSON(r)
//Only let sane data through the gate.
if isRecordSane(m) {
if check(m) {
fmt.Fprint(w, "OK")
} else {
fmt.Fprint(w, "BAD")
}
} else {
//We hit this if nasty JSON data came through. Shouldn't touch bloom or redis.
//To remove this message, don't let your application send UID, IP, or MID that doesn't match "^[A-Za-z0-9.]{0,60}$"
sanitizeError()
fmt.Fprintln(w, "BAD")
}
}
func writeRecord(key []byte) {
err := client.Set(string(key), 1, 0).Err()
if err != nil {
//(TODO Try to make new connection)
rebuildConnection()
log.WithFields(log.Fields{
"error": err,
}).Error("Problem connecting to database.")
}
}
func rebuildConnection() {
log.Debug("Attempting to reconnect...")
client = redis.NewClient(&redis.Options{
Addr: c.Host + ":" + c.Port,
Password: c.Password, // no password set
DB: 0, // use default DB
})
}
func loadRecords() {
timeTrack(time.Now(), "Loading records")
var cursor uint64
var n int
//Empty our filter before re-filling
filter.ClearAll()
for {
var keys []string
var err error
//The shard name is pulled from config. We don't want to waste time on records that won't be asked of us.
keys, cursor, err = client.Scan(cursor, c.Shard + "*", 10).Result()
if err != nil {
log.Error("Could not connect to database. Continuing without records")
break
}
n += len(keys)
for _, element := range keys {
filter.Add([]byte(element))
}
if cursor == 0 {
break
}
}
log.WithFields(log.Fields{
"number": n,
}).Debug("Loaded historical records.")
}
func canGetKey(s string) bool {
err := client.Get(s).Err()
if err != nil {
return false
}
return true
}
func writeUserRecord(rh RecordHashes) {
err := client.MSet(string(rh.uid), 1, string(rh.uidMID), 1, string(rh.uidIP), 1, string(rh.uidALL), 1).Err()
if err != nil {
log.Error("MSet failed.")
log.Error(err)
}
//Bloom
filter.Add(rh.uidMID)
filter.Add(rh.uidIP)
filter.Add(rh.uid)
filter.Add(rh.uidALL)
}
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.WithFields(log.Fields{
"time": elapsed.String(),
"event": name,
}).Debug("Time tracked")
}
//Only using init to configure logging. See configuration.go
func init() {
level, err := log.ParseLevel(c.Loglevel)
if err != nil {
log.Error("Issue setting log level. Make sure log level is a string: debug, warn, info, error, panic")
}
log.SetLevel(level)
}