authority.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package authority
  2. import (
  3. "crypto"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "sync"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority/provisioner"
  11. "github.com/smallstep/certificates/ct"
  12. "github.com/smallstep/certificates/db"
  13. "github.com/smallstep/cli/crypto/pemutil"
  14. "github.com/smallstep/cli/crypto/x509util"
  15. )
  16. const (
  17. legacyAuthority = "step-certificate-authority"
  18. )
  19. // Authority implements the Certificate Authority internal interface.
  20. type Authority struct {
  21. config *Config
  22. rootX509Certs []*x509.Certificate
  23. intermediateIdentity *x509util.Identity
  24. sshCAUserCertSignKey crypto.Signer
  25. sshCAHostCertSignKey crypto.Signer
  26. certificates *sync.Map
  27. startTime time.Time
  28. provisioners *provisioner.Collection
  29. db db.AuthDB
  30. ctClient ct.Client
  31. // Do not re-initialize
  32. initOnce bool
  33. }
  34. // Option sets options to the Authority.
  35. type Option func(*Authority)
  36. // WithDatabase sets an already initialized authority database to a new
  37. // authority. This option is intended to be use on graceful reloads.
  38. func WithDatabase(db db.AuthDB) Option {
  39. return func(a *Authority) {
  40. a.db = db
  41. }
  42. }
  43. // New creates and initiates a new Authority type.
  44. func New(config *Config, opts ...Option) (*Authority, error) {
  45. err := config.Validate()
  46. if err != nil {
  47. return nil, err
  48. }
  49. var ctClient ct.Client
  50. // only first one is supported at the moment.
  51. if len(config.CTs) > 0 {
  52. if ctClient, err = ct.New(config.CTs[0]); err != nil {
  53. return nil, err
  54. }
  55. }
  56. var a = &Authority{
  57. config: config,
  58. certificates: new(sync.Map),
  59. provisioners: provisioner.NewCollection(config.getAudiences()),
  60. ctClient: ctClient,
  61. }
  62. for _, opt := range opts {
  63. opt(a)
  64. }
  65. if err := a.init(); err != nil {
  66. return nil, err
  67. }
  68. return a, nil
  69. }
  70. // init performs validation and initializes the fields of an Authority struct.
  71. func (a *Authority) init() error {
  72. // Check if handler has already been validated/initialized.
  73. if a.initOnce {
  74. return nil
  75. }
  76. var err error
  77. // Initialize step-ca Database if it's not already initialized with WithDB.
  78. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  79. if a.db == nil {
  80. if a.db, err = db.New(a.config.DB); err != nil {
  81. return err
  82. }
  83. }
  84. // Load the root certificates and add them to the certificate store
  85. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  86. for i, path := range a.config.Root {
  87. crt, err := pemutil.ReadCertificate(path)
  88. if err != nil {
  89. return err
  90. }
  91. // Add root certificate to the certificate map
  92. sum := sha256.Sum256(crt.Raw)
  93. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  94. a.rootX509Certs[i] = crt
  95. }
  96. // Add federated roots
  97. for _, path := range a.config.FederatedRoots {
  98. crt, err := pemutil.ReadCertificate(path)
  99. if err != nil {
  100. return err
  101. }
  102. sum := sha256.Sum256(crt.Raw)
  103. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  104. }
  105. // Decrypt and load intermediate public / private key pair.
  106. if len(a.config.Password) > 0 {
  107. a.intermediateIdentity, err = x509util.LoadIdentityFromDisk(
  108. a.config.IntermediateCert,
  109. a.config.IntermediateKey,
  110. pemutil.WithPassword([]byte(a.config.Password)),
  111. )
  112. if err != nil {
  113. return err
  114. }
  115. } else {
  116. a.intermediateIdentity, err = x509util.LoadIdentityFromDisk(a.config.IntermediateCert, a.config.IntermediateKey)
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. // Decrypt and load SSH keys
  122. if a.config.SSH != nil {
  123. if a.config.SSH.HostKey != "" {
  124. a.sshCAHostCertSignKey, err = parseCryptoSigner(a.config.SSH.HostKey, a.config.Password)
  125. if err != nil {
  126. return err
  127. }
  128. }
  129. if a.config.SSH.UserKey != "" {
  130. a.sshCAUserCertSignKey, err = parseCryptoSigner(a.config.SSH.UserKey, a.config.Password)
  131. if err != nil {
  132. return err
  133. }
  134. }
  135. }
  136. // Store all the provisioners
  137. for _, p := range a.config.AuthorityConfig.Provisioners {
  138. if err := a.provisioners.Store(p); err != nil {
  139. return err
  140. }
  141. }
  142. // JWT numeric dates are seconds.
  143. a.startTime = time.Now().Truncate(time.Second)
  144. // Set flag indicating that initialization has been completed, and should
  145. // not be repeated.
  146. a.initOnce = true
  147. return nil
  148. }
  149. // GetDatabase returns the authority database. If the configuration does not
  150. // define a database, GetDatabase will return a db.SimpleDB instance.
  151. func (a *Authority) GetDatabase() db.AuthDB {
  152. return a.db
  153. }
  154. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  155. func (a *Authority) Shutdown() error {
  156. return a.db.Shutdown()
  157. }
  158. func parseCryptoSigner(filename, password string) (crypto.Signer, error) {
  159. var opts []pemutil.Options
  160. if password != "" {
  161. opts = append(opts, pemutil.WithPassword([]byte(password)))
  162. }
  163. key, err := pemutil.Read(filename, opts...)
  164. if err != nil {
  165. return nil, err
  166. }
  167. signer, ok := key.(crypto.Signer)
  168. if !ok {
  169. return nil, errors.Errorf("key %s of type %T cannot be used for signing operations", filename, key)
  170. }
  171. return signer, nil
  172. }