Debian Codegraph @

cryptor/cryptor.go

raw symbols SCIP
1 // Package cryptor encrypts and decrypts files using the Red October
2 // vault and key cache.
3 //
4 // Copyright (c) 2013 CloudFlare, Inc.
5
6 package cryptor
7
8 import (
9 "crypto/aes"
10 "crypto/cipher"
11 "crypto/hmac"
12 "crypto/sha1"
13 "encoding/json"
14 "errors"
15 "log"
16 "sort"
17 "strconv"
18 "strings"
19
20 "github.com/cloudflare/redoctober/config"
21 "github.com/cloudflare/redoctober/keycache"
22 "github.com/cloudflare/redoctober/msp"
23 "github.com/cloudflare/redoctober/padding"
24 "github.com/cloudflare/redoctober/passvault"
25 "github.com/cloudflare/redoctober/persist"
26 "github.com/cloudflare/redoctober/symcrypt"
27 )
28
29 const (
30 DEFAULT_VERSION = 1
31 )
32
33 type Cryptor struct {
34 records *passvault.Records
35 cache *keycache.Cache
36 persist persist.Store
37 }
38
39 func New(records *passvault.Records, cache *keycache.Cache, config *config.Config) (*Cryptor, error) {
40 if cache == nil {
41 cache = &keycache.Cache{UserKeys: make(map[keycache.DelegateIndex]keycache.ActiveUser)}
42 }
43
44 store, err := persist.New(config.Delegations)
45 if err != nil {
46 return nil, err
47 }
48
49 c := &Cryptor{
50 records: records,
51 cache: cache,
52 persist: store,
53 }
54 return c, nil
55 }
56
57 // AccessStructure represents different possible access structures for
58 // encrypted data. If len(Names) > 0, then at least 2 of the users in the list
59 // must be delegated to decrypt. If len(LeftNames) > 0 & len(RightNames) > 0,
60 // then at least one from each list must be delegated (if the same user is in
61 // both, then he can decrypt it alone). If a predicate is present, it must be
62 // satisfied to decrypt.
63 type AccessStructure struct {
64 Minimum int
65 Names []string
66
67 LeftNames []string
68 RightNames []string
69
70 Predicate string
71 }
72
73 // Implements msp.UserDatabase
74 type UserDatabase struct {
75 names *[]string
76
77 records *passvault.Records
78 cache *keycache.Cache
79
80 user string
81 labels []string
82 keySet map[string]SingleWrappedKey
83 shareSet map[string][][]byte
84 }
85
86 func (u UserDatabase) ValidUser(name string) bool {
87 _, ok := u.records.GetRecord(name)
88 return ok
89 }
90
91 func (u UserDatabase) CanGetShare(name string) bool {
92 _, _, ok1 := u.cache.MatchUser(name, u.user, u.labels)
93 _, ok2 := u.shareSet[name]
94 _, ok3 := u.keySet[name]
95
96 return ok1 && ok2 && ok3
97 }
98
99 func (u UserDatabase) GetShare(name string) ([][]byte, error) {
100 *u.names = append(*u.names, name)
101
102 return u.cache.DecryptShares(
103 u.shareSet[name],
104 name,
105 u.user,
106 u.labels,
107 u.keySet[name].Key,
108 )
109 }
110
111 // MultiWrappedKey is a structure containing a 16-byte key encrypted
112 // once for each of the keys corresponding to the names of the users
113 // in Name in order.
114 type MultiWrappedKey struct {
115 Name []string
116 Key []byte
117 }
118
119 // SingleWrappedKey is a structure containing a 16-byte key encrypted
120 // by an RSA or EC key.
121 type SingleWrappedKey struct {
122 Key []byte
123 aesKey []byte
124 }
125
126 // EncryptedData is the format for encrypted data containing all the
127 // keys necessary to decrypt it when delegated.
128 type EncryptedData struct {
129 Version int
130 VaultId int `json:",omitempty"`
131 Labels []string `json:",omitempty"`
132 Predicate string `json:",omitempty"`
133 KeySet []MultiWrappedKey `json:",omitempty"`
134 KeySetRSA map[string]SingleWrappedKey `json:",omitempty"`
135 ShareSet map[string][][]byte `json:",omitempty"`
136 IV []byte `json:",omitempty"`
137 Data []byte
138 Signature []byte
139 }
140
141 type pair struct {
142 name string
143 key []byte
144 }
145
146 type mwkSlice []MultiWrappedKey
147 type swkSlice []pair
148
149 func (s mwkSlice) Len() int { return len(s) }
150 func (s mwkSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
151 func (s mwkSlice) Less(i, j int) bool { // Alphabetic order
152 var shorter = i
153 if len(s[i].Name) > len(s[j].Name) {
154 shorter = j
155 }
156
157 for index := range s[shorter].Name {
158 if s[i].Name[index] != s[j].Name[index] {
159 return s[i].Name[index] < s[j].Name[index]
160 }
161 }
162
163 return false
164 }
165
166 func (s swkSlice) Len() int { return len(s) }
167 func (s swkSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
168 func (s swkSlice) Less(i, j int) bool { return s[i].name < s[j].name }
169
170 // computeHmac computes the signature of the encrypted data structure
171 // the signature takes into account every element of the EncryptedData
172 // structure, with all keys sorted alphabetically by name
173 func (encrypted *EncryptedData) computeHmac(key []byte) []byte {
174 mac := hmac.New(sha1.New, key)
175
176 // sort the multi-wrapped keys
177 mwks := mwkSlice(encrypted.KeySet)
178 sort.Sort(mwks)
179
180 // sort the singly-wrapped keys
181 var swks swkSlice
182 for name, val := range encrypted.KeySetRSA {
183 swks = append(swks, pair{name, val.Key})
184 }
185 sort.Sort(&swks)
186
187 // sort the labels
188 sort.Strings(encrypted.Labels)
189
190 // start hashing
191 mac.Write([]byte(strconv.Itoa(encrypted.Version)))
192 mac.Write([]byte(strconv.Itoa(encrypted.VaultId)))
193
194 // hash the multi-wrapped keys
195 for _, mwk := range encrypted.KeySet {
196 for _, name := range mwk.Name {
197 mac.Write([]byte(name))
198 }
199 mac.Write(mwk.Key)
200 }
201
202 // hash the single-wrapped keys
203 for index := range swks {
204 mac.Write([]byte(swks[index].name))
205 mac.Write(swks[index].key)
206 }
207
208 // hash the IV and data
209 mac.Write(encrypted.IV)
210 mac.Write(encrypted.Data)
211
212 // hash the labels
213 for index := range encrypted.Labels {
214 mac.Write([]byte(encrypted.Labels[index]))
215 }
216
217 return mac.Sum(nil)
218 }
219
220 func (encrypted *EncryptedData) lock(key []byte) (err error) {
221 payload, err := json.Marshal(encrypted)
222 if err != nil {
223 return
224 }
225
226 mac := hmac.New(sha1.New, key)
227 mac.Write(payload)
228 sig := mac.Sum(nil)
229
230 *encrypted = EncryptedData{
231 Version: -1,
232 Data: payload,
233 Signature: sig,
234 }
235
236 return
237 }
238
239 func (encrypted *EncryptedData) unlock(key []byte) (err error) {
240 if encrypted.Version != -1 {
241 return
242 }
243
244 mac := hmac.New(sha1.New, key)
245 mac.Write(encrypted.Data)
246 sig := mac.Sum(nil)
247
248 if !hmac.Equal(encrypted.Signature, sig) {
249 err = errors.New("Signature mismatch")
250 return
251 }
252
253 return json.Unmarshal(encrypted.Data, encrypted)
254 }
255
256 // wrapKey encrypts the clear key according to an access structure.
257 func (encrypted *EncryptedData) wrapKey(records *passvault.Records, clearKey []byte, access AccessStructure) (err error) {
258 generateRandomKey := func(name string) (singleWrappedKey SingleWrappedKey, err error) {
259 rec, ok := records.GetRecord(name)
260 if !ok {
261 err = errors.New("Missing user on disk")
262 return
263 }
264
265 if singleWrappedKey.aesKey, err = symcrypt.MakeRandom(16); err != nil {
266 return
267 }
268
269 if singleWrappedKey.Key, err = rec.EncryptKey(singleWrappedKey.aesKey); err != nil {
270 return
271 }
272
273 return
274 }
275
276 encryptKey := func(keyNames []string, clearKey []byte) (keyBytes []byte, err error) {
277 keyBytes = make([]byte, 16)
278 copy(keyBytes, clearKey)
279 for _, keyName := range keyNames {
280 var keyCrypt cipher.Block
281 keyCrypt, err = aes.NewCipher(encrypted.KeySetRSA[keyName].aesKey)
282 if err != nil {
283 return
284 }
285
286 keyCrypt.Encrypt(keyBytes, keyBytes)
287 }
288
289 return
290 }
291
292 if len(access.Names) > 0 && access.Minimum > 0 {
293 // Generate a random AES key for each user and RSA/ECIES encrypt it
294 encrypted.KeySetRSA = make(map[string]SingleWrappedKey)
295
296 for _, name := range access.Names {
297 encrypted.KeySetRSA[name], err = generateRandomKey(name)
298 if err != nil {
299 return err
300 }
301
302 if access.Minimum == 1 {
303 keyBytes, err := encryptKey([]string{access.Names[0]}, clearKey)
304 if err != nil {
305 return err
306 }
307
308 encrypted.KeySet = append(encrypted.KeySet, MultiWrappedKey{
309 Name: []string{access.Names[0]},
310 Key: keyBytes,
311 })
312 }
313 }
314
315 if access.Minimum == 2 {
316 for i := 0; i < len(access.Names); i++ {
317 for j := i + 1; j < len(access.Names); j++ {
318 keyBytes, err := encryptKey([]string{access.Names[j], access.Names[i]}, clearKey)
319 if err != nil {
320 return err
321 }
322
323 out := MultiWrappedKey{
324 Name: []string{access.Names[i], access.Names[j]},
325 Key: keyBytes,
326 }
327
328 encrypted.KeySet = append(encrypted.KeySet, out)
329 }
330 }
331 } else if access.Minimum > 2 {
332 err = errors.New("Encryption to a list of owners with minimum > 2 is not implemented")
333 return err
334 }
335 } else if len(access.LeftNames) > 0 && len(access.RightNames) > 0 {
336 // Generate a random AES key for each user and RSA/ECIES encrypt it
337 encrypted.KeySetRSA = make(map[string]SingleWrappedKey)
338
339 for _, name := range access.LeftNames {
340 encrypted.KeySetRSA[name], err = generateRandomKey(name)
341 if err != nil {
342 return err
343 }
344 }
345
346 for _, name := range access.RightNames {
347 encrypted.KeySetRSA[name], err = generateRandomKey(name)
348 if err != nil {
349 return err
350 }
351 }
352
353 // encrypt file key with every combination of one left key and one right key
354 encrypted.KeySet = make([]MultiWrappedKey, 0)
355
356 for _, leftName := range access.LeftNames {
357 for _, rightName := range access.RightNames {
358 if leftName == rightName {
359 continue
360 }
361
362 keyBytes, err := encryptKey([]string{rightName, leftName}, clearKey)
363 if err != nil {
364 return err
365 }
366
367 out := MultiWrappedKey{
368 Name: []string{leftName, rightName},
369 Key: keyBytes,
370 }
371
372 encrypted.KeySet = append(encrypted.KeySet, out)
373 }
374 }
375 } else if len(access.Predicate) > 0 {
376 encrypted.KeySetRSA = make(map[string]SingleWrappedKey)
377
378 sss, err := msp.StringToMSP(access.Predicate)
379 if err != nil {
380 return err
381 }
382
383 db := UserDatabase{records: records}
384 shareSet, err := sss.DistributeShares(clearKey, &db)
385 if err != nil {
386 return err
387 }
388
389 for name, _ := range shareSet {
390 encrypted.KeySetRSA[name], err = generateRandomKey(name)
391 if err != nil {
392 return err
393 }
394 crypt, err := aes.NewCipher(encrypted.KeySetRSA[name].aesKey)
395 if err != nil {
396 return err
397 }
398
399 for i, _ := range shareSet[name] {
400 tmp := make([]byte, 16)
401 crypt.Encrypt(tmp, shareSet[name][i])
402 shareSet[name][i] = tmp
403 }
404 }
405
406 encrypted.ShareSet = shareSet
407 encrypted.Predicate = access.Predicate
408 } else {
409 return errors.New("Invalid access structure.")
410 }
411
412 return nil
413 }
414
415 // unwrapKey decrypts first key in keys whose encryption keys are in keycache
416 func (encrypted *EncryptedData) unwrapKey(cache *keycache.Cache, user string) (unwrappedKey []byte, names []string, err error) {
417 var (
418 decryptErr error
419 fullMatch bool = false
420 nameSet = map[string]bool{}
421 )
422
423 if len(encrypted.Predicate) == 0 {
424 for _, mwKey := range encrypted.KeySet {
425 // validate the size of the keys
426 if len(mwKey.Key) != 16 {
427 err = errors.New("Invalid Input")
428 }
429
430 if err != nil {
431 return nil, nil, err
432 }
433
434 // loop through users to see if they are all delegated
435 fullMatch = true
436 for _, mwName := range mwKey.Name {
437 if valid := cache.Valid(mwName, user, encrypted.Labels); !valid {
438 fullMatch = false
439 break
440 }
441 nameSet[mwName] = true
442 }
443
444 // if the keys are delegated, decrypt the mwKey with them
445 if fullMatch == true {
446 tmpKeyValue := mwKey.Key
447 for _, mwName := range mwKey.Name {
448 pubEncrypted := encrypted.KeySetRSA[mwName]
449 if tmpKeyValue, decryptErr = cache.DecryptKey(tmpKeyValue, mwName, user, encrypted.Labels, pubEncrypted.Key); decryptErr != nil {
450 break
451 }
452 }
453 unwrappedKey = tmpKeyValue
454 break
455 }
456 }
457
458 if !fullMatch {
459 err = ErrNotEnoughDelegations
460 return
461 }
462
463 if decryptErr != nil {
464 err = errors.New("Failed to decrypt with all keys in keyset")
465 return
466 }
467
468 names = make([]string, 0, len(nameSet))
469 for name := range nameSet {
470 names = append(names, name)
471 }
472 return
473 } else {
474 var sss msp.MSP
475 sss, err = msp.StringToMSP(encrypted.Predicate)
476 if err != nil {
477 return nil, nil, err
478 }
479
480 db := UserDatabase{
481 names: &names,
482 cache: cache,
483 user: user,
484 labels: encrypted.Labels,
485 keySet: encrypted.KeySetRSA,
486 shareSet: encrypted.ShareSet,
487 }
488 unwrappedKey, err = sss.RecoverSecret(&db)
489
490 return
491 }
492 }
493
494 // Encrypt encrypts data with the keys associated with names. This
495 // requires a minimum of min keys to decrypt. NOTE: as currently
496 // implemented, the maximum value for min is 2.
497 func (c *Cryptor) Encrypt(in []byte, labels []string, access AccessStructure) (resp []byte, err error) {
498 var encrypted EncryptedData
499 encrypted.Version = DEFAULT_VERSION
500 if encrypted.VaultId, err = c.records.GetVaultID(); err != nil {
501 return
502 }
503
504 // Generate random IV and encryption key
505 encrypted.IV, err = symcrypt.MakeRandom(16)
506 if err != nil {
507 return
508 }
509
510 clearKey, err := symcrypt.MakeRandom(16)
511 if err != nil {
512 return
513 }
514
515 err = encrypted.wrapKey(c.records, clearKey, access)
516 if err != nil {
517 return
518 }
519
520 // encrypt file with clear key
521 aesCrypt, err := aes.NewCipher(clearKey)
522 if err != nil {
523 return
524 }
525
526 clearFile := padding.AddPadding(in)
527
528 encryptedFile := make([]byte, len(clearFile))
529 aesCBC := cipher.NewCBCEncrypter(aesCrypt, encrypted.IV)
530 aesCBC.CryptBlocks(encryptedFile, clearFile)
531
532 encrypted.Data = encryptedFile
533 encrypted.Labels = labels
534
535 hmacKey, err := c.records.GetHMACKey()
536 if err != nil {
537 return
538 }
539 encrypted.Signature = encrypted.computeHmac(hmacKey)
540 encrypted.lock(hmacKey)
541
542 return json.Marshal(encrypted)
543 }
544
545 // Decrypt decrypts a file using the keys in the key cache.
546 func (c *Cryptor) Decrypt(in []byte, user string) (resp []byte, labels, names []string, secure bool, err error) {
547 return c.decrypt(c.cache, in, user)
548 }
549
550 func (c *Cryptor) decrypt(cache *keycache.Cache, in []byte, user string) (resp []byte, labels, names []string, secure bool, err error) {
551 // unwrap encrypted file
552 var encrypted EncryptedData
553 if err = json.Unmarshal(in, &encrypted); err != nil {
554 return
555 }
556 if encrypted.Version != DEFAULT_VERSION && encrypted.Version != -1 {
557 return nil, nil, nil, secure, errors.New("Unknown version")
558 }
559
560 secure = encrypted.Version == -1
561
562 hmacKey, err := c.records.GetHMACKey()
563 if err != nil {
564 return
565 }
566
567 if err = encrypted.unlock(hmacKey); err != nil {
568 return
569 }
570
571 // make sure file was encrypted with the active vault
572 vaultId, err := c.records.GetVaultID()
573 if err != nil {
574 return
575 }
576 if encrypted.VaultId != vaultId {
577 return nil, nil, nil, secure, errors.New("Wrong vault")
578 }
579
580 // compute HMAC
581 expectedMAC := encrypted.computeHmac(hmacKey)
582 if !hmac.Equal(encrypted.Signature, expectedMAC) {
583 err = errors.New("Signature mismatch")
584 return
585 }
586
587 // decrypt file key with delegate keys
588 var unwrappedKey = make([]byte, 16)
589 unwrappedKey, names, err = encrypted.unwrapKey(cache, user)
590 if err != nil {
591 return
592 }
593
594 aesCrypt, err := aes.NewCipher(unwrappedKey)
595 if err != nil {
596 return
597 }
598 clearData := make([]byte, len(encrypted.Data))
599 aesCBC := cipher.NewCBCDecrypter(aesCrypt, encrypted.IV)
600
601 // decrypt contents of file
602 aesCBC.CryptBlocks(clearData, encrypted.Data)
603
604 resp, err = padding.RemovePadding(clearData)
605 labels = encrypted.Labels
606 return
607 }
608
609 // GetOwners returns the list of users that can delegate their passwords
610 // to decrypt the given encrypted secret.
611 func (c *Cryptor) GetOwners(in []byte) (names []string, predicate string, err error) {
612 // unwrap encrypted file
613 var encrypted EncryptedData
614 if err = json.Unmarshal(in, &encrypted); err != nil {
615 return
616 }
617 if encrypted.Version != DEFAULT_VERSION && encrypted.Version != -1 {
618 err = errors.New("Unknown version")
619 return
620 }
621
622 hmacKey, err := c.records.GetHMACKey()
623 if err != nil {
624 return
625 }
626
627 if err = encrypted.unlock(hmacKey); err != nil {
628 return
629 }
630
631 // make sure file was encrypted with the active vault
632 vaultId, err := c.records.GetVaultID()
633 if err != nil {
634 return
635 }
636 if encrypted.VaultId != vaultId {
637 err = errors.New("Wrong vault")
638 return
639 }
640
641 // compute HMAC
642 expectedMAC := encrypted.computeHmac(hmacKey)
643 if !hmac.Equal(encrypted.Signature, expectedMAC) {
644 err = errors.New("Signature mismatch")
645 return
646 }
647
648 addedNames := make(map[string]bool)
649 for _, mwKey := range encrypted.KeySet { // names from the combinatorial method
650 for _, mwName := range mwKey.Name {
651 if !addedNames[mwName] {
652 names = append(names, mwName)
653 addedNames[mwName] = true
654 }
655 }
656 }
657
658 for name, _ := range encrypted.ShareSet { // names from the secret splitting method
659 if !addedNames[name] {
660 names = append(names, name)
661 addedNames[name] = true
662 }
663 }
664 predicate = encrypted.Predicate
665
666 return
667 }
668
669 // LiveSummary returns a list of the users currently delegated.
670 func (c *Cryptor) LiveSummary() map[string]keycache.ActiveUser {
671 return c.cache.GetSummary()
672 }
673
674 // Refresh purges all expired or fully-used delegations in the
675 // crypto's key cache. It returns an error if the delegations
676 // should have been stored, but couldn't be.
677 func (c *Cryptor) Refresh() error {
678 n := c.cache.Refresh()
679 if n != 0 {
680 return c.store()
681 }
682 return nil
683 }
684
685 // Flush removes all delegations.
686 func (c *Cryptor) Flush() error {
687 if c.cache.Flush() {
688 return c.store()
689 }
690 return nil
691 }
692
693 // Delegate attempts to decrypt a key for the specified user and add
694 // the key to the key cache.
695 func (c *Cryptor) Delegate(record passvault.PasswordRecord, name, password string, users, labels []string, uses int, slot, durationString string) (err error) {
696 err = c.cache.AddKeyFromRecord(record, name, password, users, labels, uses, slot, durationString)
697 if err != nil {
698 return err
699 }
700
701 return c.store()
702 }
703
704 // DelegateStatus will return a list of admins who have delegated to a particular user, for a particular label.
705 // This is useful information to have when determining the status of an order and conveying order progress.
706 func (c *Cryptor) DelegateStatus(name string, labels, admins []string) (adminsDelegated []string, hasDelegated int) {
707 return c.cache.DelegateStatus(name, labels, admins)
708 }
709
710 // store serialises the key cache, encrypts it, and writes it to disk.
711 func (c *Cryptor) store() error {
712 // If the store isn't currently active, we shouldn't attempt
713 // to persist the store.
714 st := c.persist.Status()
715 if st.State != persist.Active {
716 return nil
717 }
718
719 cache, err := json.Marshal(c.cache.GetSummary())
720 if err != nil {
721 return err
722 }
723
724 access := AccessStructure{
725 Names: c.persist.Users(),
726 Predicate: c.persist.Policy(),
727 }
728
729 cache, err = c.Encrypt(cache, persist.Labels, access)
730 if err != nil {
731 return err
732 }
733
734 return c.persist.Store(cache)
735 }
736
737 // ErrRestoreDelegations is a sentinal value returned when more
738 // delegations are needed for the restore to continue.
739 var ErrRestoreDelegations = errors.New("cryptor: need more delegations")
740
741 // ErrNotEnoughDelegations is a error returned by Decrypt.
742 var ErrNotEnoughDelegations = errors.New("need more delegated keys")
743
744 // Restore delegates the named user to the persistence key cache. If
745 // enough delegations are present to restore the cache, the current
746 // Red October key cache is replaced with the persisted one.
747 func (c *Cryptor) Restore(name, password string, uses int, slot, durationString string) error {
748 // If the persistence store is already active, don't proceed.
749 if st := c.persist.Status(); st != nil && st.State == persist.Active {
750 return nil
751 }
752
753 record, ok := c.records.GetRecord(name)
754 if !ok {
755 return errors.New("Missing user on disk")
756 }
757
758 err := c.persist.Delegate(record, name, password, c.persist.Users(), persist.Labels, uses, slot, durationString)
759 if err != nil {
760 return err
761 }
762
763 // A failure to decrypt isn't a restore error, it (most often)
764 // just means there aren't enough delegations yet; the
765 // sentinal value ErrRestoreDelegations is returned to
766 // indicate this. However, the error
767 cache, _, names, _, err := c.decrypt(c.persist.Cache(), c.persist.Blob(), name)
768 if err != nil {
769 if err == msp.ErrNotEnoughShares {
770 return ErrRestoreDelegations
771 }
772 return err
773 }
774
775 log.Printf("cryptor.restore success: names=%s", strings.Join(names, ","))
776
777 var uk map[string]keycache.ActiveUser
778 err = json.Unmarshal(cache, &uk)
779 if err != nil {
780 return err
781 }
782
783 rcache := keycache.NewFrom(uk)
784 err = rcache.Restore()
785 if err != nil {
786 return err
787 }
788
789 c.cache = rcache
790 c.persist.Persist()
791 c.persist.Cache().Flush()
792 return nil
793 }
794
795 // Status returns the status of the underlying persistence store.
796 func (c *Cryptor) Status() *persist.Status {
797 return c.persist.Status()
798 }
799
800 // ResetPersisted clears any persisted delegations and returns the
801 // vault to an active delegation state if configured.
802 func (c *Cryptor) ResetPersisted() (*persist.Status, error) {
803 err := c.persist.Purge()
804 return c.persist.Status(), err
805 }