authority.go 12 KB

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