Debian Codegraph @

passvault/passvault.go

raw symbols SCIP
1 // Package passvault manages the vault containing user records on
2 // disk. It contains usernames and associated passwords which are
3 // stored hashed (with salt) using scrypt.
4 //
5 // Copyright (c) 2013 CloudFlare, Inc.
6
7 package passvault
8
9 import (
10 "bytes"
11 "crypto/aes"
12 "crypto/ecdsa"
13 "crypto/elliptic"
14 "crypto/rand"
15 "crypto/rsa"
16 "crypto/sha1"
17 "crypto/x509"
18 "encoding/binary"
19 "encoding/json"
20 "errors"
21 "io/ioutil"
22 "math/big"
23 mrand "math/rand"
24 "os"
25
26 "github.com/cloudflare/redoctober/ecdh"
27 "github.com/cloudflare/redoctober/padding"
28 "github.com/cloudflare/redoctober/symcrypt"
29 "golang.org/x/crypto/scrypt"
30 )
31
32 // Constants for record type
33 const (
34 RSARecord = "RSA"
35 ECCRecord = "ECC"
36 )
37
38 var DefaultRecordType = RSARecord
39
40 // Constants for scrypt
41 const (
42 KEYLENGTH = 16 // 16-byte output from scrypt
43 N = 16384 // Cost parameter
44 R = 8 // Block size
45 P = 1 // Parallelization factor
46
47 DEFAULT_VERSION = 1
48 )
49
50 type ECPublicKey struct {
51 Curve *elliptic.CurveParams
52 X, Y *big.Int
53 }
54
55 // toECDSA takes the internal ECPublicKey and returns an equivalent
56 // an ecdsa.PublicKey
57 func (pk *ECPublicKey) toECDSA() *ecdsa.PublicKey {
58 ecdsaPub := new(ecdsa.PublicKey)
59 ecdsaPub.Curve = pk.Curve
60 ecdsaPub.X = pk.X
61 ecdsaPub.Y = pk.Y
62
63 return ecdsaPub
64 }
65
66 // PasswordRecord is the structure used to store password and key
67 // material for a single user name. It is written and read from
68 // storage in JSON format.
69 type PasswordRecord struct {
70 Type string
71 PasswordSalt []byte
72 HashedPassword []byte
73 KeySalt []byte
74 RSAKey struct {
75 RSAExp []byte
76 RSAExpIV []byte
77 RSAPrimeP []byte
78 RSAPrimePIV []byte
79 RSAPrimeQ []byte
80 RSAPrimeQIV []byte
81 RSAPublic rsa.PublicKey
82 }
83 ECKey struct {
84 ECPriv []byte
85 ECPrivIV []byte
86 ECPublic ECPublicKey
87 }
88 AltNames map[string]string
89 Admin bool
90 }
91
92 // diskRecords is the structure used to read and write a JSON file
93 // containing the contents of a password vault
94 type Records struct {
95 Version int
96 VaultId int
97 HmacKey []byte
98 Passwords map[string]PasswordRecord
99
100 localPath string // Path of current vault
101 }
102
103 // Summary is a minmial account summary.
104 type Summary struct {
105 Admin bool
106 Type string
107 }
108
109 func init() {
110 // seed math.random from crypto.random
111 seedBytes, _ := symcrypt.MakeRandom(8)
112 seedBuf := bytes.NewBuffer(seedBytes)
113 n64, _ := binary.ReadVarint(seedBuf)
114 mrand.Seed(n64)
115 }
116
117 // hashPassword takes a password and derives a scrypt salted and hashed
118 // version
119 func hashPassword(password string, salt []byte) ([]byte, error) {
120 return scrypt.Key([]byte(password), salt, N, R, P, KEYLENGTH)
121 }
122
123 // encryptRSARecord takes an RSA private key and encrypts it with
124 // a password key
125 func encryptRSARecord(newRec *PasswordRecord, rsaPriv *rsa.PrivateKey, passKey []byte) (err error) {
126 if newRec.RSAKey.RSAExpIV, err = symcrypt.MakeRandom(16); err != nil {
127 return
128 }
129
130 paddedExponent := padding.AddPadding(rsaPriv.D.Bytes())
131 if newRec.RSAKey.RSAExp, err = symcrypt.EncryptCBC(paddedExponent, newRec.RSAKey.RSAExpIV, passKey); err != nil {
132 return
133 }
134
135 if newRec.RSAKey.RSAPrimePIV, err = symcrypt.MakeRandom(16); err != nil {
136 return
137 }
138
139 paddedPrimeP := padding.AddPadding(rsaPriv.Primes[0].Bytes())
140 if newRec.RSAKey.RSAPrimeP, err = symcrypt.EncryptCBC(paddedPrimeP, newRec.RSAKey.RSAPrimePIV, passKey); err != nil {
141 return
142 }
143
144 if newRec.RSAKey.RSAPrimeQIV, err = symcrypt.MakeRandom(16); err != nil {
145 return
146 }
147
148 paddedPrimeQ := padding.AddPadding(rsaPriv.Primes[1].Bytes())
149 newRec.RSAKey.RSAPrimeQ, err = symcrypt.EncryptCBC(paddedPrimeQ, newRec.RSAKey.RSAPrimeQIV, passKey)
150 return
151 }
152
153 // encryptECCRecord takes an ECDSA private key and encrypts it with
154 // a password key.
155 func encryptECCRecord(newRec *PasswordRecord, ecPriv *ecdsa.PrivateKey, passKey []byte) (err error) {
156 ecX509, err := x509.MarshalECPrivateKey(ecPriv)
157 if err != nil {
158 return
159 }
160
161 if newRec.ECKey.ECPrivIV, err = symcrypt.MakeRandom(16); err != nil {
162 return
163 }
164
165 paddedX509 := padding.AddPadding(ecX509)
166 newRec.ECKey.ECPriv, err = symcrypt.EncryptCBC(paddedX509, newRec.ECKey.ECPrivIV, passKey)
167 return
168 }
169
170 // createPasswordRec creates a new record from a username and password
171 func createPasswordRec(password string, admin bool, userType string) (newRec PasswordRecord, err error) {
172 newRec.Type = userType
173
174 if newRec.PasswordSalt, err = symcrypt.MakeRandom(16); err != nil {
175 return
176 }
177
178 if newRec.HashedPassword, err = hashPassword(password, newRec.PasswordSalt); err != nil {
179 return
180 }
181
182 if newRec.KeySalt, err = symcrypt.MakeRandom(16); err != nil {
183 return
184 }
185
186 passKey, err := derivePasswordKey(password, newRec.KeySalt)
187 if err != nil {
188 return
189 }
190
191 newRec.AltNames = make(map[string]string)
192
193 // generate a key pair
194 switch userType {
195 case RSARecord:
196 var rsaPriv *rsa.PrivateKey
197 rsaPriv, err = rsa.GenerateKey(rand.Reader, 2048)
198 if err != nil {
199 return
200 }
201 // encrypt RSA key with password key
202 if err = encryptRSARecord(&newRec, rsaPriv, passKey); err != nil {
203 return
204 }
205 newRec.RSAKey.RSAPublic = rsaPriv.PublicKey
206 case ECCRecord:
207 var ecPriv *ecdsa.PrivateKey
208 ecPriv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
209 if err != nil {
210 return
211 }
212 // encrypt ECDSA key with password key
213 if err = encryptECCRecord(&newRec, ecPriv, passKey); err != nil {
214 return
215 }
216 newRec.ECKey.ECPublic.Curve = ecPriv.PublicKey.Curve.Params()
217 newRec.ECKey.ECPublic.X = ecPriv.PublicKey.X
218 newRec.ECKey.ECPublic.Y = ecPriv.PublicKey.Y
219 default:
220 err = errors.New("Unknown record type")
221 }
222
223 newRec.Admin = admin
224
225 return
226 }
227
228 // derivePasswordKey generates a key from a password (and salt) using
229 // scrypt
230 func derivePasswordKey(password string, keySalt []byte) ([]byte, error) {
231 return scrypt.Key([]byte(password), keySalt, N, R, P, KEYLENGTH)
232 }
233
234 // decryptECB decrypts bytes using a key in AES ECB mode.
235 func decryptECB(data, key []byte) (decryptedData []byte, err error) {
236 aesCrypt, err := aes.NewCipher(key)
237 if err != nil {
238 return
239 }
240
241 decryptedData = make([]byte, len(data))
242 aesCrypt.Decrypt(decryptedData, data)
243
244 return
245 }
246
247 // encryptECB encrypts bytes using a key in AES ECB mode.
248 func encryptECB(data, key []byte) (encryptedData []byte, err error) {
249 aesCrypt, err := aes.NewCipher(key)
250 if err != nil {
251 return
252 }
253
254 encryptedData = make([]byte, len(data))
255 aesCrypt.Encrypt(encryptedData, data)
256
257 return
258 }
259
260 // InitFromDisk reads the record from disk and initialize global context.
261 func InitFrom(path string) (records Records, err error) {
262 var jsonDiskRecord []byte
263
264 if path != "memory" {
265 jsonDiskRecord, err = ioutil.ReadFile(path)
266
267 // It's OK for the file to be missing, we'll create it later if
268 // anything is added.
269
270 if err != nil && !os.IsNotExist(err) {
271 return
272 }
273 }
274
275 // Initialized so that we can determine later if anything was read
276 // from the file.
277
278 records.Version = 0
279 if len(jsonDiskRecord) != 0 {
280 if err = json.Unmarshal(jsonDiskRecord, &records); err != nil {
281 return
282 }
283 }
284
285 err = errors.New("Format error")
286 for k, rec := range records.Passwords {
287
288 if rec.AltNames == nil {
289 rec.AltNames = make(map[string]string)
290 records.Passwords[k] = rec
291 }
292 if len(rec.PasswordSalt) != 16 {
293 return
294 }
295 if len(rec.HashedPassword) != 16 {
296 return
297 }
298 if len(rec.KeySalt) != 16 {
299 return
300 }
301 if rec.Type == RSARecord {
302 if len(rec.RSAKey.RSAExp) == 0 || len(rec.RSAKey.RSAExp)%16 != 0 {
303 return
304 }
305 if len(rec.RSAKey.RSAPrimeP) == 0 || len(rec.RSAKey.RSAPrimeP)%16 != 0 {
306 return
307 }
308 if len(rec.RSAKey.RSAPrimeQ) == 0 || len(rec.RSAKey.RSAPrimeQ)%16 != 0 {
309 return
310 }
311 if len(rec.RSAKey.RSAExpIV) != 16 {
312 return
313 }
314 if len(rec.RSAKey.RSAPrimePIV) != 16 {
315 return
316 }
317 if len(rec.RSAKey.RSAPrimeQIV) != 16 {
318 return
319 }
320 }
321 if rec.Type == ECCRecord {
322 if len(rec.ECKey.ECPriv) == 0 || len(rec.ECKey.ECPriv)%16 != 0 {
323 return
324 }
325 if len(rec.ECKey.ECPrivIV) != 16 {
326 return
327 }
328 }
329 }
330
331 // If the Version field is 0 then it indicates that nothing was
332 // read from the file and so it needs to be initialized.
333
334 if records.Version == 0 {
335 records.Version = DEFAULT_VERSION
336 records.VaultId = int(mrand.Int31())
337 records.HmacKey, err = symcrypt.MakeRandom(16)
338 if err != nil {
339 return
340 }
341 records.Passwords = make(map[string]PasswordRecord)
342 }
343
344 records.localPath = path
345
346 err = nil
347 return
348 }
349
350 // WriteRecordsToDisk saves the current state of the records to disk.
351 func (records *Records) WriteRecordsToDisk() error {
352 if records.localPath == "memory" {
353 return nil
354 }
355
356 jsonDiskRecord, err := json.Marshal(records)
357 if err != nil {
358 return err
359 }
360 return ioutil.WriteFile(records.localPath, jsonDiskRecord, 0644)
361 }
362
363 // AddNewRecord adds a new record for a given username and password.
364 func (records *Records) AddNewRecord(name, password string, admin bool, userType string) (PasswordRecord, error) {
365 pr, err := createPasswordRec(password, admin, userType)
366 if err != nil {
367 return pr, err
368 }
369 records.SetRecord(pr, name)
370 return pr, records.WriteRecordsToDisk()
371 }
372
373 // ChangePassword changes the password for a given user.
374 func (records *Records) ChangePassword(name, password, newPassword, hipchatName string) (err error) {
375 pr, ok := records.GetRecord(name)
376
377 if !ok {
378 err = errors.New("Record not present")
379 return
380 }
381
382 if len(hipchatName) != 0 {
383 pr.AltNames["HipchatName"] = hipchatName
384 }
385
386 if len(newPassword) == 0 {
387 records.SetRecord(pr, name)
388 return records.WriteRecordsToDisk()
389 }
390
391 var keySalt []byte
392 if keySalt, err = symcrypt.MakeRandom(16); err != nil {
393 return
394 }
395 newPassKey, err := derivePasswordKey(newPassword, keySalt)
396 if err != nil {
397 return
398 }
399
400 // decrypt with old password and re-encrypt original key with new password
401 if pr.Type == RSARecord {
402 var rsaKey rsa.PrivateKey
403 rsaKey, err = pr.GetKeyRSA(password)
404 if err != nil {
405 return
406 }
407
408 // encrypt RSA key with password key
409 err = encryptRSARecord(&pr, &rsaKey, newPassKey)
410 if err != nil {
411 return
412 }
413 } else if pr.Type == ECCRecord {
414 var ecKey *ecdsa.PrivateKey
415 ecKey, err = pr.GetKeyECC(password)
416 if err != nil {
417 return
418 }
419
420 // encrypt ECDSA key with password key
421 err = encryptECCRecord(&pr, ecKey, newPassKey)
422 if err != nil {
423 return
424 }
425 } else {
426 err = errors.New("Unkown record type")
427 return
428 }
429
430 // add the password salt and hash
431 if pr.PasswordSalt, err = symcrypt.MakeRandom(16); err != nil {
432 return
433 }
434 if pr.HashedPassword, err = hashPassword(newPassword, pr.PasswordSalt); err != nil {
435 return
436 }
437
438 pr.KeySalt = keySalt
439
440 records.SetRecord(pr, name)
441
442 return records.WriteRecordsToDisk()
443 }
444
445 // DeleteRecord deletes a given record.
446 func (records *Records) DeleteRecord(name string) error {
447 if _, ok := records.GetRecord(name); ok {
448 delete(records.Passwords, name)
449 return records.WriteRecordsToDisk()
450 }
451 return errors.New("Record missing")
452 }
453
454 // RevokeRecord removes admin status from a record.
455 func (records *Records) RevokeRecord(name string) error {
456 if rec, ok := records.GetRecord(name); ok {
457 rec.Admin = false
458 records.SetRecord(rec, name)
459 return records.WriteRecordsToDisk()
460 }
461 return errors.New("Record missing")
462 }
463
464 // MakeAdmin adds admin status to a given record.
465 func (records *Records) MakeAdmin(name string) error {
466 if rec, ok := records.GetRecord(name); ok {
467 rec.Admin = true
468 records.SetRecord(rec, name)
469 return records.WriteRecordsToDisk()
470 }
471 return errors.New("Record missing")
472 }
473
474 // SetRecord puts a record into the global status.
475 func (records *Records) SetRecord(pr PasswordRecord, name string) {
476 records.Passwords[name] = pr
477 }
478
479 // GetRecord returns a record given a name.
480 func (records *Records) GetRecord(name string) (PasswordRecord, bool) {
481 dpr, found := records.Passwords[name]
482 return dpr, found
483 }
484
485 // GetVaultId returns the id of the current vault.
486 func (records *Records) GetVaultID() (id int, err error) {
487 return records.VaultId, nil
488 }
489
490 // GetHmacKey returns the hmac key of the current vault.
491 func (records *Records) GetHMACKey() (key []byte, err error) {
492 return records.HmacKey, nil
493 }
494
495 // NumRecords returns the number of records in the vault.
496 func (records *Records) NumRecords() int {
497 return len(records.Passwords)
498 }
499
500 // GetSummary returns a summary of the records on disk.
501 func (records *Records) GetSummary() (summary map[string]Summary) {
502 summary = make(map[string]Summary)
503 for name, pass := range records.Passwords {
504 summary[name] = Summary{pass.Admin, pass.Type}
505 }
506 return
507 }
508
509 // IsAdmin returns the admin status of the PasswordRecord.
510 func (pr *PasswordRecord) IsAdmin() bool {
511 return pr.Admin
512 }
513
514 // GetType returns the type status of the PasswordRecord.
515 func (pr *PasswordRecord) GetType() string {
516 return pr.Type
517 }
518
519 // EncryptKey encrypts a 16-byte key with the RSA or EC key of the record.
520 func (pr *PasswordRecord) EncryptKey(in []byte) (out []byte, err error) {
521 if pr.Type == RSARecord {
522 return rsa.EncryptOAEP(sha1.New(), rand.Reader, &pr.RSAKey.RSAPublic, in, nil)
523 } else if pr.Type == ECCRecord {
524 return ecdh.Encrypt(pr.ECKey.ECPublic.toECDSA(), in)
525 } else {
526 return nil, errors.New("Invalid function for record type")
527 }
528 }
529
530 // GetKeyRSAPub returns the RSA public key of the record.
531 func (pr *PasswordRecord) GetKeyRSAPub() (out *rsa.PublicKey, err error) {
532 if pr.Type != RSARecord {
533 return out, errors.New("Invalid function for record type")
534 }
535 return &pr.RSAKey.RSAPublic, err
536 }
537
538 // GetKeyECCPub returns the ECDSA public key out of the record.
539 func (pr *PasswordRecord) GetKeyECCPub() (out *ecdsa.PublicKey, err error) {
540 if pr.Type != ECCRecord {
541 return out, errors.New("Invalid function for record type")
542 }
543 return pr.ECKey.ECPublic.toECDSA(), err
544 }
545
546 // GetKeyECC returns the ECDSA private key of the record given the correct password.
547 func (pr *PasswordRecord) GetKeyECC(password string) (key *ecdsa.PrivateKey, err error) {
548 if pr.Type != ECCRecord {
549 return key, errors.New("Invalid function for record type")
550 }
551
552 if err = pr.ValidatePassword(password); err != nil {
553 return
554 }
555
556 passKey, err := derivePasswordKey(password, pr.KeySalt)
557 if err != nil {
558 return
559 }
560
561 x509Padded, err := symcrypt.DecryptCBC(pr.ECKey.ECPriv, pr.ECKey.ECPrivIV, passKey)
562 if err != nil {
563 return
564 }
565
566 ecX509, err := padding.RemovePadding(x509Padded)
567 if err != nil {
568 return
569 }
570 return x509.ParseECPrivateKey(ecX509)
571 }
572
573 // GetKeyRSA returns the RSA private key of the record given the correct password.
574 func (pr *PasswordRecord) GetKeyRSA(password string) (key rsa.PrivateKey, err error) {
575 if pr.Type != RSARecord {
576 return key, errors.New("Invalid function for record type")
577 }
578
579 err = pr.ValidatePassword(password)
580 if err != nil {
581 return
582 }
583
584 passKey, err := derivePasswordKey(password, pr.KeySalt)
585 if err != nil {
586 return
587 }
588
589 rsaExponentPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAExp, pr.RSAKey.RSAExpIV, passKey)
590 if err != nil {
591 return
592 }
593 rsaExponent, err := padding.RemovePadding(rsaExponentPadded)
594 if err != nil {
595 return
596 }
597
598 rsaPrimePPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeP, pr.RSAKey.RSAPrimePIV, passKey)
599 if err != nil {
600 return
601 }
602 rsaPrimeP, err := padding.RemovePadding(rsaPrimePPadded)
603 if err != nil {
604 return
605 }
606
607 rsaPrimeQPadded, err := symcrypt.DecryptCBC(pr.RSAKey.RSAPrimeQ, pr.RSAKey.RSAPrimeQIV, passKey)
608 if err != nil {
609 return
610 }
611 rsaPrimeQ, err := padding.RemovePadding(rsaPrimeQPadded)
612 if err != nil {
613 return
614 }
615
616 key.PublicKey = pr.RSAKey.RSAPublic
617 key.D = big.NewInt(0).SetBytes(rsaExponent)
618 key.Primes = []*big.Int{big.NewInt(0), big.NewInt(0)}
619 key.Primes[0].SetBytes(rsaPrimeP)
620 key.Primes[1].SetBytes(rsaPrimeQ)
621
622 err = key.Validate()
623 if err != nil {
624 return
625 }
626
627 return
628 }
629 func (r *Records) GetAltNameFromName(alt, name string) (altName string, found bool) {
630 if passwordRecord, ok := r.Passwords[name]; ok {
631 if altName, ok := passwordRecord.AltNames[alt]; ok {
632 return altName, true
633 }
634 }
635 return "", false
636 }
637 func (r *Records) GetAltNamesFromName(alt string, names []string) map[string]string {
638 altNames := make(map[string]string)
639 for _, name := range names {
640 altName, found := r.GetAltNameFromName(alt, name)
641 if !found {
642 altName = name
643 }
644 altNames[name] = altName
645 }
646 return altNames
647
648 }
649
650 // ValidatePassword returns an error if the password is incorrect.
651 func (pr *PasswordRecord) ValidatePassword(password string) error {
652 h, err := hashPassword(password, pr.PasswordSalt)
653 if err != nil {
654 return err
655 }
656
657 if bytes.Compare(h, pr.HashedPassword) != 0 {
658 return errors.New("Wrong Password")
659 }
660 return nil
661 }