-
Notifications
You must be signed in to change notification settings - Fork 1
/
identity.go
537 lines (514 loc) · 17.4 KB
/
identity.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package e3db
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"strings"
"github.com/google/uuid"
e3dbClients "github.com/tozny/e3db-clients-go"
"github.com/tozny/e3db-clients-go/identityClient"
"github.com/tozny/e3db-clients-go/storageClient"
"golang.org/x/crypto/blake2b"
)
// Identity wraps a Tozny Identity, which contains identity, realm, and client information.
type Identity struct {
ID int64
Username string
FirstName string
LastName string
Realm *Realm
*ToznySDKV3
}
// Realm wraps information for connecting to a Tozny Identity realm with a specific application
type Realm struct {
Name string
App string
APIEndpoint string
BrokerTargetURL string
EmailExpiryMinutes int
realmInfo *identityClient.RealmInfo
}
type realmInfo struct {
Domain string
}
type IdentityData struct {
RealmName string `json:"realm_name"`
RealmDomain string `json:"realm_domain"`
AppName string `json:"app_name"`
APIEndpoint string `json:"api_url"`
UserID int64 `json:"user_id"`
BrokerTargetURL string `json:"broker_target_url"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
}
type serializedIdentity struct {
Config string `json:"config"`
Storage string `json:"storage"`
}
func (r *Realm) Info() (*identityClient.RealmInfo, error) {
if r.realmInfo == nil {
client := identityClient.New(e3dbClients.ClientConfig{
Host: r.APIEndpoint,
})
info, err := client.RealmInfo(context.Background(), r.Name)
if err != nil {
return r.realmInfo, err
}
r.realmInfo = info
}
return r.realmInfo, nil
}
func (r *Realm) Register(username, password, registrationToken, email, firstName, lastName string) (*Identity, error) {
identity := &Identity{
Realm: r,
}
if r.BrokerTargetURL == "" {
return identity, fmt.Errorf("realm BrokerTargetURL can not be empty")
}
encryptionKeyPair, err := e3dbClients.GenerateKeyPair()
if err != nil {
return identity, err
}
signingKeyPair, err := e3dbClients.GenerateSigningKeys()
if err != nil {
return identity, err
}
info, err := r.Info()
if err != nil {
return identity, err
}
payload := identityClient.RegisterIdentityRequest{
RealmRegistrationToken: registrationToken,
RealmName: info.Name,
Identity: identityClient.Identity{
Name: strings.ToLower(username),
Email: email,
PublicKeys: map[string]string{e3dbClients.DefaultEncryptionKeyType: encryptionKeyPair.Public.Material},
SigningKeys: map[string]string{signingKeyPair.Public.Type: signingKeyPair.Public.Material},
FirstName: firstName,
LastName: lastName,
},
}
client := identityClient.New(e3dbClients.ClientConfig{
Host: r.APIEndpoint,
})
registration, err := client.RegisterIdentity(context.Background(), payload)
if err != nil {
return identity, err
}
storageClient, err := NewToznySDKV3(ToznySDKConfig{
ClientConfig: e3dbClients.ClientConfig{
ClientID: registration.Identity.ToznyID.String(),
APIKey: registration.Identity.APIKeyID,
APISecret: registration.Identity.APIKeySecret,
Host: r.APIEndpoint,
AuthNHost: r.APIEndpoint,
EncryptionKeys: e3dbClients.EncryptionKeys{
Public: e3dbClients.Key{
Material: encryptionKeyPair.Public.Material,
Type: e3dbClients.DefaultEncryptionKeyType,
},
Private: e3dbClients.Key{
Material: encryptionKeyPair.Private.Material,
Type: e3dbClients.DefaultEncryptionKeyType,
},
},
SigningKeys: e3dbClients.SigningKeys{
Public: e3dbClients.Key{
Material: signingKeyPair.Public.Material,
Type: e3dbClients.DefaultSigningKeyType,
},
Private: e3dbClients.Key{
Material: signingKeyPair.Private.Material,
Type: e3dbClients.DefaultSigningKeyType,
},
},
},
APIEndpoint: r.APIEndpoint,
})
if err != nil {
return identity, err
}
identity.ID = registration.Identity.ID
identity.Username = registration.Identity.Name
identity.FirstName = registration.Identity.FirstName
identity.LastName = registration.Identity.LastName
identity.ToznySDKV3 = storageClient
_, err = identity.writePasswordNote(password)
if err != nil {
return identity, err
}
_, err = identity.writeBrokerNotes(email)
if err != nil {
return identity, err
}
return identity, nil
}
func (i *Identity) DeriveCredentails(password string, nameSalt string) (string, e3dbClients.EncryptionKeys, e3dbClients.SigningKeys, error) {
return e3dbClients.DeriveIdentityCredentials(i.Username, password, i.Realm.Name, nameSalt)
}
// ChangePassword Updates the password for an identity
func (i *Identity) ChangePassword(newPassword string) (*storageClient.Note, error) {
return i.updatePasswordNote(newPassword)
}
func (i *Identity) updatePasswordNote(password string) (*storageClient.Note, error) {
// Get Realm Info
info, err := i.Realm.Info()
if err != nil {
return &storageClient.Note{}, err
}
// Derive Credentials with new password
noteName, encryptionKeyPair, signingKeyPair, err := i.DeriveCredentails(password, "")
if err != nil {
return &storageClient.Note{}, err
}
// Prepare the Arguments needed
eacp := storageClient.TozIDEACP{
RealmName: info.Domain,
}
eacps := &storageClient.EACP{
TozIDEACP: &eacp,
}
return i.replaceNoteByName(noteName, &encryptionKeyPair, &signingKeyPair, eacps)
}
func (i *Identity) writePasswordNote(password string) (*storageClient.Note, error) {
info, err := i.Realm.Info()
if err != nil {
return &storageClient.Note{}, err
}
noteName, encryptionKeyPair, signingKeyPair, err := i.DeriveCredentails(password, "")
if err != nil {
return &storageClient.Note{}, err
}
eacp := storageClient.TozIDEACP{
RealmName: info.Domain,
}
eacps := &storageClient.EACP{
TozIDEACP: &eacp,
}
return i.writeCredentialNote(noteName, &encryptionKeyPair, &signingKeyPair, eacps)
}
func (i *Identity) writeBrokerNotes(email string) ([]*storageClient.Note, error) {
realmInfo, err := i.Realm.Info()
if err != nil {
return []*storageClient.Note{}, err
}
// Skip credential notes if there is no broker
if realmInfo.BrokerIdentityToznyID == uuid.Nil {
return []*storageClient.Note{}, nil
}
// Fetch the public broker info
brokerInfo, err := i.ClientInfo(context.Background(), realmInfo.BrokerIdentityToznyID.String())
if brokerInfo == nil {
err = fmt.Errorf("Broker info not found for realm %q", realmInfo.Name)
}
if err != nil {
return []*storageClient.Note{}, err
}
// If there is no broker, do not try to write broker notes
// otherwise, get the broker's info
// Email EACP
emailEACP := storageClient.EmailEACP{
EmailAddress: email,
Template: "claim_account",
ProviderLink: i.Realm.BrokerTargetURL,
DefaultExpirationMinutes: i.Realm.EmailExpiryMinutes,
}
// format the name based on if first and last are provided
name := ""
if i.FirstName != "" {
name = i.FirstName
}
if i.LastName != "" {
if name != "" {
name = name + " "
}
name = name + i.LastName
}
if name != "" {
emailEACP.TemplateFields = map[string]string{"name": name}
}
// Create struct for looping and processing
brokerNotes := []struct {
eacps *storageClient.EACP
keyPrefix string
keyType string
}{
{
eacps: &storageClient.EACP{
EmailEACP: &emailEACP,
},
keyPrefix: "brokerKey",
keyType: "broker",
},
{
eacps: &storageClient.EACP{
ToznyOTPEACP: &storageClient.ToznyOTPEACP{
Include: true,
},
},
keyPrefix: "broker_otp",
keyType: "tozny_otp",
},
}
writtenNotes := []*storageClient.Note{}
for _, noteInfo := range brokerNotes {
// TODO: refactor to run these concurrently
noteKey, keyNote, err := i.writeKeyNote(noteInfo.keyPrefix, brokerInfo.PublicKey.Curve25519, brokerInfo.SigningKey.Ed25519, noteInfo.eacps)
if err != nil {
return []*storageClient.Note{}, err
}
noteName, cryptoKeyPair, signingKeyPair, err := i.DeriveCredentails(noteKey, noteInfo.keyType)
if err != nil {
return []*storageClient.Note{}, err
}
keyNoteID, err := uuid.Parse(keyNote.NoteID)
if err != nil {
return []*storageClient.Note{}, err
}
brokeredEACP := &storageClient.EACP{
LastAccessEACP: &storageClient.LastAccessEACP{
LastReadNoteID: keyNoteID,
},
}
credentialNote, err := i.writeCredentialNote(noteName, &cryptoKeyPair, &signingKeyPair, brokeredEACP)
if err != nil {
return []*storageClient.Note{}, err
}
writtenNotes = append(writtenNotes, keyNote, credentialNote)
}
return writtenNotes, nil
}
func (i *Identity) writeCredentialNote(noteName string, encryptionKeyPair *e3dbClients.EncryptionKeys, signingKeyPair *e3dbClients.SigningKeys, eacps *storageClient.EACP) (*storageClient.Note, error) {
serialized, err := i.Serialize()
rawNoteBody := NoteBody{
"config": serialized.Config,
"storage": serialized.Storage,
}
rawCredentialNote := storageClient.Note{
IDString: noteName,
ClientID: i.ClientID,
Mode: e3dbClients.DefaultCryptographicMode,
RecipientSigningKey: signingKeyPair.Public.Material,
WriterSigningKey: i.StorageClient.SigningKeys.Public.Material,
WriterEncryptionKey: i.StorageClient.EncryptionKeys.Public.Material,
Data: rawNoteBody,
MaxViews: -1,
Expires: false,
EACPS: eacps,
}
// Sign over all the note data and the signature material itself
privateSigningKeyBytes, err := e3dbClients.Base64Decode(i.StorageClient.SigningKeys.Private.Material)
if err != nil {
return &storageClient.Note{}, err
}
notePrivateSigningKey := [e3dbClients.SigningKeySize]byte{}
copy(notePrivateSigningKey[:], privateSigningKeyBytes)
signingSalt := uuid.New().String()
signedNote, err := i.SignNote(rawCredentialNote, ¬ePrivateSigningKey, signingSalt)
if err != nil {
return &storageClient.Note{}, err
}
accessKey := e3dbClients.RandomSymmetricKey()
encryptedAccessKey, err := e3dbClients.EncryptAccessKey(accessKey, e3dbClients.EncryptionKeys{
Private: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: i.StorageClient.EncryptionKeys.Private.Material,
},
Public: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: encryptionKeyPair.Public.Material,
},
})
if err != nil {
return &storageClient.Note{}, err
}
// Encrypt the signed note and add the encrypted version of the access
// key to the note for the reader to be able to decrypt the note
encryptedNoteBody := e3dbClients.EncryptData(signedNote.Data, accessKey)
signedNote.Data = *encryptedNoteBody
signedNote.EncryptedAccessKey = encryptedAccessKey
// Write the credential note
credentialNote, err := i.WriteNote(context.Background(), signedNote)
if err != nil {
return &storageClient.Note{}, err
}
return credentialNote, nil
}
func (i *Identity) writeKeyNote(prefix, cryptoKey, signingKey string, eacps *storageClient.EACP) (string, *storageClient.Note, error) {
nameSeed := fmt.Sprintf("%s:%s@realm:%s", prefix, i.Username, i.Realm.Name)
hashedMessageAccumlator, err := blake2b.New(e3dbClients.Blake2BBytes, nil)
if err != nil {
return "", &storageClient.Note{}, err
}
hashedMessageAccumlator.Write([]byte(nameSeed))
hashedMessageBytes := hashedMessageAccumlator.Sum(nil)
noteName := e3dbClients.Base64Encode(hashedMessageBytes)
keyBytes := make([]byte, 64)
_, err = rand.Read(keyBytes)
if err != nil {
return "", &storageClient.Note{}, err
}
noteKey := e3dbClients.Base64Encode(keyBytes)
rawNoteBody := NoteBody{
"broker_key": noteKey,
"username": i.Username,
}
rawCredentialNote := storageClient.Note{
IDString: noteName,
ClientID: i.ClientID,
Mode: e3dbClients.DefaultCryptographicMode,
RecipientSigningKey: signingKey,
WriterSigningKey: i.StorageClient.SigningKeys.Public.Material,
WriterEncryptionKey: i.StorageClient.EncryptionKeys.Public.Material,
Data: rawNoteBody,
MaxViews: -1,
Expires: false,
EACPS: eacps,
}
// Sign over all the broker note data and the signature material itself
privateSigningKeyBytes, err := e3dbClients.Base64Decode(i.StorageClient.SigningKeys.Private.Material)
if err != nil {
return "", &storageClient.Note{}, err
}
notePrivateSigningKey := [e3dbClients.SigningKeySize]byte{}
copy(notePrivateSigningKey[:], privateSigningKeyBytes)
signingSalt := uuid.New().String()
signedNote, err := i.SignNote(rawCredentialNote, ¬ePrivateSigningKey, signingSalt)
if err != nil {
return "", &storageClient.Note{}, err
}
accessKey := e3dbClients.RandomSymmetricKey()
encryptedAccessKey, err := e3dbClients.EncryptAccessKey(accessKey, e3dbClients.EncryptionKeys{
Private: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: i.StorageClient.EncryptionKeys.Private.Material,
},
Public: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: cryptoKey,
},
})
if err != nil {
return "", &storageClient.Note{}, err
}
// Encrypt the signed note and add the encrypted version of the access
// key to the note for the reader to be able to decrypt the note
encryptedNoteBody := e3dbClients.EncryptData(signedNote.Data, accessKey)
signedNote.Data = *encryptedNoteBody
signedNote.EncryptedAccessKey = encryptedAccessKey
// Write the broker key note
keyNote, err := i.WriteNote(context.Background(), signedNote)
if err != nil {
return "", &storageClient.Note{}, err
}
return noteKey, keyNote, nil
}
func (i *Identity) Serialize() (serializedIdentity, error) {
var serialized serializedIdentity
info, err := i.Realm.Info()
if err != nil {
return serialized, err
}
config := IdentityData{
RealmName: i.Realm.Name,
RealmDomain: info.Domain,
AppName: i.Realm.App,
APIEndpoint: i.Realm.APIEndpoint,
UserID: i.ID,
BrokerTargetURL: i.Realm.BrokerTargetURL,
FirstName: i.FirstName,
LastName: i.LastName,
}
configBytes, err := json.Marshal(config)
if err != nil {
return serialized, err
}
storage := ClientConfig{
APIKeyID: i.StorageClient.APIKey,
APISecret: i.StorageClient.APISecret,
APIURL: i.APIEndpoint,
ClientEmail: "",
ClientID: i.ClientID,
PublicKey: i.StorageClient.EncryptionKeys.Public.Material,
PrivateKey: i.StorageClient.EncryptionKeys.Private.Material,
PublicSigningKey: i.StorageClient.SigningKeys.Public.Material,
PrivateSigningKey: i.StorageClient.SigningKeys.Private.Material,
Version: 2,
}
storageBytes, err := json.Marshal(storage)
if err != nil {
return serialized, err
}
serialized.Config = string(configBytes)
serialized.Storage = string(storageBytes)
return serialized, nil
}
func (i *Identity) createEncryptedNote(noteName string, encryptionKeyPair *e3dbClients.EncryptionKeys, signingKeyPair *e3dbClients.SigningKeys, eacps *storageClient.EACP) (*storageClient.Note, error) {
// Create Note
serialized, err := i.Serialize()
rawNoteBody := NoteBody{
"config": serialized.Config,
"storage": serialized.Storage,
}
rawCredentialNote := storageClient.Note{
IDString: noteName,
ClientID: i.ClientID,
Mode: e3dbClients.DefaultCryptographicMode,
RecipientSigningKey: signingKeyPair.Public.Material,
WriterSigningKey: i.StorageClient.SigningKeys.Public.Material,
WriterEncryptionKey: i.StorageClient.EncryptionKeys.Public.Material,
Data: rawNoteBody,
MaxViews: -1,
Expires: false,
EACPS: eacps,
}
// Sign over all the note data and the signature material itself
privateSigningKeyBytes, err := e3dbClients.Base64Decode(i.StorageClient.SigningKeys.Private.Material)
if err != nil {
return &storageClient.Note{}, err
}
// Sign the note with Private signing key
notePrivateSigningKey := [e3dbClients.SigningKeySize]byte{}
copy(notePrivateSigningKey[:], privateSigningKeyBytes)
signingSalt := uuid.New().String()
signedNote, err := i.SignNote(rawCredentialNote, ¬ePrivateSigningKey, signingSalt)
if err != nil {
return &storageClient.Note{}, err
}
accessKey := e3dbClients.RandomSymmetricKey()
// Create Encrypted Access Key
encryptedAccessKey, err := e3dbClients.EncryptAccessKey(accessKey, e3dbClients.EncryptionKeys{
Private: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: i.StorageClient.EncryptionKeys.Private.Material,
},
Public: e3dbClients.Key{
Type: e3dbClients.DefaultEncryptionKeyType,
Material: encryptionKeyPair.Public.Material,
},
})
if err != nil {
return &storageClient.Note{}, err
}
// Encrypt the signed note and add the encrypted version of the access
// key to the note for the reader to be able to decrypt the note
encryptedNoteBody := e3dbClients.EncryptData(signedNote.Data, accessKey)
signedNote.Data = *encryptedNoteBody
signedNote.EncryptedAccessKey = encryptedAccessKey
return &signedNote, nil
}
func (i *Identity) replaceNoteByName(noteName string, encryptionKeyPair *e3dbClients.EncryptionKeys, signingKeyPair *e3dbClients.SigningKeys, eacps *storageClient.EACP) (*storageClient.Note, error) {
// Create Encrypted Note, Using the encryption and signing keypair derived from the new password
signedNote, err := i.createEncryptedNote(noteName, encryptionKeyPair, signingKeyPair, eacps)
if err != nil {
return &storageClient.Note{}, err
}
// Update Note
credentialNote, err := i.UpsertNoteByIDString(context.Background(), *signedNote)
if err != nil {
return &storageClient.Note{}, err
}
return credentialNote, nil
}