tls.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package authority
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "crypto/x509/pkix"
  6. "encoding/asn1"
  7. "encoding/pem"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. "github.com/smallstep/cli/crypto/pemutil"
  14. "github.com/smallstep/cli/crypto/tlsutil"
  15. "github.com/smallstep/cli/crypto/x509util"
  16. stepx509 "github.com/smallstep/cli/pkg/x509"
  17. )
  18. // GetTLSOptions returns the tls options configured.
  19. func (a *Authority) GetTLSOptions() *tlsutil.TLSOptions {
  20. return a.config.TLS
  21. }
  22. var (
  23. stepOIDRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
  24. stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
  25. oidAuthorityKeyIdentifier = asn1.ObjectIdentifier{2, 5, 29, 35}
  26. )
  27. type stepProvisionerASN1 struct {
  28. Type int
  29. Name []byte
  30. CredentialID []byte
  31. }
  32. const provisionerTypeJWK = 1
  33. func withProvisionerOID(name, kid string) x509util.WithOption {
  34. return func(p x509util.Profile) error {
  35. crt := p.Subject()
  36. b, err := asn1.Marshal(stepProvisionerASN1{
  37. Type: provisionerTypeJWK,
  38. Name: []byte(name),
  39. CredentialID: []byte(kid),
  40. })
  41. if err != nil {
  42. return err
  43. }
  44. crt.ExtraExtensions = append(crt.ExtraExtensions, pkix.Extension{
  45. Id: stepOIDProvisioner,
  46. Critical: false,
  47. Value: b,
  48. })
  49. return nil
  50. }
  51. }
  52. func withDefaultASN1DN(def *x509util.ASN1DN) x509util.WithOption {
  53. return func(p x509util.Profile) error {
  54. if def == nil {
  55. return errors.New("default ASN1DN template cannot be nil")
  56. }
  57. crt := p.Subject()
  58. if len(crt.Subject.Country) == 0 && def.Country != "" {
  59. crt.Subject.Country = append(crt.Subject.Country, def.Country)
  60. }
  61. if len(crt.Subject.Organization) == 0 && def.Organization != "" {
  62. crt.Subject.Organization = append(crt.Subject.Organization, def.Organization)
  63. }
  64. if len(crt.Subject.OrganizationalUnit) == 0 && def.OrganizationalUnit != "" {
  65. crt.Subject.OrganizationalUnit = append(crt.Subject.OrganizationalUnit, def.OrganizationalUnit)
  66. }
  67. if len(crt.Subject.Locality) == 0 && def.Locality != "" {
  68. crt.Subject.Locality = append(crt.Subject.Locality, def.Locality)
  69. }
  70. if len(crt.Subject.Province) == 0 && def.Province != "" {
  71. crt.Subject.Province = append(crt.Subject.Province, def.Province)
  72. }
  73. if len(crt.Subject.StreetAddress) == 0 && def.StreetAddress != "" {
  74. crt.Subject.StreetAddress = append(crt.Subject.StreetAddress, def.StreetAddress)
  75. }
  76. return nil
  77. }
  78. }
  79. // Sign creates a signed certificate from a certificate signing request.
  80. func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.Options, extraOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error) {
  81. var (
  82. errContext = context{"csr": csr, "signOptions": signOpts}
  83. mods = []x509util.WithOption{withDefaultASN1DN(a.config.AuthorityConfig.Template)}
  84. certValidators = []provisioner.CertificateValidator{}
  85. )
  86. for _, op := range extraOpts {
  87. switch k := op.(type) {
  88. case provisioner.CertificateValidator:
  89. certValidators = append(certValidators, k)
  90. case provisioner.CertificateRequestValidator:
  91. if err := k.Valid(csr); err != nil {
  92. return nil, nil, &apiError{err, http.StatusUnauthorized, errContext}
  93. }
  94. case provisioner.ProfileModifier:
  95. mods = append(mods, k.Option(signOpts))
  96. default:
  97. return nil, nil, &apiError{errors.Errorf("sign: invalid extra option type %T", k),
  98. http.StatusInternalServerError, errContext}
  99. }
  100. }
  101. stepCSR, err := stepx509.ParseCertificateRequest(csr.Raw)
  102. if err != nil {
  103. return nil, nil, &apiError{errors.Wrap(err, "sign: error converting x509 csr to stepx509 csr"),
  104. http.StatusInternalServerError, errContext}
  105. }
  106. issIdentity := a.intermediateIdentity
  107. leaf, err := x509util.NewLeafProfileWithCSR(stepCSR, issIdentity.Crt,
  108. issIdentity.Key, mods...)
  109. if err != nil {
  110. return nil, nil, &apiError{errors.Wrapf(err, "sign"), http.StatusInternalServerError, errContext}
  111. }
  112. crtBytes, err := leaf.CreateCertificate()
  113. if err != nil {
  114. return nil, nil, &apiError{errors.Wrap(err, "sign: error creating new leaf certificate"),
  115. http.StatusInternalServerError, errContext}
  116. }
  117. serverCert, err := x509.ParseCertificate(crtBytes)
  118. if err != nil {
  119. return nil, nil, &apiError{errors.Wrap(err, "sign: error parsing new leaf certificate"),
  120. http.StatusInternalServerError, errContext}
  121. }
  122. // FIXME: This should be before creating the certificate.
  123. for _, v := range certValidators {
  124. if err := v.Valid(serverCert); err != nil {
  125. return nil, nil, &apiError{err, http.StatusUnauthorized, errContext}
  126. }
  127. }
  128. caCert, err := x509.ParseCertificate(issIdentity.Crt.Raw)
  129. if err != nil {
  130. return nil, nil, &apiError{errors.Wrap(err, "sign: error parsing intermediate certificate"),
  131. http.StatusInternalServerError, errContext}
  132. }
  133. return serverCert, caCert, nil
  134. }
  135. // Renew creates a new Certificate identical to the old certificate, except
  136. // with a validity window that begins 'now'.
  137. func (a *Authority) Renew(ocx *x509.Certificate) (*x509.Certificate, *x509.Certificate, error) {
  138. // Check step provisioner extensions
  139. if err := a.authorizeRenewal(ocx); err != nil {
  140. return nil, nil, err
  141. }
  142. // Issuer
  143. issIdentity := a.intermediateIdentity
  144. // Convert a realx509.Certificate to the step x509 Certificate.
  145. oldCert, err := stepx509.ParseCertificate(ocx.Raw)
  146. if err != nil {
  147. return nil, nil, &apiError{
  148. errors.Wrap(err, "error converting x509.Certificate to stepx509.Certificate"),
  149. http.StatusInternalServerError, context{},
  150. }
  151. }
  152. now := time.Now().UTC()
  153. duration := oldCert.NotAfter.Sub(oldCert.NotBefore)
  154. newCert := &stepx509.Certificate{
  155. PublicKey: oldCert.PublicKey,
  156. Issuer: issIdentity.Crt.Subject,
  157. Subject: oldCert.Subject,
  158. NotBefore: now,
  159. NotAfter: now.Add(duration),
  160. KeyUsage: oldCert.KeyUsage,
  161. UnhandledCriticalExtensions: oldCert.UnhandledCriticalExtensions,
  162. ExtKeyUsage: oldCert.ExtKeyUsage,
  163. UnknownExtKeyUsage: oldCert.UnknownExtKeyUsage,
  164. BasicConstraintsValid: oldCert.BasicConstraintsValid,
  165. IsCA: oldCert.IsCA,
  166. MaxPathLen: oldCert.MaxPathLen,
  167. MaxPathLenZero: oldCert.MaxPathLenZero,
  168. OCSPServer: oldCert.OCSPServer,
  169. IssuingCertificateURL: oldCert.IssuingCertificateURL,
  170. DNSNames: oldCert.DNSNames,
  171. EmailAddresses: oldCert.EmailAddresses,
  172. IPAddresses: oldCert.IPAddresses,
  173. URIs: oldCert.URIs,
  174. PermittedDNSDomainsCritical: oldCert.PermittedDNSDomainsCritical,
  175. PermittedDNSDomains: oldCert.PermittedDNSDomains,
  176. ExcludedDNSDomains: oldCert.ExcludedDNSDomains,
  177. PermittedIPRanges: oldCert.PermittedIPRanges,
  178. ExcludedIPRanges: oldCert.ExcludedIPRanges,
  179. PermittedEmailAddresses: oldCert.PermittedEmailAddresses,
  180. ExcludedEmailAddresses: oldCert.ExcludedEmailAddresses,
  181. PermittedURIDomains: oldCert.PermittedURIDomains,
  182. ExcludedURIDomains: oldCert.ExcludedURIDomains,
  183. CRLDistributionPoints: oldCert.CRLDistributionPoints,
  184. PolicyIdentifiers: oldCert.PolicyIdentifiers,
  185. }
  186. // Copy all extensions except for Authority Key Identifier. This one might
  187. // be different if we rotate the intermediate certificate and it will cause
  188. // a TLS bad certificate error.
  189. for _, ext := range oldCert.Extensions {
  190. if !ext.Id.Equal(oidAuthorityKeyIdentifier) {
  191. newCert.ExtraExtensions = append(newCert.ExtraExtensions, ext)
  192. }
  193. }
  194. leaf, err := x509util.NewLeafProfileWithTemplate(newCert,
  195. issIdentity.Crt, issIdentity.Key)
  196. if err != nil {
  197. return nil, nil, &apiError{err, http.StatusInternalServerError, context{}}
  198. }
  199. crtBytes, err := leaf.CreateCertificate()
  200. if err != nil {
  201. return nil, nil, &apiError{errors.Wrap(err, "error renewing certificate from existing server certificate"),
  202. http.StatusInternalServerError, context{}}
  203. }
  204. serverCert, err := x509.ParseCertificate(crtBytes)
  205. if err != nil {
  206. return nil, nil, &apiError{errors.Wrap(err, "error parsing new server certificate"),
  207. http.StatusInternalServerError, context{}}
  208. }
  209. caCert, err := x509.ParseCertificate(issIdentity.Crt.Raw)
  210. if err != nil {
  211. return nil, nil, &apiError{errors.Wrap(err, "error parsing intermediate certificate"),
  212. http.StatusInternalServerError, context{}}
  213. }
  214. return serverCert, caCert, nil
  215. }
  216. // GetTLSCertificate creates a new leaf certificate to be used by the CA HTTPS server.
  217. func (a *Authority) GetTLSCertificate() (*tls.Certificate, error) {
  218. profile, err := x509util.NewLeafProfile("Step Online CA",
  219. a.intermediateIdentity.Crt, a.intermediateIdentity.Key,
  220. x509util.WithHosts(strings.Join(a.config.DNSNames, ",")))
  221. if err != nil {
  222. return nil, err
  223. }
  224. crtBytes, err := profile.CreateCertificate()
  225. if err != nil {
  226. return nil, err
  227. }
  228. keyPEM, err := pemutil.Serialize(profile.SubjectPrivateKey())
  229. if err != nil {
  230. return nil, err
  231. }
  232. crtPEM := pem.EncodeToMemory(&pem.Block{
  233. Type: "CERTIFICATE",
  234. Bytes: crtBytes,
  235. })
  236. // Load the x509 key pair (combining server and intermediate blocks)
  237. // to a tls.Certificate.
  238. intermediatePEM, err := pemutil.Serialize(a.intermediateIdentity.Crt)
  239. if err != nil {
  240. return nil, err
  241. }
  242. tlsCrt, err := tls.X509KeyPair(append(crtPEM,
  243. pem.EncodeToMemory(intermediatePEM)...),
  244. pem.EncodeToMemory(keyPEM))
  245. if err != nil {
  246. return nil, errors.Wrap(err, "error creating tls certificate")
  247. }
  248. // Get the 'leaf' certificate and set the attribute accordingly.
  249. leaf, err := x509.ParseCertificate(tlsCrt.Certificate[0])
  250. if err != nil {
  251. return nil, errors.Wrap(err, "error parsing tls certificate")
  252. }
  253. tlsCrt.Leaf = leaf
  254. return &tlsCrt, nil
  255. }