tls.go 8.8 KB

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