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