authority.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "log"
  9. "sync"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. "github.com/smallstep/certificates/db"
  14. "github.com/smallstep/certificates/kms"
  15. kmsapi "github.com/smallstep/certificates/kms/apiv1"
  16. "github.com/smallstep/certificates/sshutil"
  17. "github.com/smallstep/certificates/templates"
  18. "github.com/smallstep/cli/crypto/pemutil"
  19. "golang.org/x/crypto/ssh"
  20. )
  21. const (
  22. legacyAuthority = "step-certificate-authority"
  23. )
  24. // Authority implements the Certificate Authority internal interface.
  25. type Authority struct {
  26. config *Config
  27. keyManager kms.KeyManager
  28. provisioners *provisioner.Collection
  29. db db.AuthDB
  30. templates *templates.Templates
  31. // X509 CA
  32. rootX509Certs []*x509.Certificate
  33. federatedX509Certs []*x509.Certificate
  34. x509Signer crypto.Signer
  35. x509Issuer *x509.Certificate
  36. certificates *sync.Map
  37. // SSH CA
  38. sshCAUserCertSignKey ssh.Signer
  39. sshCAHostCertSignKey ssh.Signer
  40. sshCAUserCerts []ssh.PublicKey
  41. sshCAHostCerts []ssh.PublicKey
  42. sshCAUserFederatedCerts []ssh.PublicKey
  43. sshCAHostFederatedCerts []ssh.PublicKey
  44. // Do not re-initialize
  45. initOnce bool
  46. startTime time.Time
  47. // Custom functions
  48. sshBastionFunc func(ctx context.Context, user, hostname string) (*Bastion, error)
  49. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  50. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]sshutil.Host, error)
  51. getIdentityFunc provisioner.GetIdentityFunc
  52. }
  53. // New creates and initiates a new Authority type.
  54. func New(config *Config, opts ...Option) (*Authority, error) {
  55. err := config.Validate()
  56. if err != nil {
  57. return nil, err
  58. }
  59. var a = &Authority{
  60. config: config,
  61. certificates: new(sync.Map),
  62. }
  63. // Apply options.
  64. for _, fn := range opts {
  65. if err := fn(a); err != nil {
  66. return nil, err
  67. }
  68. }
  69. // Initialize authority from options or configuration.
  70. if err := a.init(); err != nil {
  71. return nil, err
  72. }
  73. return a, nil
  74. }
  75. // NewEmbedded initializes an authority that can be embedded in a different
  76. // project without the limitations of the config.
  77. func NewEmbedded(opts ...Option) (*Authority, error) {
  78. a := &Authority{
  79. config: &Config{},
  80. certificates: new(sync.Map),
  81. }
  82. // Apply options.
  83. for _, fn := range opts {
  84. if err := fn(a); err != nil {
  85. return nil, err
  86. }
  87. }
  88. // Validate required options
  89. switch {
  90. case a.config == nil:
  91. return nil, errors.New("cannot create an authority without a configuration")
  92. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  93. return nil, errors.New("cannot create an authority without a root certificate")
  94. case a.x509Issuer == nil && a.config.IntermediateCert == "":
  95. return nil, errors.New("cannot create an authority without an issuer certificate")
  96. case a.x509Signer == nil && a.config.IntermediateKey == "":
  97. return nil, errors.New("cannot create an authority without an issuer signer")
  98. }
  99. // Initialize config required fields.
  100. a.config.init()
  101. // Initialize authority from options or configuration.
  102. if err := a.init(); err != nil {
  103. return nil, err
  104. }
  105. return a, nil
  106. }
  107. // init performs validation and initializes the fields of an Authority struct.
  108. func (a *Authority) init() error {
  109. // Check if handler has already been validated/initialized.
  110. if a.initOnce {
  111. return nil
  112. }
  113. var err error
  114. // Initialize key manager if it has not been set in the options.
  115. if a.keyManager == nil {
  116. var options kmsapi.Options
  117. if a.config.KMS != nil {
  118. options = *a.config.KMS
  119. }
  120. a.keyManager, err = kms.New(context.Background(), options)
  121. if err != nil {
  122. return err
  123. }
  124. }
  125. // Initialize step-ca Database if it's not already initialized with WithDB.
  126. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  127. if a.db == nil {
  128. if a.db, err = db.New(a.config.DB); err != nil {
  129. return err
  130. }
  131. }
  132. // Read root certificates and store them in the certificates map.
  133. if len(a.rootX509Certs) == 0 {
  134. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  135. for i, path := range a.config.Root {
  136. crt, err := pemutil.ReadCertificate(path)
  137. if err != nil {
  138. return err
  139. }
  140. a.rootX509Certs[i] = crt
  141. }
  142. }
  143. for _, crt := range a.rootX509Certs {
  144. sum := sha256.Sum256(crt.Raw)
  145. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  146. }
  147. // Read federated certificates and store them in the certificates map.
  148. if len(a.federatedX509Certs) == 0 {
  149. a.federatedX509Certs = make([]*x509.Certificate, len(a.config.FederatedRoots))
  150. for i, path := range a.config.FederatedRoots {
  151. crt, err := pemutil.ReadCertificate(path)
  152. if err != nil {
  153. return err
  154. }
  155. a.federatedX509Certs[i] = crt
  156. }
  157. }
  158. for _, crt := range a.federatedX509Certs {
  159. sum := sha256.Sum256(crt.Raw)
  160. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  161. }
  162. // Read intermediate and create X509 signer.
  163. if a.x509Signer == nil {
  164. crt, err := pemutil.ReadCertificate(a.config.IntermediateCert)
  165. if err != nil {
  166. return err
  167. }
  168. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  169. SigningKey: a.config.IntermediateKey,
  170. Password: []byte(a.config.Password),
  171. })
  172. if err != nil {
  173. return err
  174. }
  175. a.x509Signer = signer
  176. a.x509Issuer = crt
  177. }
  178. // Decrypt and load SSH keys
  179. var tmplVars templates.Step
  180. if a.config.SSH != nil {
  181. if a.config.SSH.HostKey != "" {
  182. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  183. SigningKey: a.config.SSH.HostKey,
  184. Password: []byte(a.config.Password),
  185. })
  186. if err != nil {
  187. return err
  188. }
  189. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(signer)
  190. if err != nil {
  191. return errors.Wrap(err, "error creating ssh signer")
  192. }
  193. // Append public key to list of host certs
  194. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  195. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  196. }
  197. if a.config.SSH.UserKey != "" {
  198. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  199. SigningKey: a.config.SSH.UserKey,
  200. Password: []byte(a.config.Password),
  201. })
  202. if err != nil {
  203. return err
  204. }
  205. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(signer)
  206. if err != nil {
  207. return errors.Wrap(err, "error creating ssh signer")
  208. }
  209. // Append public key to list of user certs
  210. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  211. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  212. }
  213. // Append other public keys
  214. for _, key := range a.config.SSH.Keys {
  215. switch key.Type {
  216. case provisioner.SSHHostCert:
  217. if key.Federated {
  218. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, key.PublicKey())
  219. } else {
  220. a.sshCAHostCerts = append(a.sshCAHostCerts, key.PublicKey())
  221. }
  222. case provisioner.SSHUserCert:
  223. if key.Federated {
  224. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, key.PublicKey())
  225. } else {
  226. a.sshCAUserCerts = append(a.sshCAUserCerts, key.PublicKey())
  227. }
  228. default:
  229. return errors.Errorf("unsupported type %s", key.Type)
  230. }
  231. }
  232. // Configure template variables.
  233. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  234. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  235. // On the templates we skip the first one because there's a distinction
  236. // between the main key and federated keys.
  237. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  238. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  239. }
  240. // Merge global and configuration claims
  241. claimer, err := provisioner.NewClaimer(a.config.AuthorityConfig.Claims, globalProvisionerClaims)
  242. if err != nil {
  243. return err
  244. }
  245. // TODO: should we also be combining the ssh federated roots here?
  246. // If we rotate ssh roots keys, sshpop provisioner will lose ability to
  247. // validate old SSH certificates, unless they are added as federated certs.
  248. sshKeys, err := a.GetSSHRoots(context.Background())
  249. if err != nil {
  250. return err
  251. }
  252. // Initialize provisioners
  253. audiences := a.config.getAudiences()
  254. a.provisioners = provisioner.NewCollection(audiences)
  255. config := provisioner.Config{
  256. Claims: claimer.Claims(),
  257. Audiences: audiences,
  258. DB: a.db,
  259. SSHKeys: &provisioner.SSHKeys{
  260. UserKeys: sshKeys.UserKeys,
  261. HostKeys: sshKeys.HostKeys,
  262. },
  263. GetIdentityFunc: a.getIdentityFunc,
  264. }
  265. // Store all the provisioners
  266. for _, p := range a.config.AuthorityConfig.Provisioners {
  267. if err := p.Init(config); err != nil {
  268. return err
  269. }
  270. if err := a.provisioners.Store(p); err != nil {
  271. return err
  272. }
  273. }
  274. // Configure templates, currently only ssh templates are supported.
  275. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  276. a.templates = a.config.Templates
  277. if a.templates == nil {
  278. a.templates = templates.DefaultTemplates()
  279. }
  280. if a.templates.Data == nil {
  281. a.templates.Data = make(map[string]interface{})
  282. }
  283. a.templates.Data["Step"] = tmplVars
  284. }
  285. // JWT numeric dates are seconds.
  286. a.startTime = time.Now().Truncate(time.Second)
  287. // Set flag indicating that initialization has been completed, and should
  288. // not be repeated.
  289. a.initOnce = true
  290. return nil
  291. }
  292. // GetDatabase returns the authority database. If the configuration does not
  293. // define a database, GetDatabase will return a db.SimpleDB instance.
  294. func (a *Authority) GetDatabase() db.AuthDB {
  295. return a.db
  296. }
  297. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  298. func (a *Authority) Shutdown() error {
  299. if err := a.keyManager.Close(); err != nil {
  300. log.Printf("error closing the key manager: %v", err)
  301. }
  302. return a.db.Shutdown()
  303. }