-
Notifications
You must be signed in to change notification settings - Fork 49
/
operations.go
336 lines (289 loc) · 9.37 KB
/
operations.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
package keysharecore
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/binary"
"time"
"github.com/privacybydesign/gabi"
"github.com/privacybydesign/gabi/big"
"github.com/privacybydesign/gabi/gabikeys"
irma "github.com/privacybydesign/irmago"
"github.com/go-errors/errors"
"github.com/golang-jwt/jwt/v4"
)
var (
ErrInvalidPin = errors.New("invalid pin")
ErrPinTooLong = errors.New("pin too long")
ErrInvalidChallenge = errors.New("challenge out of bounds")
ErrInvalidJWT = errors.New("invalid jwt token")
ErrExpiredJWT = errors.New("jwt expired")
ErrKeyNotFound = errors.New("public key not found")
ErrUnknownCommit = errors.New("unknown commit id")
ErrChallengeResponseRequired = errors.New("challenge-response authentication required")
ErrWrongChallenge = errors.New("wrong challenge")
)
// ChallengeJWTMaxExpiry is the maximum exp (expiry) that we allow JWTs to have with which calls to
// GenerateChallenge() (i.e. /users/verify_start) are authenticated.
const ChallengeJWTMaxExpiry = 6 * time.Minute
// NewUserSecrets generates a new keyshare secret, secured with the given pin.
func (c *Core) NewUserSecrets(pin string, pk *ecdsa.PublicKey) (UserSecrets, error) {
secret, err := gabi.NewKeyshareSecret()
if err != nil {
return nil, err
}
id := make([]byte, 32)
_, err = rand.Read(id)
if err != nil {
return nil, err
}
// Build unencrypted secrets
var s unencryptedUserSecrets
if err = s.setPin(pin); err != nil {
return nil, err
}
if err = s.setKeyshareSecret(secret); err != nil {
return nil, err
}
if err = s.setID(id); err != nil {
return nil, err
}
s.PublicKey = pk
// And encrypt
return c.encryptUserSecrets(s)
}
// ValidateAuth checks pin for validity and generates JWT for future access.
func (c *Core) ValidateAuth(secrets UserSecrets, jwtt string) (string, error) {
s, err := c.decryptUserSecrets(secrets)
if err != nil {
return "", err
}
pin, err := c.verifyChallengeResponse(s, jwtt)
if err != nil {
return "", err
}
if err = s.verifyPin(pin); err != nil {
return "", err
}
return c.authJWT(&s)
}
func (c *Core) authJWT(s *unencryptedUserSecrets) (string, error) {
t := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"iss": c.jwtIssuer,
"sub": "auth_tok",
"iat": t.Unix(),
"exp": t.Add(time.Duration(c.jwtPinExpiry) * time.Second).Unix(),
"token_id": base64.StdEncoding.EncodeToString(s.ID),
})
token.Header["kid"] = c.jwtPrivateKeyID
return token.SignedString(c.jwtPrivateKey)
}
func (c *Core) verifyChallengeResponse(s unencryptedUserSecrets, jwtt string) (string, error) {
challenge := c.consumeChallenge(s.ID)
if challenge == nil {
return "", ErrChallengeResponseRequired
}
claims := &irma.KeyshareAuthResponseClaims{}
if _, err := jwt.ParseWithClaims(jwtt, claims, s.publicKey); err != nil {
return "", err
}
if subtle.ConstantTimeCompare(challenge, claims.Challenge) != 1 {
return "", ErrWrongChallenge
}
return claims.Pin, nil
}
// ValidateJWT checks whether the given JWT is currently valid as an access token for operations
// on the provided encrypted keyshare user secrets.
func (c *Core) ValidateJWT(secrets UserSecrets, jwt string) error {
_, err := c.verifyAccess(secrets, jwt)
return err
}
// ChangePin changes the pin in an encrypted keyshare user secret to a new value, after validating that
// the request was validly signed and that the old value is known by the caller.
func (c *Core) ChangePin(secrets UserSecrets, jwtt string) (UserSecrets, error) {
s, err := c.decryptUserSecrets(secrets)
if err != nil {
return nil, err
}
claims := &irma.KeyshareChangePinClaims{}
if _, err = jwt.ParseWithClaims(jwtt, claims, s.publicKey); err != nil {
return nil, err
}
if err = s.verifyPin(claims.OldPin); err != nil {
return nil, err
}
// change and reencrypt
id := make([]byte, 32)
_, err = rand.Read(id)
if err != nil {
return nil, err
}
if err = s.setPin(claims.NewPin); err != nil {
return nil, err
}
if err = s.setID(id); err != nil {
return nil, err
}
return c.encryptUserSecrets(s)
}
// verifyAccess checks that a given access jwt is valid, and if so, return decrypted keyshare user secrets.
// Note: Although this is an internal function, it is tested directly
func (c *Core) verifyAccess(secrets UserSecrets, jwtToken string) (unencryptedUserSecrets, error) {
// Verify token validity
token, err := jwt.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
if token.Method != jwt.SigningMethodRS256 {
return nil, ErrInvalidJWT
}
return &c.jwtPrivateKey.PublicKey, nil
})
if err != nil {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || claims.Valid() != nil {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return unencryptedUserSecrets{}, ErrExpiredJWT
}
if _, present := claims["token_id"]; !present {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
tokenIDB64, ok := claims["token_id"].(string)
if !ok {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
tokenID, err := base64.StdEncoding.DecodeString(tokenIDB64)
if err != nil {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
s, err := c.decryptUserSecrets(secrets)
if err != nil {
return unencryptedUserSecrets{}, err
}
if subtle.ConstantTimeCompare(s.ID, tokenID) != 1 {
return unencryptedUserSecrets{}, ErrInvalidJWT
}
return s, nil
}
// GenerateCommitments generates keyshare commitments using the specified Idemix public key(s).
func (c *Core) GenerateCommitments(secrets UserSecrets, accessToken string, keyIDs []irma.PublicKeyIdentifier) ([]*gabi.ProofPCommitment, uint64, error) {
// Validate input request and build key list
var keyList []*gabikeys.PublicKey
for _, keyID := range keyIDs {
key, ok := c.trustedKeys[keyID]
if !ok {
return nil, 0, ErrKeyNotFound
}
keyList = append(keyList, key)
}
// verify access and decrypt
s, err := c.verifyAccess(secrets, accessToken)
if err != nil {
return nil, 0, err
}
// Generate commitment
commitSecret, commitments, err := gabi.NewKeyshareCommitments(s.KeyshareSecret, keyList)
if err != nil {
return nil, 0, err
}
// Generate commitment id
var commitID uint64
err = binary.Read(rand.Reader, binary.LittleEndian, &commitID)
if err != nil {
return nil, 0, err
}
// Store commit in backing storage
c.commitmentMutex.Lock()
c.commitmentData[commitID] = commitSecret
c.commitmentMutex.Unlock()
return commitments, commitID, nil
}
// GenerateResponse generates the response of a zero-knowledge proof of the keyshare secret, for a given previous commit and challenge.
func (c *Core) GenerateResponse(secrets UserSecrets, accessToken string, commitID uint64, challenge *big.Int, keyID irma.PublicKeyIdentifier) (string, error) {
// Validate request
if uint(challenge.BitLen()) > gabikeys.DefaultSystemParameters[1024].Lh || challenge.Cmp(big.NewInt(0)) < 0 {
return "", ErrInvalidChallenge
}
key, ok := c.trustedKeys[keyID]
if !ok {
return "", ErrKeyNotFound
}
// verify access and decrypt
s, err := c.verifyAccess(secrets, accessToken)
if err != nil {
return "", err
}
// Fetch commit
c.commitmentMutex.Lock()
commit, ok := c.commitmentData[commitID]
delete(c.commitmentData, commitID)
c.commitmentMutex.Unlock()
if !ok {
return "", ErrUnknownCommit
}
// Generate response
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"ProofP": gabi.KeyshareResponse(s.KeyshareSecret, commit, challenge, key),
"iat": time.Now().Unix(),
"sub": "ProofP",
"iss": c.jwtIssuer,
})
token.Header["kid"] = c.jwtPrivateKeyID
return token.SignedString(c.jwtPrivateKey)
}
func (c *Core) GenerateChallenge(secrets UserSecrets, jwtt string) ([]byte, error) {
s, err := c.decryptUserSecrets(secrets)
if err != nil {
return nil, err
}
if s.PublicKey == nil {
return nil, errors.New("can't do challenge-response: no public key associated to account")
}
claims := &irma.KeyshareAuthRequestClaims{}
if _, err = jwt.ParseWithClaims(jwtt, claims, s.publicKey); err != nil {
return nil, err
}
// Impose explicit maximum on JWT expiry; we don't want eternally valid JWTs.
if claims.ExpiresAt == nil || claims.ExpiresAt.After(time.Now().Add(ChallengeJWTMaxExpiry)) {
return nil, errors.Errorf("JWT expiry may not be more than %s from now", ChallengeJWTMaxExpiry)
}
challenge := make([]byte, 32)
_, err = rand.Read(challenge)
if err != nil {
return nil, err
}
c.authChallengesMutex.Lock()
defer c.authChallengesMutex.Unlock()
c.authChallenges[string(s.ID)] = challenge
return challenge, nil
}
func (c *Core) consumeChallenge(id []byte) []byte {
c.authChallengesMutex.Lock()
defer c.authChallengesMutex.Unlock()
stringID := string(id)
challenge := c.authChallenges[stringID]
delete(c.authChallenges, stringID)
return challenge
}
func (c *Core) SetUserPublicKey(secrets UserSecrets, pin string, pk *ecdsa.PublicKey) (string, UserSecrets, error) {
s, err := c.decryptUserSecretsIfPinOK(secrets, pin)
if err != nil {
return "", nil, err
}
if s.PublicKey != nil {
return "", nil, errors.New("user already has public key")
}
s.PublicKey = pk
secrets, err = c.encryptUserSecrets(s)
if err != nil {
return "", nil, err
}
jwtt, err := c.authJWT(&s)
if err != nil {
return "", nil, err
}
return jwtt, secrets, nil
}