-
Notifications
You must be signed in to change notification settings - Fork 1
/
webauthn.go
345 lines (287 loc) · 9.2 KB
/
webauthn.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
package mfa
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/gorilla/mux"
uuid "github.com/satori/go.uuid"
)
const IDParam = "id"
// ApiMeta holds metadata about the calling service for use in WebAuthn responses.
// Since this service/api is consumed by multiple sources this information cannot
// be stored in the envConfig
type ApiMeta struct {
RPDisplayName string `json:"RPDisplayName"` // Display Name for your site
RPID string `json:"RPID"` // Generally the FQDN for your site
RPOrigin string `json:"RPOrigin"` // The origin URL for WebAuthn requests
RPIcon string `json:"RPIcon"` // Optional icon URL for your site
UserUUID string `json:"UserUUID"`
Username string `json:"Username"`
UserDisplayName string `json:"UserDisplayName"`
UserIcon string `json:"UserIcon"`
}
// beginRegistrationResponse adds uuid to response for consumers that depend on this api to generate the uuid
type beginRegistrationResponse struct {
UUID string `json:"uuid"`
protocol.CredentialCreation
}
type finishRegistrationResponse struct {
KeyHandleHash string `json:"key_handle_hash"`
}
type finishLoginResponse struct {
CredentialID string `json:"credentialId"` // DEPRECATED, use KeyHandleHash instead
KeyHandleHash string `json:"key_handle_hash"`
}
func BeginRegistration(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
}
// If user.id is empty, treat as new user/registration
if user.ID == "" {
user.ID = uuid.NewV4().String()
}
options, err := user.BeginRegistration()
if err != nil {
jsonResponse(w, fmt.Sprintf("failed to begin registration: %s", err.Error()), http.StatusBadRequest)
return
}
response := beginRegistrationResponse{
user.ID,
*options,
}
jsonResponse(w, response, http.StatusOK)
}
func FinishRegistration(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
return
}
keyHandleHash, err := user.FinishRegistration(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
return
}
response := finishRegistrationResponse{
KeyHandleHash: keyHandleHash,
}
jsonResponse(w, response, http.StatusOK) // Handle next steps
}
func BeginLogin(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error getting user from context: %s\n", err)
return
}
options, err := user.BeginLogin()
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error beginning user login: %s\n", err)
return
}
jsonResponse(w, options, http.StatusOK)
}
func FinishLogin(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error getting user from context: %s\n", err)
return
}
credential, err := user.FinishLogin(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error finishing user login : %s\n", err)
return
}
resp := finishLoginResponse{
CredentialID: string(credential.ID),
KeyHandleHash: hashAndEncodeKeyHandle(credential.ID),
}
jsonResponse(w, resp, http.StatusOK)
}
func DeleteUser(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error getting user from context: %s\n", err)
return
}
if err := user.Delete(); err != nil {
jsonResponse(w, err, http.StatusInternalServerError)
log.Printf("error deleting user: %s", err)
return
}
jsonResponse(w, nil, http.StatusNoContent)
}
func DeleteCredential(w http.ResponseWriter, r *http.Request) {
user, err := getUserFromContext(r)
if err != nil {
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("error getting user from context: %s\n", err)
return
}
params := mux.Vars(r)
credID, ok := params[IDParam]
if !ok || credID == "" {
err := fmt.Errorf("%s path parameter not provided to DeleteCredential", IDParam)
jsonResponse(w, err, http.StatusBadRequest)
log.Printf("%s\n", err)
return
}
status, err := user.DeleteCredential(credID)
if err != nil {
log.Printf("error deleting user credential: %s", err)
}
jsonResponse(w, err, status)
}
type simpleError struct {
Error string `json:"error"`
}
func newSimpleError(err error) simpleError {
return simpleError{Error: err.Error()}
}
func jsonResponse(w http.ResponseWriter, body interface{}, status int) {
var data interface{}
switch b := body.(type) {
case error:
data = newSimpleError(b)
default:
data = body
}
jBody := []byte{}
var err error
if data != nil {
jBody, err = json.Marshal(data)
if err != nil {
log.Printf("failed to marshal response body to json: %s\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("failed to marshal response body to json"))
return
}
}
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
_, err = w.Write(jBody)
if err != nil {
log.Printf("faild to write response in jsonResponse: %s\n", err)
}
}
func fixStringEncoding(content string) string {
content = strings.ReplaceAll(content, "+", "-")
content = strings.ReplaceAll(content, "/", "_")
content = strings.ReplaceAll(content, "=", "")
return content
}
func fixEncoding(content []byte) io.Reader {
allStr := string(content)
return bytes.NewReader([]byte(fixStringEncoding(allStr)))
}
func getWebAuthnFromApiMeta(meta ApiMeta) (*webauthn.WebAuthn, error) {
web, err := webauthn.New(&webauthn.Config{
RPDisplayName: meta.RPDisplayName, // Display Name for your site
RPID: meta.RPID, // Generally the FQDN for your site
RPOrigins: []string{meta.RPOrigin}, // The origin URL for WebAuthn requests
Debug: true,
})
if err != nil {
fmt.Println(err)
}
return web, nil
}
func getApiMetaFromRequest(r *http.Request) (ApiMeta, error) {
meta := ApiMeta{
RPDisplayName: r.Header.Get("x-mfa-RPDisplayName"),
RPID: r.Header.Get("x-mfa-RPID"),
RPOrigin: r.Header.Get("x-mfa-RPOrigin"),
RPIcon: r.Header.Get("x-mfa-RPIcon"),
UserUUID: r.Header.Get("x-mfa-UserUUID"),
Username: r.Header.Get("x-mfa-Username"),
UserDisplayName: r.Header.Get("x-mfa-UserDisplayName"),
UserIcon: r.Header.Get("x-mfa-UserIcon"),
}
// check that required fields are provided
if meta.RPDisplayName == "" {
msg := "missing required header: x-mfa-RPDisplayName"
return ApiMeta{}, fmt.Errorf(msg)
}
if meta.RPID == "" {
msg := "missing required header: x-mfa-RPID"
return ApiMeta{}, fmt.Errorf(msg)
}
if meta.Username == "" {
msg := "missing required header: x-mfa-Username"
return ApiMeta{}, fmt.Errorf(msg)
}
if meta.UserDisplayName == "" {
msg := "missing required header: x-mfa-UserDisplayName"
return ApiMeta{}, fmt.Errorf(msg)
}
return meta, nil
}
func getUserFromContext(r *http.Request) (*DynamoUser, error) {
user, ok := r.Context().Value(UserContextKey).(*DynamoUser)
if !ok {
return &DynamoUser{}, errors.New("unable to get user from request context")
}
return user, nil
}
func AuthenticateRequest(r *http.Request) (*DynamoUser, error) {
// get key and secret from headers
key := r.Header.Get("x-mfa-apikey")
secret := r.Header.Get("x-mfa-apisecret")
if key == "" || secret == "" {
return nil, fmt.Errorf("x-mfa-apikey and x-mfa-apisecret are required")
}
log.Printf("API called by key: %s. %s %s", key, r.Method, r.RequestURI)
localStorage, err := NewStorage(envConfig.AWSConfig)
if err != nil {
return nil, fmt.Errorf("error initializing storage: %s", err.Error())
}
apiKey := ApiKey{
Key: key,
Secret: secret,
Store: localStorage,
}
err = apiKey.Load()
if err != nil {
return nil, fmt.Errorf("failed to load api key: %s", err.Error())
}
if apiKey.ActivatedAt == 0 {
return nil, fmt.Errorf("api call attempted for not yet activated key: %s", apiKey.Key)
}
valid, err := apiKey.IsCorrect(secret)
if err != nil {
return nil, fmt.Errorf("failed to validate api key: %s", err.Error())
}
if !valid {
return nil, fmt.Errorf("invalid api secret for key %s: %s", key, err.Error())
}
// apiMeta includes info about the user and webauthn config
apiMeta, err := getApiMetaFromRequest(r)
if err != nil {
msg := fmt.Sprintf("unable to retrieve api meta information from request: %s", err.Error())
log.Println(msg)
return nil, fmt.Errorf(msg)
}
webAuthnClient, err := getWebAuthnFromApiMeta(apiMeta)
if err != nil {
return nil, fmt.Errorf("unable to create webauthn client from api meta config: %s", err.Error())
}
user := NewDynamoUser(apiMeta, localStorage, apiKey, webAuthnClient)
// If this user exists (api key value is not empty), make sure the calling API Key owns the user and is allowed to operate on it
if user.ApiKeyValue != "" && user.ApiKeyValue != apiKey.Key {
log.Printf("api key %s tried to access user %s but that user does not belong to that api key", apiKey.Key, user.ID)
return nil, fmt.Errorf("user does not exist")
}
return &user, nil
}