trustkey.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package daemon
  2. import (
  3. "encoding/json"
  4. "encoding/pem"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "github.com/docker/docker/pkg/ioutils"
  9. "github.com/docker/docker/pkg/system"
  10. "github.com/docker/libtrust"
  11. )
  12. // LoadOrCreateTrustKey attempts to load the libtrust key at the given path,
  13. // otherwise generates a new one
  14. // TODO: this should use more of libtrust.LoadOrCreateTrustKey which may need
  15. // a refactor or this function to be moved into libtrust
  16. func loadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {
  17. err := system.MkdirAll(filepath.Dir(trustKeyPath), 0700, "")
  18. if err != nil {
  19. return nil, err
  20. }
  21. trustKey, err := libtrust.LoadKeyFile(trustKeyPath)
  22. if err == libtrust.ErrKeyFileDoesNotExist {
  23. trustKey, err = libtrust.GenerateECP256PrivateKey()
  24. if err != nil {
  25. return nil, fmt.Errorf("Error generating key: %s", err)
  26. }
  27. encodedKey, err := serializePrivateKey(trustKey, filepath.Ext(trustKeyPath))
  28. if err != nil {
  29. return nil, fmt.Errorf("Error serializing key: %s", err)
  30. }
  31. if err := ioutils.AtomicWriteFile(trustKeyPath, encodedKey, os.FileMode(0600)); err != nil {
  32. return nil, fmt.Errorf("Error saving key file: %s", err)
  33. }
  34. } else if err != nil {
  35. return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err)
  36. }
  37. return trustKey, nil
  38. }
  39. func serializePrivateKey(key libtrust.PrivateKey, ext string) (encoded []byte, err error) {
  40. if ext == ".json" || ext == ".jwk" {
  41. encoded, err = json.Marshal(key)
  42. if err != nil {
  43. return nil, fmt.Errorf("unable to encode private key JWK: %s", err)
  44. }
  45. } else {
  46. pemBlock, err := key.PEMBlock()
  47. if err != nil {
  48. return nil, fmt.Errorf("unable to encode private key PEM: %s", err)
  49. }
  50. encoded = pem.EncodeToMemory(pemBlock)
  51. }
  52. return
  53. }