order.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "crypto/x509"
  7. "encoding/json"
  8. "net"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. "go.step.sm/crypto/keyutil"
  14. "go.step.sm/crypto/x509util"
  15. )
  16. type IdentifierType string
  17. const (
  18. // IP is the ACME ip identifier type
  19. IP IdentifierType = "ip"
  20. // DNS is the ACME dns identifier type
  21. DNS IdentifierType = "dns"
  22. // PermanentIdentifier is the ACME permanent-identifier identifier type
  23. // defined in https://datatracker.ietf.org/doc/html/draft-bweeks-acme-device-attest-00
  24. PermanentIdentifier IdentifierType = "permanent-identifier"
  25. )
  26. // Identifier encodes the type that an order pertains to.
  27. type Identifier struct {
  28. Type IdentifierType `json:"type"`
  29. Value string `json:"value"`
  30. }
  31. // Order contains order metadata for the ACME protocol order type.
  32. type Order struct {
  33. ID string `json:"id"`
  34. AccountID string `json:"-"`
  35. ProvisionerID string `json:"-"`
  36. Status Status `json:"status"`
  37. ExpiresAt time.Time `json:"expires"`
  38. Identifiers []Identifier `json:"identifiers"`
  39. NotBefore time.Time `json:"notBefore"`
  40. NotAfter time.Time `json:"notAfter"`
  41. Error *Error `json:"error,omitempty"`
  42. AuthorizationIDs []string `json:"-"`
  43. AuthorizationURLs []string `json:"authorizations"`
  44. FinalizeURL string `json:"finalize"`
  45. CertificateID string `json:"-"`
  46. CertificateURL string `json:"certificate,omitempty"`
  47. }
  48. // ToLog enables response logging.
  49. func (o *Order) ToLog() (interface{}, error) {
  50. b, err := json.Marshal(o)
  51. if err != nil {
  52. return nil, WrapErrorISE(err, "error marshaling order for logging")
  53. }
  54. return string(b), nil
  55. }
  56. // UpdateStatus updates the ACME Order Status if necessary.
  57. // Changes to the order are saved using the database interface.
  58. func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
  59. now := clock.Now()
  60. switch o.Status {
  61. case StatusInvalid:
  62. return nil
  63. case StatusValid:
  64. return nil
  65. case StatusReady:
  66. // Check expiry
  67. if now.After(o.ExpiresAt) {
  68. o.Status = StatusInvalid
  69. o.Error = NewError(ErrorMalformedType, "order has expired")
  70. break
  71. }
  72. return nil
  73. case StatusPending:
  74. // Check expiry
  75. if now.After(o.ExpiresAt) {
  76. o.Status = StatusInvalid
  77. o.Error = NewError(ErrorMalformedType, "order has expired")
  78. break
  79. }
  80. var count = map[Status]int{
  81. StatusValid: 0,
  82. StatusInvalid: 0,
  83. StatusPending: 0,
  84. }
  85. for _, azID := range o.AuthorizationIDs {
  86. az, err := db.GetAuthorization(ctx, azID)
  87. if err != nil {
  88. return WrapErrorISE(err, "error getting authorization ID %s", azID)
  89. }
  90. if err = az.UpdateStatus(ctx, db); err != nil {
  91. return WrapErrorISE(err, "error updating authorization ID %s", azID)
  92. }
  93. st := az.Status
  94. count[st]++
  95. }
  96. switch {
  97. case count[StatusInvalid] > 0:
  98. o.Status = StatusInvalid
  99. // No change in the order status, so just return the order as is -
  100. // without writing any changes.
  101. case count[StatusPending] > 0:
  102. return nil
  103. case count[StatusValid] == len(o.AuthorizationIDs):
  104. o.Status = StatusReady
  105. default:
  106. return NewErrorISE("unexpected authz status")
  107. }
  108. default:
  109. return NewErrorISE("unrecognized order status: %s", o.Status)
  110. }
  111. if err := db.UpdateOrder(ctx, o); err != nil {
  112. return WrapErrorISE(err, "error updating order")
  113. }
  114. return nil
  115. }
  116. // getKeyFingerprint returns a fingerprint from the list of authorizations. This
  117. // fingerprint is used on the device-attest-01 flow to verify the attestation
  118. // certificate public key with the CSR public key.
  119. //
  120. // There's no point on reading all the authorizations as there will be only one
  121. // for a permanent identifier.
  122. func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string, error) {
  123. for _, azID := range o.AuthorizationIDs {
  124. az, err := db.GetAuthorization(ctx, azID)
  125. if err != nil {
  126. return "", WrapErrorISE(err, "error getting authorization %q", azID)
  127. }
  128. // There's no point on reading all the authorizations as there will
  129. // be only one for a permanent identifier.
  130. if az.Fingerprint != "" {
  131. return az.Fingerprint, nil
  132. }
  133. }
  134. return "", nil
  135. }
  136. // Finalize signs a certificate if the necessary conditions for Order completion
  137. // have been met.
  138. //
  139. // TODO(mariano): Here or in the challenge validation we should perform some
  140. // external validation using the identifier value and the attestation data. From
  141. // a validation service we can get the list of SANs to set in the final
  142. // certificate.
  143. func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
  144. if err := o.UpdateStatus(ctx, db); err != nil {
  145. return err
  146. }
  147. switch o.Status {
  148. case StatusInvalid:
  149. return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
  150. case StatusValid:
  151. return nil
  152. case StatusPending:
  153. return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
  154. case StatusReady:
  155. break
  156. default:
  157. return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
  158. }
  159. // Get key fingerprint if any. And then compare it with the CSR fingerprint.
  160. //
  161. // In device-attest-01 challenges we should check that the keys in the CSR
  162. // and the attestation certificate are the same.
  163. fingerprint, err := o.getAuthorizationFingerprint(ctx, db)
  164. if err != nil {
  165. return err
  166. }
  167. if fingerprint != "" {
  168. fp, err := keyutil.Fingerprint(csr.PublicKey)
  169. if err != nil {
  170. return WrapErrorISE(err, "error calculating key fingerprint")
  171. }
  172. if subtle.ConstantTimeCompare([]byte(fingerprint), []byte(fp)) == 0 {
  173. return NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
  174. }
  175. }
  176. // canonicalize the CSR to allow for comparison
  177. csr = canonicalize(csr)
  178. // Template data
  179. data := x509util.NewTemplateData()
  180. data.SetCommonName(csr.Subject.CommonName)
  181. // Custom sign options passed to authority.Sign
  182. var extraOptions []provisioner.SignOption
  183. // TODO: support for multiple identifiers?
  184. var permanentIdentifier string
  185. for i := range o.Identifiers {
  186. if o.Identifiers[i].Type == PermanentIdentifier {
  187. permanentIdentifier = o.Identifiers[i].Value
  188. // the first (and only) Permanent Identifier that gets added to the certificate
  189. // should be equal to the Subject Common Name if it's set. If not equal, the CSR
  190. // is rejected, because the Common Name hasn't been challenged in that case. This
  191. // could result in unauthorized access if a relying system relies on the Common
  192. // Name in its authorization logic.
  193. if csr.Subject.CommonName != "" && csr.Subject.CommonName != permanentIdentifier {
  194. return NewError(ErrorBadCSRType, "CSR Subject Common Name does not match identifiers exactly: "+
  195. "CSR Subject Common Name = %s, Order Permanent Identifier = %s", csr.Subject.CommonName, permanentIdentifier)
  196. }
  197. break
  198. }
  199. }
  200. var defaultTemplate string
  201. if permanentIdentifier != "" {
  202. defaultTemplate = x509util.DefaultAttestedLeafTemplate
  203. data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
  204. Type: x509util.PermanentIdentifierType,
  205. Value: permanentIdentifier,
  206. })
  207. extraOptions = append(extraOptions, provisioner.AttestationData{
  208. PermanentIdentifier: permanentIdentifier,
  209. })
  210. } else {
  211. defaultTemplate = x509util.DefaultLeafTemplate
  212. sans, err := o.sans(csr)
  213. if err != nil {
  214. return err
  215. }
  216. data.SetSubjectAlternativeNames(sans...)
  217. }
  218. // Get authorizations from the ACME provisioner.
  219. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  220. signOps, err := p.AuthorizeSign(ctx, "")
  221. if err != nil {
  222. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  223. }
  224. // Unlike most of the provisioners, ACME's AuthorizeSign method doesn't
  225. // define the templates, and the template data used in WebHooks is not
  226. // available.
  227. for _, signOp := range signOps {
  228. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  229. wc.TemplateData = data
  230. }
  231. }
  232. templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
  233. if err != nil {
  234. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  235. }
  236. // Build extra signing options.
  237. signOps = append(signOps, templateOptions)
  238. signOps = append(signOps, extraOptions...)
  239. // Sign a new certificate.
  240. certChain, err := auth.Sign(csr, provisioner.SignOptions{
  241. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  242. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  243. }, signOps...)
  244. if err != nil {
  245. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  246. }
  247. cert := &Certificate{
  248. AccountID: o.AccountID,
  249. OrderID: o.ID,
  250. Leaf: certChain[0],
  251. Intermediates: certChain[1:],
  252. }
  253. if err := db.CreateCertificate(ctx, cert); err != nil {
  254. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  255. }
  256. o.CertificateID = cert.ID
  257. o.Status = StatusValid
  258. if err = db.UpdateOrder(ctx, o); err != nil {
  259. return WrapErrorISE(err, "error updating order %s", o.ID)
  260. }
  261. return nil
  262. }
  263. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  264. var sans []x509util.SubjectAlternativeName
  265. if len(csr.EmailAddresses) > 0 || len(csr.URIs) > 0 {
  266. return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
  267. }
  268. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  269. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
  270. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  271. orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
  272. indexDNS, indexIP, indexPID := 0, 0, 0
  273. for _, n := range o.Identifiers {
  274. switch n.Type {
  275. case DNS:
  276. orderNames[indexDNS] = n.Value
  277. indexDNS++
  278. case IP:
  279. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  280. indexIP++
  281. case PermanentIdentifier:
  282. orderPIDs[indexPID] = n.Value
  283. indexPID++
  284. default:
  285. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  286. }
  287. }
  288. orderNames = uniqueSortedLowerNames(orderNames)
  289. orderIPs = uniqueSortedIPs(orderIPs)
  290. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses)
  291. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  292. index := 0
  293. // Validate identifier names against CSR alternative names.
  294. //
  295. // Note that with certificate templates we are not going to check for the
  296. // absence of other SANs as they will only be set if the template allows
  297. // them.
  298. if len(csr.DNSNames) != len(orderNames) {
  299. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  300. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  301. }
  302. for i := range csr.DNSNames {
  303. if csr.DNSNames[i] != orderNames[i] {
  304. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  305. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  306. }
  307. sans[index] = x509util.SubjectAlternativeName{
  308. Type: x509util.DNSType,
  309. Value: csr.DNSNames[i],
  310. }
  311. index++
  312. }
  313. if len(csr.IPAddresses) != len(orderIPs) {
  314. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  315. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  316. }
  317. for i := range csr.IPAddresses {
  318. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  319. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  320. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  321. }
  322. sans[index] = x509util.SubjectAlternativeName{
  323. Type: x509util.IPType,
  324. Value: csr.IPAddresses[i].String(),
  325. }
  326. index++
  327. }
  328. return sans, nil
  329. }
  330. // numberOfIdentifierType returns the number of Identifiers that
  331. // are of type typ.
  332. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  333. c := 0
  334. for _, id := range ids {
  335. if id.Type == typ {
  336. c++
  337. }
  338. }
  339. return c
  340. }
  341. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  342. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  343. // but may not be expected. It also adds a Subject Common Name to either the IP
  344. // addresses or DNS names slice, depending on whether it can be parsed as an IP
  345. // or not. This might result in an additional SAN in the final certificate.
  346. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  347. // for clarity only; we're operating on the same object by pointer
  348. canonicalized = csr
  349. // RFC8555: The CSR MUST indicate the exact same set of requested
  350. // identifiers as the initial newOrder request. Identifiers of type "dns"
  351. // MUST appear either in the commonName portion of the requested subject
  352. // name or in an extensionRequest attribute [RFC2985] requesting a
  353. // subjectAltName extension, or both. Subject Common Names that can be
  354. // parsed as an IP are included as an IP address for the equality check.
  355. // If these were excluded, a certificate could contain an IP as the
  356. // common name without having been challenged.
  357. if csr.Subject.CommonName != "" {
  358. if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
  359. canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
  360. } else {
  361. canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
  362. }
  363. }
  364. canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
  365. canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
  366. return canonicalized
  367. }
  368. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  369. // not considered equal. IPv6 representations of IPv4 addresses are
  370. // considered equal to the IPv4 address in this implementation, which is
  371. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  372. // is equal to "192.168.42.42". This is considered a known issue within
  373. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  374. func ipsAreEqual(x, y net.IP) bool {
  375. if x == nil || y == nil {
  376. return false
  377. }
  378. return x.Equal(y)
  379. }
  380. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  381. // of them are lowercased. The returned names will be in their lowercased form
  382. // and sorted alphabetically.
  383. func uniqueSortedLowerNames(names []string) (unique []string) {
  384. nameMap := make(map[string]int, len(names))
  385. for _, name := range names {
  386. nameMap[strings.ToLower(name)] = 1
  387. }
  388. unique = make([]string, 0, len(nameMap))
  389. for name := range nameMap {
  390. unique = append(unique, name)
  391. }
  392. sort.Strings(unique)
  393. return
  394. }
  395. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  396. // are sorted by their bytes (octet) representation.
  397. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  398. type entry struct {
  399. ip net.IP
  400. }
  401. ipEntryMap := make(map[string]entry, len(ips))
  402. for _, ip := range ips {
  403. // reparsing the IP results in the IP being represented using 16 bytes
  404. // for both IPv4 as well as IPv6, even when the ips slice contains IPs that
  405. // are represented by 4 bytes. This ensures a fair comparison and thus ordering.
  406. ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
  407. }
  408. unique = make([]net.IP, 0, len(ipEntryMap))
  409. for _, entry := range ipEntryMap {
  410. unique = append(unique, entry.ip)
  411. }
  412. sort.Slice(unique, func(i, j int) bool {
  413. return bytes.Compare(unique[i], unique[j]) < 0
  414. })
  415. return
  416. }