forked from sqrldev/server-go-ssp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli_handler.go
334 lines (301 loc) · 9.62 KB
/
cli_handler.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
package ssp
import (
"fmt"
"log"
"net/http"
"github.com/davecgh/go-spew/spew"
)
var supportedCommands = map[string]bool{
"query": true,
"ident": true,
"enable": true,
"disable": true,
"remove": true,
}
// Cli implements the /cli.sqrl endpoint
func (api *SqrlSspAPI) Cli(w http.ResponseWriter, r *http.Request) {
log.Printf("Req: %v", r.URL)
nut := Nut(r.URL.Query().Get("nut"))
if nut == "" {
w.Write(NewCliResponse("", "").WithClientFailure().Encode())
return
}
// response mutates from here depending on available values
response := NewCliResponse(Nut(nut), api.qry(nut))
req, err := ParseCliRequest(r)
if err != nil {
log.Printf("Can't parse body or bad signature: %v", err)
w.Write(response.WithClientFailure().WithCommandFailed().Encode())
return
}
// Signature is OK from here on!
// defer writing the response and saving the new nut
defer api.writeResponse(req, response, w)
// TODO remove me
spew.Dump(req)
hoardCache, err := api.getAndDelete(Nut(nut))
if err != nil {
if err == ErrNotFound {
log.Printf("Nut %v not found", nut)
response.WithClientFailure().WithCommandFailed()
return
}
log.Printf("Failed nut lookup: %v", err)
response.WithTransientError().WithCommandFailed()
return
}
response.HoardCache = hoardCache
// validation checks
err = api.requestValidations(hoardCache, req, r, response)
if err != nil {
return
}
if req.Client.Cmd == "query" {
tmpIdent := req.Identity()
tmpIdent.Btn = -1
response.Ask = api.Authenticator.AskResponse(tmpIdent)
}
// generate new nut
nut, err = api.tree.Nut()
if err != nil {
log.Printf("Error generating nut: %v", err)
response.WithCommandFailed()
return
}
// new nut to the response from here on out
response.Nut = nut
response.Qry = api.qry(nut)
// check if the same user has already been authenticated previously
identity, err := api.authStore.FindIdentity(req.Client.Idk)
if err != nil && err != ErrNotFound {
log.Printf("Error looking up identity: %v", err)
response.WithCommandFailed()
return
}
// Check is we know about a previous identity
previousIdentity, err := api.checkPreviousIdentity(req, response)
if err != nil {
return
}
if identity != nil {
err := api.knownIdentity(req, response, identity)
if err != nil {
return
}
} else if req.Client.Cmd == "ident" {
// create new identity from the request
identity = req.Identity()
// handle previous identity swap if the current identity is new
err := api.checkPreviousSwap(previousIdentity, identity, response)
if err != nil {
return
}
// Do we id match on first auth? grc says nope; PaulF and I think yes
response.WithIDMatch()
}
api.setSuk(req, response, identity)
// Finish authentication and saving
api.finishCliResponse(req, response, identity, hoardCache)
}
func (api *SqrlSspAPI) writeResponse(req *CliRequest, response *CliResponse, w http.ResponseWriter) {
respBytes := response.Encode()
// TODO debug remove me
decodedResp, _ := Sqrl64.DecodeString(string(respBytes))
log.Printf("Response: %v", string(decodedResp))
log.Printf("Encoded response: %v", string(respBytes))
// always save back the new nut
if response.HoardCache != nil {
err := api.hoard.Save(response.Nut, &HoardCache{
State: "associated",
RemoteIP: response.HoardCache.RemoteIP,
OriginalNut: response.HoardCache.OriginalNut,
PagNut: response.HoardCache.PagNut,
LastRequest: req,
LastResponse: respBytes,
}, api.NutExpiration)
if err != nil {
log.Printf("Failed saving to hoard: %v", err)
response.WithCommandFailed()
respBytes = response.Encode()
} else {
log.Printf("Saved nut %v in hoard", response.Nut)
}
}
w.Write(respBytes)
log.Println()
}
func (api *SqrlSspAPI) setSuk(req *CliRequest, response *CliResponse, identity *SqrlIdentity) {
if req.Client.Opt["suk"] {
if identity != nil {
response.Suk = identity.Suk
} else if req.Client.Cmd == "ident" {
response.Suk = req.Client.Suk
}
}
}
func (api *SqrlSspAPI) finishCliResponse(req *CliRequest, response *CliResponse, identity *SqrlIdentity, hoardCache *HoardCache) {
accountDisabled := false
if identity != nil {
accountDisabled = identity.Disabled
}
if req.IsAuthCommand() && !accountDisabled {
log.Printf("Authenticated Idk: %#v", identity)
authURL, err := api.authenticateIdentity(identity, req.Client.Btn)
if err != nil {
log.Printf("Failed saving identity: %v", err)
response.WithCommandFailed()
return
}
if req.Client.Opt["cps"] {
log.Printf("Setting CPS Auth: %v", authURL)
response.URL = authURL
}
}
// fail the ident on account disable
if req.Client.Cmd == "ident" && accountDisabled {
response.WithCommandFailed()
}
if req.IsAuthCommand() && !accountDisabled {
// for non-CPS we save the state back to the PagNut for redirect on polling
if !req.Client.Opt["cps"] {
err := api.hoard.Save(hoardCache.PagNut, &HoardCache{
State: "authenticated",
RemoteIP: hoardCache.RemoteIP,
OriginalNut: hoardCache.OriginalNut,
PagNut: hoardCache.PagNut,
LastRequest: req,
Identity: identity,
}, api.NutExpiration)
if err != nil {
log.Printf("Failed saving to hoard: %v", err)
response.WithCommandFailed()
}
log.Printf("Saved pagnut %v in hoard", hoardCache.PagNut)
}
}
}
func (api *SqrlSspAPI) checkPreviousSwap(previousIdentity, identity *SqrlIdentity, response *CliResponse) error {
if previousIdentity != nil {
err := api.swapIdentities(previousIdentity, identity)
if err != nil {
log.Printf("Failed swapping identities: %v", err)
response.WithCommandFailed()
return fmt.Errorf("identity swap error")
}
log.Printf("Swapped identity %#v for %#v", previousIdentity, identity)
// TODO should we clear the PreviousIDMatch here?
response.ClearPreviousIDMatch()
}
return nil
}
func (api *SqrlSspAPI) checkPreviousIdentity(req *CliRequest, response *CliResponse) (*SqrlIdentity, error) {
var previousIdentity *SqrlIdentity
var err error
if req.Client.Pidk != "" {
previousIdentity, err = api.authStore.FindIdentity(req.Client.Pidk)
if err != nil && err != ErrNotFound {
log.Printf("Error looking up previous identity: %v", err)
response.WithCommandFailed()
return nil, err
}
}
if previousIdentity != nil {
response.WithPreviousIDMatch()
// as per spec, proactively return the suk on pidk match
req.Client.Opt["suk"] = true
}
return previousIdentity, nil
}
func (api *SqrlSspAPI) requestValidations(hoardCache *HoardCache, req *CliRequest, r *http.Request, response *CliResponse) error {
req.IPAddress = api.RemoteIP(r)
// validate last response against this request
if hoardCache.LastResponse != nil && !req.ValidateLastResponse(hoardCache.LastResponse) {
response.WithCommandFailed()
// this is intentionally after so nothing about last response leaks
log.Printf("Last response %v and this one don't match: %v", string(hoardCache.LastResponse), string(req.Server))
return fmt.Errorf("validation error")
}
// validate the IP if required
if hoardCache.RemoteIP != req.IPAddress {
if !req.Client.Opt["noiptest"] {
log.Printf("Rejecting on IP mis-match orig: %v current: %v", hoardCache.RemoteIP, api.RemoteIP(r))
response.WithCommandFailed()
return fmt.Errorf("validation error")
}
} else {
log.Printf("Matched IP addresses")
response = response.WithIPMatch()
}
// validating the current request and associated Idk's match
if hoardCache.LastRequest != nil && hoardCache.LastRequest.Client.Idk != req.Client.Idk {
log.Printf("Identity mismatch orig: %v current %v", hoardCache.LastRequest.Client.Idk, req.Client.Idk)
response.WithCommandFailed().WithClientFailure().WithBadIDAssociation()
return fmt.Errorf("validation error")
}
if !supportedCommands[req.Client.Cmd] {
response.WithFunctionNotSupported()
return fmt.Errorf("Uknown command: %v", req.Client.Cmd)
}
return nil
}
func (api *SqrlSspAPI) knownIdentity(req *CliRequest, response *CliResponse, identity *SqrlIdentity) error {
if identity.Rekeyed != "" {
response.WithIdentitySuperseded()
log.Printf("Attempt to use Rekeyed IDK: %v from %v", identity.Idk, req.IPAddress)
if req.Client.Cmd != "query" {
response.WithCommandFailed()
}
return fmt.Errorf("attempted use of rekeyed identity")
} else {
response.WithIDMatch()
}
// copy the current Btn value from the request
identity.Btn = req.Client.Btn
changed := false
if req.IsAuthCommand() {
changed = req.UpdateIdentity(identity)
}
if req.Client.Cmd == "enable" || req.Client.Cmd == "remove" {
err := req.VerifyUrs(identity.Vuk)
if err != nil {
log.Printf("enable command failed urs validation")
// TODO: remove since sig check failed here?
if identity.Disabled {
response.WithSQRLDisabled()
}
response.WithClientFailure().WithCommandFailed()
return fmt.Errorf("identity error")
}
if req.Client.Cmd == "enable" {
log.Printf("Reenabled account: %v", identity.Idk)
identity.Disabled = false
changed = true
} else if req.Client.Cmd == "remove" {
err := api.removeIdentity(identity)
if err != nil {
log.Printf("Failed removing identity %v: %v", identity.Idk, err)
response.WithClientFailure().WithCommandFailed()
return fmt.Errorf("identity error")
}
response.ClearIDMatch()
log.Printf("removed identity %v", identity.Idk)
}
}
if req.Client.Cmd == "disable" {
identity.Disabled = true
changed = true
}
if identity.Disabled {
req.Client.Opt["suk"] = true
response.WithSQRLDisabled()
}
if changed {
err := api.authStore.SaveIdentity(identity)
if err != nil {
log.Printf("Failed saving identity %v: %v", identity.Idk, err)
response.WithClientFailure().WithCommandFailed()
return fmt.Errorf("identity error")
}
}
return nil
}