authority.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. opts := provisioner.SignOptions{}
  247. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  248. if err != nil {
  249. return nil, fmt.Errorf("error creating template options from SCEP provisioner: %w", err)
  250. }
  251. signOps = append(signOps, templateOptions)
  252. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  253. if err != nil {
  254. return nil, fmt.Errorf("error generating certificate for order: %w", err)
  255. }
  256. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  257. cert := certChain[0]
  258. // and create a degenerate cert structure
  259. deg, err := microscep.DegenerateCertificates([]*x509.Certificate{cert})
  260. if err != nil {
  261. return nil, err
  262. }
  263. // apparently the pkcs7 library uses a global default setting for the content encryption
  264. // algorithm to use when en- or decrypting data. We need to restore the current setting after
  265. // the cryptographic operation, so that other usages of the library are not influenced by
  266. // this call to Encrypt(). We are not required to use the same algorithm the SCEP client uses.
  267. encryptionAlgorithmToRestore := pkcs7.ContentEncryptionAlgorithm
  268. pkcs7.ContentEncryptionAlgorithm = p.GetContentEncryptionAlgorithm()
  269. e7, err := pkcs7.Encrypt(deg, msg.P7.Certificates)
  270. if err != nil {
  271. return nil, err
  272. }
  273. pkcs7.ContentEncryptionAlgorithm = encryptionAlgorithmToRestore
  274. // PKIMessageAttributes to be signed
  275. config := pkcs7.SignerInfoConfig{
  276. ExtraSignedAttributes: []pkcs7.Attribute{
  277. {
  278. Type: oidSCEPtransactionID,
  279. Value: msg.TransactionID,
  280. },
  281. {
  282. Type: oidSCEPpkiStatus,
  283. Value: microscep.SUCCESS,
  284. },
  285. {
  286. Type: oidSCEPmessageType,
  287. Value: microscep.CertRep,
  288. },
  289. {
  290. Type: oidSCEPrecipientNonce,
  291. Value: msg.SenderNonce,
  292. },
  293. {
  294. Type: oidSCEPsenderNonce,
  295. Value: msg.SenderNonce,
  296. },
  297. },
  298. }
  299. signedData, err := pkcs7.NewSignedData(e7)
  300. if err != nil {
  301. return nil, err
  302. }
  303. // add the certificate into the signed data type
  304. // this cert must be added before the signedData because the recipient will expect it
  305. // as the first certificate in the array
  306. signedData.AddCertificate(cert)
  307. authCert := a.intermediateCertificate
  308. // sign the attributes
  309. if err := signedData.AddSigner(authCert, a.service.signer, config); err != nil {
  310. return nil, err
  311. }
  312. certRepBytes, err := signedData.Finish()
  313. if err != nil {
  314. return nil, err
  315. }
  316. cr := &CertRepMessage{
  317. PKIStatus: microscep.SUCCESS,
  318. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  319. Certificate: cert,
  320. degenerate: deg,
  321. }
  322. // create a CertRep message from the original
  323. crepMsg := &PKIMessage{
  324. Raw: certRepBytes,
  325. TransactionID: msg.TransactionID,
  326. MessageType: microscep.CertRep,
  327. CertRepMessage: cr,
  328. }
  329. return crepMsg, nil
  330. }
  331. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  332. func (a *Authority) CreateFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  333. config := pkcs7.SignerInfoConfig{
  334. ExtraSignedAttributes: []pkcs7.Attribute{
  335. {
  336. Type: oidSCEPtransactionID,
  337. Value: msg.TransactionID,
  338. },
  339. {
  340. Type: oidSCEPpkiStatus,
  341. Value: microscep.FAILURE,
  342. },
  343. {
  344. Type: oidSCEPfailInfo,
  345. Value: info,
  346. },
  347. {
  348. Type: oidSCEPfailInfoText,
  349. Value: infoText,
  350. },
  351. {
  352. Type: oidSCEPmessageType,
  353. Value: microscep.CertRep,
  354. },
  355. {
  356. Type: oidSCEPsenderNonce,
  357. Value: msg.SenderNonce,
  358. },
  359. {
  360. Type: oidSCEPrecipientNonce,
  361. Value: msg.SenderNonce,
  362. },
  363. },
  364. }
  365. signedData, err := pkcs7.NewSignedData(nil)
  366. if err != nil {
  367. return nil, err
  368. }
  369. // sign the attributes
  370. if err := signedData.AddSigner(a.intermediateCertificate, a.service.signer, config); err != nil {
  371. return nil, err
  372. }
  373. certRepBytes, err := signedData.Finish()
  374. if err != nil {
  375. return nil, err
  376. }
  377. cr := &CertRepMessage{
  378. PKIStatus: microscep.FAILURE,
  379. FailInfo: microscep.FailInfo(info),
  380. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  381. }
  382. // create a CertRep message from the original
  383. crepMsg := &PKIMessage{
  384. Raw: certRepBytes,
  385. TransactionID: msg.TransactionID,
  386. MessageType: microscep.CertRep,
  387. CertRepMessage: cr,
  388. }
  389. return crepMsg, nil
  390. }
  391. // MatchChallengePassword verifies a SCEP challenge password
  392. func (a *Authority) MatchChallengePassword(ctx context.Context, password string) (bool, error) {
  393. p, err := provisionerFromContext(ctx)
  394. if err != nil {
  395. return false, err
  396. }
  397. if subtle.ConstantTimeCompare([]byte(p.GetChallengePassword()), []byte(password)) == 1 {
  398. return true, nil
  399. }
  400. // TODO: support dynamic challenges, i.e. a list of challenges instead of one?
  401. // That's probably a bit harder to configure, though; likely requires some data store
  402. // that can be interacted with more easily, via some internal API, for example.
  403. return false, nil
  404. }
  405. // GetCACaps returns the CA capabilities
  406. func (a *Authority) GetCACaps(ctx context.Context) []string {
  407. p, err := provisionerFromContext(ctx)
  408. if err != nil {
  409. return defaultCapabilities
  410. }
  411. caps := p.GetCapabilities()
  412. if len(caps) == 0 {
  413. return defaultCapabilities
  414. }
  415. // TODO: validate the caps? Ensure they are the right format according to RFC?
  416. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  417. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  418. // For example for renewals, which we could disable in the provisioner, should then also
  419. // not be reported in cacaps operation.
  420. return caps
  421. }