-
Notifications
You must be signed in to change notification settings - Fork 2
/
webauthn_manager.go
197 lines (170 loc) · 6.32 KB
/
webauthn_manager.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
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"html/template"
"log/slog"
"net/http"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/justinas/nosurf"
"github.com/lstoll/cookiesession"
)
type webauthnManager struct {
db *DB
webauthn *webauthn.WebAuthn
sessmgr *cookiesession.Manager[webSession, *webSession]
}
func (w *webauthnManager) AddHandlers(mux *http.ServeMux) {
mux.HandleFunc("/registration/begin", w.beginRegistration)
mux.HandleFunc("/registration/finish", w.finishRegistration)
mux.HandleFunc("GET /registration", w.registration)
}
// registration is a page used to add a new key. It should handle either a user
// in the session (from the logged in keys page), or a boostrap token and user
// id as query params for an inactive user.
func (w *webauthnManager) registration(rw http.ResponseWriter, req *http.Request) {
// first, check the URL for a registration token and user id. If it exists,
// check if we have the user and if they are active/with a matching token,
// embed it in the page.
uid := req.URL.Query().Get("user_id")
et := req.URL.Query().Get("enrollment_token")
if uid != "" && et != "" {
// we want to enroll a user. Find them, and match the token
user, err := w.db.GetUserByID(uid)
if err != nil {
w.httpErr(req.Context(), rw, fmt.Errorf("get user %s: %w", uid, err))
return
}
if user.EnrollmentKey == "" || subtle.ConstantTimeCompare([]byte(et), []byte(user.EnrollmentKey)) == 0 {
w.httpUnauth(rw, "either previous enrollment completed fine, or invalid enrollment")
return
}
sess := w.sessmgr.Get(req.Context())
sess.PendingWebauthnEnrollment = &pendingWebauthnEnrollment{
ForUserID: uid,
}
w.sessmgr.Save(req.Context(), sess)
}
// list keys will send the pending enrollment ID
w.execTemplate(rw, req, "register_key.tmpl.html", map[string]interface{}{})
}
func (w *webauthnManager) beginRegistration(rw http.ResponseWriter, req *http.Request) {
sess := w.sessmgr.Get(req.Context())
if sess.PendingWebauthnEnrollment == nil || sess.PendingWebauthnEnrollment.ForUserID == "" {
w.httpUnauth(rw, "no enroll to user id set in session")
return
}
user, err := w.db.GetUserByID(sess.PendingWebauthnEnrollment.ForUserID)
if err != nil {
w.httpErr(req.Context(), rw, fmt.Errorf("get user %s: %w", sess.PendingWebauthnEnrollment.ForUserID, err))
return
}
// postttttt this
keyName := req.URL.Query().Get("key_name")
if keyName == "" {
w.httpErr(req.Context(), rw, fmt.Errorf("key name required"))
return
}
authSelect := protocol.AuthenticatorSelection{
RequireResidentKey: protocol.ResidentKeyRequired(),
UserVerification: protocol.VerificationRequired,
}
conveyancePref := protocol.ConveyancePreference(protocol.PreferDirectAttestation)
options, sessionData, err := w.webauthn.BeginRegistration(user, webauthn.WithAuthenticatorSelection(authSelect), webauthn.WithConveyancePreference(conveyancePref))
if err != nil {
w.httpErr(req.Context(), rw, err)
return
}
sess.PendingWebauthnEnrollment.KeyName = keyName
sess.PendingWebauthnEnrollment.WebauthnSessionData = sessionData
w.sessmgr.Save(req.Context(), sess)
if err := json.NewEncoder(rw).Encode(options); err != nil {
w.httpErr(req.Context(), rw, err)
return
}
}
func (w *webauthnManager) finishRegistration(rw http.ResponseWriter, req *http.Request) {
sess := w.sessmgr.Get(req.Context())
if sess.PendingWebauthnEnrollment == nil || sess.PendingWebauthnEnrollment.ForUserID == "" {
w.httpUnauth(rw, "no enroll to user id set in session")
return
}
user, err := w.db.GetUserByID(sess.PendingWebauthnEnrollment.ForUserID) // TODO - guard the allow unactive for enrol only!
if err != nil {
w.httpErr(req.Context(), rw, fmt.Errorf("getting user %s: %w", sess.PendingWebauthnEnrollment.ForUserID, err))
return
}
if sess.PendingWebauthnEnrollment.WebauthnSessionData == nil {
w.httpErr(req.Context(), rw, fmt.Errorf("session data not in session"))
return
}
sessionData := *sess.PendingWebauthnEnrollment.WebauthnSessionData
keyName := sess.PendingWebauthnEnrollment.KeyName
// purge the data from the session
returnTo := sess.PendingWebauthnEnrollment.ReturnTo
sess.PendingWebauthnEnrollment = nil
w.sessmgr.Save(req.Context(), sess)
parsedResponse, err := protocol.ParseCredentialCreationResponseBody(req.Body)
if err != nil {
w.httpErr(req.Context(), rw, fmt.Errorf("parsing credential creation response: %w", err))
return
}
credential, err := w.webauthn.CreateCredential(user, sessionData, parsedResponse)
if err != nil {
w.httpErr(req.Context(), rw, fmt.Errorf("creating credential: %w", err))
return
}
if err := w.db.CreateUserCredential(user.ID, keyName, WebauthnCredential{Credential: *credential, Name: keyName, AddedAt: time.Now()}); err != nil {
w.httpErr(req.Context(), rw, err)
return
}
// OK
_ = returnTo
// TODO - return the next URL in the response, make the JS follow it.
}
func (w *webauthnManager) httpErr(ctx context.Context, rw http.ResponseWriter, err error) {
var (
pErr *protocol.Error
devinfo string
)
if errors.As(err, &pErr) {
devinfo = pErr.DevInfo
}
if errors.Is(err, ErrUserNotFound) || errors.Is(err, ErrUserNotActivated) {
http.Error(rw, err.Error(), http.StatusNotFound)
} else {
slog.ErrorContext(ctx, "webauthn manager error", logErr(err), slog.String("dev-info", devinfo))
http.Error(rw, "Internal Error", http.StatusInternalServerError)
}
}
func (w *webauthnManager) httpUnauth(rw http.ResponseWriter, msg string) {
http.Error(rw, fmt.Sprintf("Access denied: %s", msg), http.StatusForbidden)
}
func (w *webauthnManager) execTemplate(rw http.ResponseWriter, r *http.Request, templateName string, data interface{}) {
funcs := template.FuncMap{
"csrfField": func() template.HTML {
return template.HTML(fmt.Sprintf(`<input type="hidden" name="csrf_token" value="%s">`, nosurf.Token(r)))
},
"pathFor": func(_ string) string {
return "TODO"
},
}
lt, err := template.New("").Funcs(funcs).ParseFS(templates, "web/templates/webauthn/layout.tmpl.html")
if err != nil {
w.httpErr(r.Context(), rw, err)
}
t, err := lt.ParseFS(templates, "web/templates/webauthn/"+templateName)
if err != nil {
w.httpErr(r.Context(), rw, err)
return
}
if err := t.ExecuteTemplate(rw, templateName, data); err != nil {
w.httpErr(r.Context(), rw, err)
return
}
}