authority.go 7.6 KB

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