4
0

authority.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. LoadProvisionerByID(string) (provisioner.Interface, error)
  17. GetLinkExplicit(provName string, absoluteLink bool, baseURL *url.URL, inputs ...string) string
  18. GetCACertificates() ([]*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. service *Service
  31. signAuth SignAuthority
  32. }
  33. // AuthorityOptions required to create a new SCEP Authority.
  34. type AuthorityOptions struct {
  35. // Service provides the certificate chain, the signer and the decrypter to the Authority
  36. Service *Service
  37. // DNS is the host used to generate accurate SCEP links. By default the authority
  38. // will use the Host from the request, so this value will only be used if
  39. // request.Host is empty.
  40. DNS string
  41. // Prefix is a URL path prefix under which the SCEP api is served. This
  42. // prefix is required to generate accurate SCEP links.
  43. Prefix string
  44. }
  45. // SignAuthority is the interface for a signing authority
  46. type SignAuthority interface {
  47. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  48. LoadProvisionerByID(string) (provisioner.Interface, error)
  49. }
  50. // New returns a new Authority that implements the SCEP interface.
  51. func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) {
  52. authority := &Authority{
  53. prefix: ops.Prefix,
  54. dns: ops.DNS,
  55. signAuth: signAuth,
  56. }
  57. // TODO: this is not really nice to do; the Service should be removed
  58. // in its entirety to make this more interoperable with the rest of
  59. // step-ca, I think.
  60. if ops.Service != nil {
  61. authority.intermediateCertificate = ops.Service.certificateChain[0]
  62. authority.service = ops.Service
  63. }
  64. return authority, nil
  65. }
  66. var (
  67. // TODO: check the default capabilities; https://tools.ietf.org/html/rfc8894#section-3.5.2
  68. defaultCapabilities = []string{
  69. "Renewal",
  70. "SHA-1",
  71. "SHA-256",
  72. "AES",
  73. "DES3",
  74. "SCEPStandard",
  75. "POSTPKIOperation",
  76. }
  77. )
  78. // LoadProvisionerByID calls out to the SignAuthority interface to load a
  79. // provisioner by ID.
  80. func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  81. return a.signAuth.LoadProvisionerByID(id)
  82. }
  83. // GetLinkExplicit returns the requested link from the directory.
  84. func (a *Authority) GetLinkExplicit(provName string, abs bool, baseURL *url.URL, inputs ...string) string {
  85. // TODO: taken from ACME; move it to directory (if we need a directory in SCEP)?
  86. return a.getLinkExplicit(provName, abs, baseURL, inputs...)
  87. }
  88. // getLinkExplicit returns an absolute or partial path to the given resource and a base
  89. // URL dynamically obtained from the request for which the link is being calculated.
  90. func (a *Authority) getLinkExplicit(provisionerName string, abs bool, baseURL *url.URL, inputs ...string) string {
  91. // TODO: do we need to provide a way to provide a different suffix?
  92. // Like "/cgi-bin/pkiclient.exe"? Or would it be enough to have that as the name?
  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() ([]*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. if a.intermediateCertificate == nil {
  132. return nil, errors.New("no intermediate certificate available in SCEP authority")
  133. }
  134. return []*x509.Certificate{a.intermediateCertificate}, nil
  135. }
  136. // DecryptPKIEnvelope decrypts an enveloped message
  137. func (a *Authority) DecryptPKIEnvelope(ctx context.Context, msg *PKIMessage) error {
  138. p7c, err := pkcs7.Parse(msg.P7.Content)
  139. if err != nil {
  140. return errors.Wrap(err, "error parsing pkcs7 content")
  141. }
  142. envelope, err := p7c.Decrypt(a.intermediateCertificate, a.service.decrypter)
  143. if err != nil {
  144. return errors.Wrap(err, "error decrypting encrypted pkcs7 content")
  145. }
  146. msg.pkiEnvelope = envelope
  147. switch msg.MessageType {
  148. case microscep.CertRep:
  149. certs, err := microscep.CACerts(msg.pkiEnvelope)
  150. if err != nil {
  151. return errors.Wrap(err, "error extracting CA certs from pkcs7 degenerate data")
  152. }
  153. msg.CertRepMessage.Certificate = certs[0]
  154. return nil
  155. case microscep.PKCSReq, microscep.UpdateReq, microscep.RenewalReq:
  156. csr, err := x509.ParseCertificateRequest(msg.pkiEnvelope)
  157. if err != nil {
  158. return errors.Wrap(err, "parse CSR from pkiEnvelope")
  159. }
  160. // check for challengePassword
  161. cp, err := microx509util.ParseChallengePassword(msg.pkiEnvelope)
  162. if err != nil {
  163. return errors.Wrap(err, "parse challenge password in pkiEnvelope")
  164. }
  165. msg.CSRReqMessage = &microscep.CSRReqMessage{
  166. RawDecrypted: msg.pkiEnvelope,
  167. CSR: csr,
  168. ChallengePassword: cp,
  169. }
  170. return nil
  171. case microscep.GetCRL, microscep.GetCert, microscep.CertPoll:
  172. return errors.Errorf("not implemented")
  173. }
  174. return nil
  175. }
  176. // SignCSR creates an x509.Certificate based on a CSR template and Cert Authority credentials
  177. // returns a new PKIMessage with CertRep data
  178. //func (msg *PKIMessage) SignCSR(crtAuth *x509.Certificate, keyAuth *rsa.PrivateKey, template *x509.Certificate) (*PKIMessage, error) {
  179. //func (a *Authority) SignCSR(ctx context.Context, msg *PKIMessage, template *x509.Certificate) (*PKIMessage, error) {
  180. func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage) (*PKIMessage, error) {
  181. // TODO: intermediate storage of the request? In SCEP it's possible to request a csr/certificate
  182. // to be signed, which can be performed asynchronously / out-of-band. In that case a client can
  183. // poll for the status. It seems to be similar as what can happen in ACME, so might want to model
  184. // the implementation after the one in the ACME authority. Requires storage, etc.
  185. p, err := ProvisionerFromContext(ctx)
  186. if err != nil {
  187. return nil, err
  188. }
  189. // check if CSRReqMessage has already been decrypted
  190. if msg.CSRReqMessage.CSR == nil {
  191. if err := a.DecryptPKIEnvelope(ctx, msg); err != nil {
  192. return nil, err
  193. }
  194. csr = msg.CSRReqMessage.CSR
  195. }
  196. // Template data
  197. sans := []string{}
  198. sans = append(sans, csr.DNSNames...)
  199. sans = append(sans, csr.EmailAddresses...)
  200. for _, v := range csr.IPAddresses {
  201. sans = append(sans, v.String())
  202. }
  203. for _, v := range csr.URIs {
  204. sans = append(sans, v.String())
  205. }
  206. if len(sans) == 0 {
  207. sans = append(sans, csr.Subject.CommonName)
  208. }
  209. data := x509util.CreateTemplateData(csr.Subject.CommonName, sans)
  210. data.SetCertificateRequest(csr)
  211. data.SetSubject(x509util.Subject{
  212. Country: csr.Subject.Country,
  213. Organization: csr.Subject.Organization,
  214. OrganizationalUnit: csr.Subject.OrganizationalUnit,
  215. Locality: csr.Subject.Locality,
  216. Province: csr.Subject.Province,
  217. StreetAddress: csr.Subject.StreetAddress,
  218. PostalCode: csr.Subject.PostalCode,
  219. SerialNumber: csr.Subject.SerialNumber,
  220. CommonName: csr.Subject.CommonName,
  221. })
  222. // Get authorizations from the SCEP provisioner.
  223. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  224. signOps, err := p.AuthorizeSign(ctx, "")
  225. if err != nil {
  226. return nil, errors.Wrap(err, "error retrieving authorization options from SCEP provisioner")
  227. }
  228. opts := provisioner.SignOptions{
  229. // NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  230. // NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  231. }
  232. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  233. if err != nil {
  234. return nil, errors.Wrap(err, "error creating template options from SCEP provisioner")
  235. }
  236. signOps = append(signOps, templateOptions)
  237. certChain, err := a.signAuth.Sign(csr, opts, signOps...)
  238. if err != nil {
  239. return nil, errors.Wrap(err, "error generating certificate for order")
  240. }
  241. // take the issued certificate (only); https://tools.ietf.org/html/rfc8894#section-3.3.2
  242. cert := certChain[0]
  243. // and create a degenerate cert structure
  244. deg, err := microscep.DegenerateCertificates([]*x509.Certificate{cert})
  245. if err != nil {
  246. return nil, err
  247. }
  248. e7, err := pkcs7.Encrypt(deg, msg.P7.Certificates)
  249. if err != nil {
  250. return nil, err
  251. }
  252. // PKIMessageAttributes to be signed
  253. config := pkcs7.SignerInfoConfig{
  254. ExtraSignedAttributes: []pkcs7.Attribute{
  255. {
  256. Type: oidSCEPtransactionID,
  257. Value: msg.TransactionID,
  258. },
  259. {
  260. Type: oidSCEPpkiStatus,
  261. Value: microscep.SUCCESS,
  262. },
  263. {
  264. Type: oidSCEPmessageType,
  265. Value: microscep.CertRep,
  266. },
  267. {
  268. Type: oidSCEPrecipientNonce,
  269. Value: msg.SenderNonce,
  270. },
  271. {
  272. Type: oidSCEPsenderNonce,
  273. Value: msg.SenderNonce,
  274. },
  275. },
  276. }
  277. signedData, err := pkcs7.NewSignedData(e7)
  278. if err != nil {
  279. return nil, err
  280. }
  281. // add the certificate into the signed data type
  282. // this cert must be added before the signedData because the recipient will expect it
  283. // as the first certificate in the array
  284. signedData.AddCertificate(cert)
  285. authCert := a.intermediateCertificate
  286. // sign the attributes
  287. if err := signedData.AddSigner(authCert, a.service.signer, config); err != nil {
  288. return nil, err
  289. }
  290. certRepBytes, err := signedData.Finish()
  291. if err != nil {
  292. return nil, err
  293. }
  294. cr := &CertRepMessage{
  295. PKIStatus: microscep.SUCCESS,
  296. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  297. Certificate: cert,
  298. degenerate: deg,
  299. }
  300. // create a CertRep message from the original
  301. crepMsg := &PKIMessage{
  302. Raw: certRepBytes,
  303. TransactionID: msg.TransactionID,
  304. MessageType: microscep.CertRep,
  305. CertRepMessage: cr,
  306. }
  307. return crepMsg, nil
  308. }
  309. // CreateFailureResponse creates an appropriately signed reply for PKI operations
  310. func (a *Authority) CreateFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) {
  311. config := pkcs7.SignerInfoConfig{
  312. ExtraSignedAttributes: []pkcs7.Attribute{
  313. {
  314. Type: oidSCEPtransactionID,
  315. Value: msg.TransactionID,
  316. },
  317. {
  318. Type: oidSCEPpkiStatus,
  319. Value: microscep.FAILURE,
  320. },
  321. {
  322. Type: oidSCEPfailInfo,
  323. Value: info,
  324. },
  325. {
  326. Type: oidSCEPfailInfoText,
  327. Value: infoText,
  328. },
  329. {
  330. Type: oidSCEPmessageType,
  331. Value: microscep.CertRep,
  332. },
  333. {
  334. Type: oidSCEPsenderNonce,
  335. Value: msg.SenderNonce,
  336. },
  337. {
  338. Type: oidSCEPrecipientNonce,
  339. Value: msg.SenderNonce,
  340. },
  341. },
  342. }
  343. signedData, err := pkcs7.NewSignedData(nil)
  344. if err != nil {
  345. return nil, err
  346. }
  347. // sign the attributes
  348. if err := signedData.AddSigner(a.intermediateCertificate, a.service.signer, config); err != nil {
  349. return nil, err
  350. }
  351. certRepBytes, err := signedData.Finish()
  352. if err != nil {
  353. return nil, err
  354. }
  355. cr := &CertRepMessage{
  356. PKIStatus: microscep.FAILURE,
  357. FailInfo: microscep.FailInfo(info),
  358. RecipientNonce: microscep.RecipientNonce(msg.SenderNonce),
  359. }
  360. // create a CertRep message from the original
  361. crepMsg := &PKIMessage{
  362. Raw: certRepBytes,
  363. TransactionID: msg.TransactionID,
  364. MessageType: microscep.CertRep,
  365. CertRepMessage: cr,
  366. }
  367. return crepMsg, nil
  368. }
  369. // MatchChallengePassword verifies a SCEP challenge password
  370. func (a *Authority) MatchChallengePassword(ctx context.Context, password string) (bool, error) {
  371. p, err := ProvisionerFromContext(ctx)
  372. if err != nil {
  373. return false, err
  374. }
  375. if subtle.ConstantTimeCompare([]byte(p.GetChallengePassword()), []byte(password)) == 1 {
  376. return true, nil
  377. }
  378. // TODO: support dynamic challenges, i.e. a list of challenges instead of one?
  379. // That's probably a bit harder to configure, though; likely requires some data store
  380. // that can be interacted with more easily, via some internal API, for example.
  381. return false, nil
  382. }
  383. // GetCACaps returns the CA capabilities
  384. func (a *Authority) GetCACaps(ctx context.Context) []string {
  385. p, err := ProvisionerFromContext(ctx)
  386. if err != nil {
  387. return defaultCapabilities
  388. }
  389. caps := p.GetCapabilities()
  390. if len(caps) == 0 {
  391. return defaultCapabilities
  392. }
  393. // TODO: validate the caps? Ensure they are the right format according to RFC?
  394. // TODO: ensure that the capabilities are actually "enforced"/"verified" in code too:
  395. // check that only parts of the spec are used in the implementation belonging to the capabilities.
  396. // For example for renewals, which we could disable in the provisioner, should then also
  397. // not be reported in cacaps operation.
  398. return caps
  399. }