authority.go 7.4 KB

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