authority.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package authority
  2. import (
  3. "crypto"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "sync"
  8. "time"
  9. "github.com/smallstep/certificates/templates"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/authority/provisioner"
  12. "github.com/smallstep/certificates/db"
  13. "github.com/smallstep/cli/crypto/pemutil"
  14. "github.com/smallstep/cli/crypto/x509util"
  15. "golang.org/x/crypto/ssh"
  16. )
  17. const (
  18. legacyAuthority = "step-certificate-authority"
  19. )
  20. // Authority implements the Certificate Authority internal interface.
  21. type Authority struct {
  22. config *Config
  23. rootX509Certs []*x509.Certificate
  24. intermediateIdentity *x509util.Identity
  25. sshCAUserCertSignKey ssh.Signer
  26. sshCAHostCertSignKey ssh.Signer
  27. sshCAUserCerts []ssh.PublicKey
  28. sshCAHostCerts []ssh.PublicKey
  29. sshCAUserFederatedCerts []ssh.PublicKey
  30. sshCAHostFederatedCerts []ssh.PublicKey
  31. certificates *sync.Map
  32. startTime time.Time
  33. provisioners *provisioner.Collection
  34. db db.AuthDB
  35. // Do not re-initialize
  36. initOnce bool
  37. }
  38. // Option sets options to the Authority.
  39. type Option func(*Authority)
  40. // WithDatabase sets an already initialized authority database to a new
  41. // authority. This option is intended to be use on graceful reloads.
  42. func WithDatabase(db db.AuthDB) Option {
  43. return func(a *Authority) {
  44. a.db = db
  45. }
  46. }
  47. // New creates and initiates a new Authority type.
  48. func New(config *Config, opts ...Option) (*Authority, error) {
  49. err := config.Validate()
  50. if err != nil {
  51. return nil, err
  52. }
  53. var a = &Authority{
  54. config: config,
  55. certificates: new(sync.Map),
  56. provisioners: provisioner.NewCollection(config.getAudiences()),
  57. }
  58. for _, opt := range opts {
  59. opt(a)
  60. }
  61. if err := a.init(); err != nil {
  62. return nil, err
  63. }
  64. return a, nil
  65. }
  66. // init performs validation and initializes the fields of an Authority struct.
  67. func (a *Authority) init() error {
  68. // Check if handler has already been validated/initialized.
  69. if a.initOnce {
  70. return nil
  71. }
  72. var err error
  73. // Initialize step-ca Database if it's not already initialized with WithDB.
  74. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  75. if a.db == nil {
  76. if a.db, err = db.New(a.config.DB); err != nil {
  77. return err
  78. }
  79. }
  80. // Load the root certificates and add them to the certificate store
  81. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  82. for i, path := range a.config.Root {
  83. crt, err := pemutil.ReadCertificate(path)
  84. if err != nil {
  85. return err
  86. }
  87. // Add root certificate to the certificate map
  88. sum := sha256.Sum256(crt.Raw)
  89. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  90. a.rootX509Certs[i] = crt
  91. }
  92. // Add federated roots
  93. for _, path := range a.config.FederatedRoots {
  94. crt, err := pemutil.ReadCertificate(path)
  95. if err != nil {
  96. return err
  97. }
  98. sum := sha256.Sum256(crt.Raw)
  99. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  100. }
  101. // Decrypt and load intermediate public / private key pair.
  102. if len(a.config.Password) > 0 {
  103. a.intermediateIdentity, err = x509util.LoadIdentityFromDisk(
  104. a.config.IntermediateCert,
  105. a.config.IntermediateKey,
  106. pemutil.WithPassword([]byte(a.config.Password)),
  107. )
  108. if err != nil {
  109. return err
  110. }
  111. } else {
  112. a.intermediateIdentity, err = x509util.LoadIdentityFromDisk(a.config.IntermediateCert, a.config.IntermediateKey)
  113. if err != nil {
  114. return err
  115. }
  116. }
  117. // Decrypt and load SSH keys
  118. if a.config.SSH != nil {
  119. if a.config.SSH.HostKey != "" {
  120. signer, err := parseCryptoSigner(a.config.SSH.HostKey, a.config.Password)
  121. if err != nil {
  122. return err
  123. }
  124. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(signer)
  125. if err != nil {
  126. return errors.Wrap(err, "error creating ssh signer")
  127. }
  128. // Append public key to list of host certs
  129. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  130. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  131. }
  132. if a.config.SSH.UserKey != "" {
  133. signer, err := parseCryptoSigner(a.config.SSH.UserKey, a.config.Password)
  134. if err != nil {
  135. return err
  136. }
  137. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(signer)
  138. if err != nil {
  139. return errors.Wrap(err, "error creating ssh signer")
  140. }
  141. // Append public key to list of user certs
  142. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  143. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  144. }
  145. // Append other public keys
  146. for _, key := range a.config.SSH.Keys {
  147. switch key.Type {
  148. case provisioner.SSHHostCert:
  149. if key.Federated {
  150. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, key.PublicKey())
  151. } else {
  152. a.sshCAHostCerts = append(a.sshCAHostCerts, key.PublicKey())
  153. }
  154. case provisioner.SSHUserCert:
  155. if key.Federated {
  156. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, key.PublicKey())
  157. } else {
  158. a.sshCAUserCerts = append(a.sshCAUserCerts, key.PublicKey())
  159. }
  160. default:
  161. return errors.Errorf("unsupported type %s", key.Type)
  162. }
  163. }
  164. }
  165. // Merge global and configuration claims
  166. claimer, err := provisioner.NewClaimer(a.config.AuthorityConfig.Claims, globalProvisionerClaims)
  167. if err != nil {
  168. return err
  169. }
  170. // TODO: should we also be combining the ssh federated roots here?
  171. // If we rotate ssh roots keys, sshpop provisioner will lose ability to
  172. // validate old SSH certificates, unless they are added as federated certs.
  173. sshKeys, err := a.GetSSHRoots()
  174. if err != nil {
  175. return err
  176. }
  177. // Initialize provisioners
  178. config := provisioner.Config{
  179. Claims: claimer.Claims(),
  180. Audiences: a.config.getAudiences(),
  181. DB: a.db,
  182. SSHKeys: &provisioner.SSHKeys{
  183. UserKeys: sshKeys.UserKeys,
  184. HostKeys: sshKeys.HostKeys,
  185. },
  186. }
  187. // Store all the provisioners
  188. for _, p := range a.config.AuthorityConfig.Provisioners {
  189. if err := p.Init(config); err != nil {
  190. return err
  191. }
  192. if err := a.provisioners.Store(p); err != nil {
  193. return err
  194. }
  195. }
  196. // Configure protected template variables:
  197. if t := a.config.Templates; t != nil {
  198. if t.Data == nil {
  199. t.Data = make(map[string]interface{})
  200. }
  201. var vars templates.Step
  202. if a.config.SSH != nil {
  203. if a.sshCAHostCertSignKey != nil {
  204. vars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  205. vars.SSH.HostFederatedKeys = append(vars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  206. }
  207. if a.sshCAUserCertSignKey != nil {
  208. vars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  209. vars.SSH.UserFederatedKeys = append(vars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  210. }
  211. }
  212. t.Data["Step"] = vars
  213. }
  214. // JWT numeric dates are seconds.
  215. a.startTime = time.Now().Truncate(time.Second)
  216. // Set flag indicating that initialization has been completed, and should
  217. // not be repeated.
  218. a.initOnce = true
  219. return nil
  220. }
  221. // GetDatabase returns the authority database. If the configuration does not
  222. // define a database, GetDatabase will return a db.SimpleDB instance.
  223. func (a *Authority) GetDatabase() db.AuthDB {
  224. return a.db
  225. }
  226. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  227. func (a *Authority) Shutdown() error {
  228. return a.db.Shutdown()
  229. }
  230. func parseCryptoSigner(filename, password string) (crypto.Signer, error) {
  231. var opts []pemutil.Options
  232. if password != "" {
  233. opts = append(opts, pemutil.WithPassword([]byte(password)))
  234. }
  235. key, err := pemutil.Read(filename, opts...)
  236. if err != nil {
  237. return nil, err
  238. }
  239. signer, ok := key.(crypto.Signer)
  240. if !ok {
  241. return nil, errors.Errorf("key %s of type %T cannot be used for signing operations", filename, key)
  242. }
  243. return signer, nil
  244. }