authority.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package scep
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. microx509util "github.com/micromdm/scep/v2/cryptoutil/x509util"
  10. microscep "github.com/micromdm/scep/v2/scep"
  11. "go.mozilla.org/pkcs7"
  12. "go.step.sm/crypto/x509util"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. )
  15. // Authority is the layer that handles all SCEP interactions.
  16. type Authority struct {
  17. prefix string
  18. dns string
  19. intermediateCertificate *x509.Certificate
  20. caCerts []*x509.Certificate // TODO(hs): change to use these instead of root and intermediate
  21. service *Service
  22. signAuth SignAuthority
  23. }
  24. type authorityKey struct{}
  25. // NewContext adds the given authority to the context.
  26. func NewContext(ctx context.Context, a *Authority) context.Context {
  27. return context.WithValue(ctx, authorityKey{}, a)
  28. }
  29. // FromContext returns the current authority from the given context.
  30. func FromContext(ctx context.Context) (a *Authority, ok bool) {
  31. a, ok = ctx.Value(authorityKey{}).(*Authority)
  32. return
  33. }
  34. // MustFromContext returns the current authority from the given context. It will
  35. // panic if the authority is not in the context.
  36. func MustFromContext(ctx context.Context) *Authority {
  37. if a, ok := FromContext(ctx); !ok {
  38. panic("scep authority is not in the context")
  39. } else {
  40. return a
  41. }
  42. }
  43. // AuthorityOptions required to create a new SCEP Authority.
  44. type AuthorityOptions struct {
  45. // Service provides the certificate chain, the signer and the decrypter to the Authority
  46. Service *Service
  47. // DNS is the host used to generate accurate SCEP links. By default the authority
  48. // will use the Host from the request, so this value will only be used if
  49. // request.Host is empty.
  50. DNS string
  51. // Prefix is a URL path prefix under which the SCEP api is served. This
  52. // prefix is required to generate accurate SCEP links.
  53. Prefix string
  54. }
  55. // SignAuthority is the interface for a signing authority
  56. type SignAuthority interface {
  57. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  58. LoadProvisionerByName(string) (provisioner.Interface, error)
  59. }
  60. // New returns a new Authority that implements the SCEP interface.
  61. func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) {
  62. authority := &Authority{
  63. prefix: ops.Prefix,
  64. dns: ops.DNS,
  65. signAuth: signAuth,
  66. }
  67. // TODO: this is not really nice to do; the Service should be removed
  68. // in its entirety to make this more interoperable with the rest of
  69. // step-ca, I think.
  70. if ops.Service != nil {
  71. authority.caCerts = ops.Service.certificateChain
  72. // TODO(hs): look into refactoring SCEP into using just caCerts everywhere, if it makes sense for more elaborate SCEP configuration. Keeping it like this for clarity (for now).
  73. authority.intermediateCertificate = ops.Service.certificateChain[0]
  74. authority.service = ops.Service
  75. }
  76. return authority, nil
  77. }
  78. var (
  79. // TODO: check the default capabilities; https://tools.ietf.org/html/rfc8894#section-3.5.2
  80. defaultCapabilities = []string{
  81. "Renewal", // NOTE: removing this will result in macOS SCEP client stating the server doesn't support renewal, but it uses PKCSreq to do so.
  82. "SHA-1",
  83. "SHA-256",
  84. "AES",
  85. "DES3",
  86. "SCEPStandard",
  87. "POSTPKIOperation",
  88. }
  89. )
  90. // LoadProvisionerByName calls out to the SignAuthority interface to load a
  91. // provisioner by name.
  92. func (a *Authority) LoadProvisionerByName(name string) (provisioner.Interface, error) {
  93. return a.signAuth.LoadProvisionerByName(name)
  94. }
  95. // GetLinkExplicit returns the requested link from the directory.
  96. func (a *Authority) GetLinkExplicit(provName string, abs bool, baseURL *url.URL, inputs ...string) string {
  97. return a.getLinkExplicit(provName, abs, baseURL, inputs...)
  98. }
  99. // getLinkExplicit returns an absolute or partial path to the given resource and a base
  100. // URL dynamically obtained from the request for which the link is being calculated.
  101. func (a *Authority) getLinkExplicit(provisionerName string, abs bool, baseURL *url.URL, inputs ...string) string {
  102. link := "/" + provisionerName
  103. if abs {
  104. // Copy the baseURL value from the pointer. https://github.com/golang/go/issues/38351
  105. u := url.URL{}
  106. if baseURL != nil {
  107. u = *baseURL
  108. }
  109. // If no Scheme is set, then default to http (in case of SCEP)
  110. if u.Scheme == "" {
  111. u.Scheme = "http"
  112. }
  113. // If no Host is set, then use the default (first DNS attr in the ca.json).
  114. if u.Host == "" {
  115. u.Host = a.dns
  116. }
  117. u.Path = a.prefix + link
  118. return u.String()
  119. }
  120. return link
  121. }
  122. // GetCACertificates returns the certificate (chain) for the CA
  123. func (a *Authority) GetCACertificates(ctx context.Context) ([]*x509.Certificate, error) {
  124. // TODO: this should return: the "SCEP Server (RA)" certificate, the issuing CA up to and excl. the root
  125. // Some clients do need the root certificate however; also see: https://github.com/openxpki/openxpki/issues/73
  126. //
  127. // This means we might need to think about if we should use the current intermediate CA
  128. // certificate as the "SCEP Server (RA)" certificate. It might be better to have a distinct
  129. // RA certificate, with a corresponding rsa.PrivateKey, just for SCEP usage, which is signed by
  130. // the intermediate CA. Will need to look how we can provide this nicely within step-ca.
  131. //
  132. // This might also mean that we might want to use a distinct instance of KMS for doing the key operations,
  133. // so that we can use RSA just for SCEP.
  134. //
  135. // Using an RA does not seem to exist in https://tools.ietf.org/html/rfc8894, but is mentioned in
  136. // https://tools.ietf.org/id/draft-nourse-scep-21.html. Will continue using the CA directly for now.
  137. //
  138. // The certificate to use should probably depend on the (configured) provisioner and may
  139. // use a distinct certificate, apart from the intermediate.
  140. p, err := provisionerFromContext(ctx)
  141. if err != nil {
  142. return nil, err
  143. }
  144. if len(a.caCerts) == 0 {
  145. return nil, errors.New("no intermediate certificate available in SCEP authority")
  146. }
  147. certs := []*x509.Certificate{}
  148. certs = append(certs, a.caCerts[0])
  149. // NOTE: we're adding the CA roots here, but they are (highly likely) different than what the RFC means.
  150. // Clients are responsible to select the right cert(s) to use, though.
  151. if p.ShouldIncludeRootInChain() && len(a.caCerts) > 1 {
  152. certs = append(certs, a.caCerts[1])
  153. }
  154. return certs, nil
  155. }
  156. // DecryptPKIEnvelope decrypts an enveloped message
  157. func (a *Authority) DecryptPKIEnvelope(ctx context.Context, msg *PKIMessage) error {
  158. p7c, err := pkcs7.Parse(msg.P7.Content)
  159. if err != nil {
  160. return fmt.Errorf("error parsing pkcs7 content: %w", err)
  161. }
  162. envelope, err := p7c.Decrypt(a.intermediateCertificate, a.service.decrypter)
  163. if err != nil {
  164. return fmt.Errorf("error decrypting encrypted pkcs7 content: %w", err)
  165. }
  166. msg.pkiEnvelope = envelope
  167. switch msg.MessageType {
  168. case microscep.CertRep:
  169. certs, err := microscep.CACerts(msg.pkiEnvelope)
  170. if err != nil {
  171. return fmt.Errorf("error extracting CA certs from pkcs7 degenerate data: %w", err)
  172. }
  173. msg.CertRepMessage.Certificate = certs[0]
  174. return nil
  175. case microscep.PKCSReq, microscep.UpdateReq, microscep.RenewalReq:
  176. csr, err := x509.ParseCertificateRequest(msg.pkiEnvelope)
  177. if err != nil {
  178. return fmt.Errorf("parse CSR from pkiEnvelope: %w", err)
  179. }
  180. // check for challengePassword
  181. cp, err := microx509util.ParseChallengePassword(msg.pkiEnvelope)
  182. if err != nil {
  183. return fmt.Errorf("parse challenge password in pkiEnvelope: %w", err)
  184. }
  185. msg.CSRReqMessage = &microscep.CSRReqMessage{
  186. RawDecrypted: msg.pkiEnvelope,
  187. CSR: csr,
  188. ChallengePassword: cp,
  189. }
  190. return nil
  191. case microscep.GetCRL, microscep.GetCert, microscep.CertPoll:
  192. return errors.New("not implemented")
  193. }
  194. return nil
  195. }
  196. // SignCSR creates an x509.Certificate based on a CSR template and Cert Authority credentials
  197. // returns a new PKIMessage with CertRep data
  198. func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage) (*PKIMessage, error) {
  199. // TODO: intermediate storage of the request? In SCEP it's possible to request a csr/certificate
  200. // to be signed, which can be performed asynchronously / out-of-band. In that case a client can
  201. // poll for the status. It seems to be similar as what can happen in ACME, so might want to model
  202. // the implementation after the one in the ACME authority. Requires storage, etc.
  203. p, err := provisionerFromContext(ctx)
  204. if err != nil {
  205. return nil, err
  206. }
  207. // check if CSRReqMessage has already been decrypted
  208. if msg.CSRReqMessage.CSR == nil {
  209. if err := a.DecryptPKIEnvelope(ctx, msg); err != nil {
  210. return nil, err
  211. }
  212. csr = msg.CSRReqMessage.CSR
  213. }
  214. // Template data
  215. sans := []string{}
  216. sans = append(sans, csr.DNSNames...)
  217. sans = append(sans, csr.EmailAddresses...)
  218. for _, v := range csr.IPAddresses {
  219. sans = append(sans, v.String())
  220. }
  221. for _, v := range csr.URIs {
  222. sans = append(sans, v.String())
  223. }
  224. if len(sans) == 0 {
  225. sans = append(sans, csr.Subject.CommonName)
  226. }
  227. data := x509util.CreateTemplateData(csr.Subject.CommonName, sans)
  228. data.SetCertificateRequest(csr)
  229. data.SetSubject(x509util.Subject{
  230. Country: csr.Subject.Country,
  231. Organization: csr.Subject.Organization,
  232. OrganizationalUnit: csr.Subject.OrganizationalUnit,
  233. Locality: csr.Subject.Locality,
  234. Province: csr.Subject.Province,
  235. StreetAddress: csr.Subject.StreetAddress,
  236. PostalCode: csr.Subject.PostalCode,
  237. SerialNumber: csr.Subject.SerialNumber,
  238. CommonName: csr.Subject.CommonName,
  239. })
  240. // Get authorizations from the SCEP provisioner.
  241. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  242. signOps, err := p.AuthorizeSign(ctx, "")
  243. if err != nil {
  244. return nil, fmt.Errorf("error retrieving authorization options from SCEP provisioner: %w", err)
  245. }
  246. // Unlike most of the provisioners, scep's AuthorizeSign method doesn't
  247. // define the templates, and the template data used in WebHooks is not
  248. // available.
  249. for _, signOp := range signOps {
  250. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  251. wc.TemplateData = data
  252. }
  253. }
  254. opts := provisioner.SignOptions{}
  255. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  256. if err != nil {
  257. return nil, fmt.Errorf("error creating template options from SCEP provisioner: %w", err)
  258. }
  259. signOps = append(signOps, templateOptions)
  260. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  261. if err != nil {
  262. return nil, fmt.Errorf("error generating certificate for order: %w", err)
  263. }
  264. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  265. cert := certChain[0]
  266. // and create a degenerate cert structure
  267. deg, err := microscep.DegenerateCertificates([]*x509.Certificate{cert})
  268. if err != nil {
  269. return nil, err
  270. }
  271. // apparently the pkcs7 library uses a global default setting for the content encryption
  272. // algorithm to use when en- or decrypting data. We need to restore the current setting after
  273. // the cryptographic operation, so that other usages of the library are not influenced by
  274. // this call to Encrypt(). We are not required to use the same algorithm the SCEP client uses.
  275. encryptionAlgorithmToRestore := pkcs7.ContentEncryptionAlgorithm
  276. pkcs7.ContentEncryptionAlgorithm = p.GetContentEncryptionAlgorithm()
  277. e7, err := pkcs7.Encrypt(deg, msg.P7.Certificates)
  278. if err != nil {
  279. return nil, err
  280. }
  281. pkcs7.ContentEncryptionAlgorithm = encryptionAlgorithmToRestore
  282. // PKIMessageAttributes to be signed
  283. config := pkcs7.SignerInfoConfig{
  284. ExtraSignedAttributes: []pkcs7.Attribute{
  285. {
  286. Type: oidSCEPtransactionID,
  287. Value: msg.TransactionID,
  288. },
  289. {
  290. Type: oidSCEPpkiStatus,
  291. Value: microscep.SUCCESS,
  292. },
  293. {
  294. Type: oidSCEPmessageType,
  295. Value: microscep.CertRep,
  296. },
  297. {
  298. Type: oidSCEPrecipientNonce,
  299. Value: msg.SenderNonce,
  300. },
  301. {
  302. Type: oidSCEPsenderNonce,
  303. Value: msg.SenderNonce,
  304. },
  305. },
  306. }
  307. signedData, err := pkcs7.NewSignedData(e7)
  308. if err != nil {
  309. return nil, err
  310. }
  311. // add the certificate into the signed data type
  312. // this cert must be added before the signedData because the recipient will expect it
  313. // as the first certificate in the array
  314. signedData.AddCertificate(cert)
  315. authCert := a.intermediateCertificate
  316. // sign the attributes
  317. if err := signedData.AddSigner(authCert, a.service.signer, config); err != nil {
  318. return nil, err
  319. }
  320. certRepBytes, err := signedData.Finish()
  321. if err != nil {
  322. return nil, err
  323. }
  324. cr := &CertRepMessage{
  325. PKIStatus: microscep.SUCCESS,
  326. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  327. Certificate: cert,
  328. degenerate: deg,
  329. }
  330. // create a CertRep message from the original
  331. crepMsg := &PKIMessage{
  332. Raw: certRepBytes,
  333. TransactionID: msg.TransactionID,
  334. MessageType: microscep.CertRep,
  335. CertRepMessage: cr,
  336. }
  337. return crepMsg, nil
  338. }
  339. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  340. func (a *Authority) CreateFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  341. config := pkcs7.SignerInfoConfig{
  342. ExtraSignedAttributes: []pkcs7.Attribute{
  343. {
  344. Type: oidSCEPtransactionID,
  345. Value: msg.TransactionID,
  346. },
  347. {
  348. Type: oidSCEPpkiStatus,
  349. Value: microscep.FAILURE,
  350. },
  351. {
  352. Type: oidSCEPfailInfo,
  353. Value: info,
  354. },
  355. {
  356. Type: oidSCEPfailInfoText,
  357. Value: infoText,
  358. },
  359. {
  360. Type: oidSCEPmessageType,
  361. Value: microscep.CertRep,
  362. },
  363. {
  364. Type: oidSCEPsenderNonce,
  365. Value: msg.SenderNonce,
  366. },
  367. {
  368. Type: oidSCEPrecipientNonce,
  369. Value: msg.SenderNonce,
  370. },
  371. },
  372. }
  373. signedData, err := pkcs7.NewSignedData(nil)
  374. if err != nil {
  375. return nil, err
  376. }
  377. // sign the attributes
  378. if err := signedData.AddSigner(a.intermediateCertificate, a.service.signer, config); err != nil {
  379. return nil, err
  380. }
  381. certRepBytes, err := signedData.Finish()
  382. if err != nil {
  383. return nil, err
  384. }
  385. cr := &CertRepMessage{
  386. PKIStatus: microscep.FAILURE,
  387. FailInfo: microscep.FailInfo(info),
  388. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  389. }
  390. // create a CertRep message from the original
  391. crepMsg := &PKIMessage{
  392. Raw: certRepBytes,
  393. TransactionID: msg.TransactionID,
  394. MessageType: microscep.CertRep,
  395. CertRepMessage: cr,
  396. }
  397. return crepMsg, nil
  398. }
  399. // MatchChallengePassword verifies a SCEP challenge password
  400. func (a *Authority) MatchChallengePassword(ctx context.Context, password string) (bool, error) {
  401. p, err := provisionerFromContext(ctx)
  402. if err != nil {
  403. return false, err
  404. }
  405. if subtle.ConstantTimeCompare([]byte(p.GetChallengePassword()), []byte(password)) == 1 {
  406. return true, nil
  407. }
  408. // TODO: support dynamic challenges, i.e. a list of challenges instead of one?
  409. // That's probably a bit harder to configure, though; likely requires some data store
  410. // that can be interacted with more easily, via some internal API, for example.
  411. return false, nil
  412. }
  413. // GetCACaps returns the CA capabilities
  414. func (a *Authority) GetCACaps(ctx context.Context) []string {
  415. p, err := provisionerFromContext(ctx)
  416. if err != nil {
  417. return defaultCapabilities
  418. }
  419. caps := p.GetCapabilities()
  420. if len(caps) == 0 {
  421. return defaultCapabilities
  422. }
  423. // TODO: validate the caps? Ensure they are the right format according to RFC?
  424. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  425. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  426. // For example for renewals, which we could disable in the provisioner, should then also
  427. // not be reported in cacaps operation.
  428. return caps
  429. }