authority.go 7.7 KB

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