authority.go 15 KB

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