/
minsession.go
380 lines (331 loc) · 8.88 KB
/
minsession.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
package authentication
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strconv"
"github.com/proidiot/gone/errors"
"github.com/proidiot/gone/log"
"github.com/stuphlabs/pullcord/config"
)
const minSessionCookieNameRandSize = 32
const minSessionCookieValueRandSize = 128
const minSessionCookieMaxAge = 2 * 60 * 60
const rngCollisionError = errors.New(
"The random number generator produced a colliding value. This is" +
" perfectly fine if it occurs extremely rarely, but if it" +
" occurs more than once, it would be extremely concerning.",
)
// MinSessionHandler is a somewhat minimalist form of a SessionHandler.
type MinSessionHandler struct {
Name string
Path string
Domain string
table map[string]*MinSession
}
func init() {
config.MustRegisterResourceType(
"minsessionhandler",
func() json.Unmarshaler {
return new(MinSessionHandler)
},
)
}
// UnmarshalJSON implements encoding/json.Unmarshaler.
func (h *MinSessionHandler) UnmarshalJSON(data []byte) error {
_ = log.Debug("Unmarshaling a MinSessionHandler")
var t struct {
Name string
Path string
Domain string
}
if e := json.Unmarshal(data, &t); e != nil {
return e
}
h.Name = t.Name
h.Path = t.Path
h.Domain = t.Domain
return nil
}
// NewMinSessionHandler creates an initialized session handler. Unfortunately a
// nil MinSessionHandler does not currently provide the desired behavior.
func NewMinSessionHandler(name, path, domain string) *MinSessionHandler {
return &MinSessionHandler{
name,
path,
domain,
make(map[string]*MinSession),
}
}
func (h *MinSessionHandler) assureTableInitialized() {
if h.table == nil {
h.table = make(map[string]*MinSession)
}
}
// GetSession generates a new session to track state with.
func (h *MinSessionHandler) GetSession() (Session, error) {
_ = log.Info("minsessionhandler is generating a new session")
_ = log.Debug(
fmt.Sprintf(
"minsession being generated by minsessionhandler: %v",
h,
),
)
h.assureTableInitialized()
var sesh MinSession
var core minSessionCore
sesh.core = &core
sesh.core.data = make(map[string]interface{})
sesh.handler = h
return &sesh, nil
}
func (h *MinSessionHandler) genCookie() (*http.Cookie, error) {
_ = log.Debug("minsession generating cookie")
h.assureTableInitialized()
var randReadErr error
var otherErr error
nbytes := make([]byte, minSessionCookieNameRandSize)
vbytes := make([]byte, minSessionCookieValueRandSize)
cookieName := ""
nameGenNeeded := true
for nameGenNeeded {
_, randReadErr = rand.Read(nbytes)
if randReadErr != nil {
_ = log.Err(
"minsession cookie generation was unable to" +
" read the needed random bytes",
)
return nil, randReadErr
}
cookieName = h.Name + "-" + hex.EncodeToString(nbytes)
// Slower than adding an else on the next if, but clearer.
nameGenNeeded = false
_, collision := h.table[cookieName]
if collision {
// We had a collision with an existing legit cookie?
// Is the random number generator broken?
err := log.Err(
fmt.Sprintf(
"minsession cookie generation has"+
" created a new cookie with a"+
" name that collides with an"+
" already existing cookie from"+
" the cookie table which"+
" shares the name: %s",
cookieName,
),
)
if err != nil {
// will not proceed if unable to log potentially
// catastrophic security events
return nil, err
}
nameGenNeeded = true
otherErr = rngCollisionError
}
}
_, randReadErr = rand.Read(vbytes)
if randReadErr != nil {
_ = log.Err(
"minsession cookie generation was unable to" +
" read the needed random bytes",
)
return nil, randReadErr
}
var cke http.Cookie
cke.Name = cookieName
cke.Value = hex.EncodeToString(vbytes)
cke.Path = h.Path
cke.Domain = h.Domain
cke.MaxAge = minSessionCookieMaxAge
// TODO make configurable
cke.Secure = false
cke.HttpOnly = true
return &cke, otherErr
}
type minSessionCore struct {
cvalue string
data map[string]interface{}
}
// MinSession represents a particular user session, and is intrinsically linked
// with the MinSessionHandler that created it.
type MinSession struct {
core *minSessionCore
handler *MinSessionHandler
}
// GetValue looks up a value stored in the session for a given key. If the key
// did not match an existing saved value, an error will be returned.
func (sesh *MinSession) GetValue(key string) (interface{}, error) {
_ = log.Debug(fmt.Sprintf("minsession requesting value for: %s", key))
value, present := sesh.core.data[key]
if !present {
return nil, NoSuchSessionValueError
}
return value, nil
}
// GetValues retrieves all the key/value pairs associated with the session.
func (sesh *MinSession) GetValues() map[string]interface{} {
_ = log.Debug("minsession requesting all values")
return sesh.core.data
}
// SetValue saves a key/value pair into the session, possibly overwriting a
// previously set value.
func (sesh *MinSession) SetValue(key string, value interface{}) error {
_ = log.Debug(fmt.Sprintf("minsession setting value for: %s", key))
sesh.core.data[key] = value
return nil
}
// CookieMask for the MinSession is an implementation of the CookieMask
// function required by all Session derivatives.
func (sesh *MinSession) CookieMask(incomingCookies []*http.Cookie) (
forwardedCookies []*http.Cookie,
setCookies []*http.Cookie,
err error,
) {
_ = log.Debug("running minsession cookiemask")
newCookieNeeded := true
cookieNameRegex := regexp.MustCompile(
"^" +
sesh.handler.Name +
"-[0-9A-Fa-f]{" +
strconv.Itoa(minSessionCookieNameRandSize*2) +
"}$",
)
inCkesBuffer := new(bytes.Buffer)
for _, cookie := range incomingCookies {
inCkesBuffer.WriteString("\"" + cookie.Name + "\",")
if cookieNameRegex.MatchString(cookie.Name) {
sesh2, present := sesh.handler.table[cookie.Name]
if present &&
len(cookie.Value) > 0 &&
cookie.Value == sesh2.core.cvalue {
_ = log.Debug(
fmt.Sprintf(
"minsession cookiemask"+
" received valid"+
" cookie with name: %s",
cookie.Name,
),
)
newCookieNeeded = false
// In the more common scenario where a new
// empty session was created, it would probably
// be faster to copy any recently set values
// into the already established session than
// vice-versa.
for key, val := range sesh.core.data {
sesh2.core.data[key] = val
}
// This should replace a new empty session with
// an already established one, but I think it
// would work as expected with two already
// established sessions as well? I hope so, at
// least... Anyway, we can't just exit here in
// case such a scenario occurs.
sesh.core = sesh2.core
} else {
if present {
// TODO: configurable info vs warn?
_ = log.Info(
fmt.Sprintf(
"minsession"+
" cookiemask"+
" received bad"+
" cookie value"+
" for valid"+
" cookie name:"+
" %s",
cookie.Name,
),
)
delete(sesh.handler.table, cookie.Name)
// TODO: should this destroy every
// session that is touched?
} else {
_ = log.Info(
fmt.Sprintf(
"minsession"+
" cookiemask"+
" received"+
" matching but"+
" invalid"+
" cookie with"+
" name: %s",
cookie.Name,
),
)
}
var badCookie http.Cookie
badCookie.Name = cookie.Name
badCookie.Value = cookie.Value
badCookie.MaxAge = -1
setCookies = append(setCookies, &badCookie)
}
} else {
forwardedCookies = append(forwardedCookies, cookie)
}
}
_ = log.Debug(
fmt.Sprintf(
"minsession cookiemask received cookies with these"+
" cookie names: [%s]",
inCkesBuffer.String(),
),
)
if newCookieNeeded {
_ = log.Debug(
"minsession cookiemask needs to generate a new cookie",
)
newCookie, err := sesh.handler.genCookie()
if newCookie == nil {
err = log.Err(
fmt.Sprintf(
"minsession cookiemask ran into"+
" unexpected, unrecoverable"+
" errors during cookie"+
" generation: %s",
err,
),
)
if err != nil {
return nil, nil, err
}
} else if err != nil && err != rngCollisionError {
err = log.Warning(
fmt.Sprintf(
"minsession cookiemask ran into"+
" unexpected but apparently"+
" recoverable errors during"+
" cookie generation: %s",
err,
),
)
if err != nil {
return nil, nil, err
}
}
setCookies = append(setCookies, newCookie)
_ = log.Info(
fmt.Sprintf(
"minsession cookiemask has added a new cookie"+
" with name: %s",
newCookie.Name,
),
)
sesh.core.cvalue = newCookie.Value
sesh.handler.table[newCookie.Name] = sesh
_ = log.Debug(
fmt.Sprintf(
"minsession cookiemask has created a new"+
" session to go with the new cookie"+
" with name: %s",
newCookie.Name,
),
)
}
return forwardedCookies, setCookies, nil
}