order.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/x509"
  6. "encoding/json"
  7. "net"
  8. "sort"
  9. "strings"
  10. "time"
  11. "github.com/google/go-attestation/oid"
  12. attest_x509 "github.com/google/go-attestation/x509"
  13. "github.com/smallstep/certificates/authority/provisioner"
  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. // Finalize signs a certificate if the necessary conditions for Order completion
  117. // have been met.
  118. //
  119. // TODO(mariano): Here or in the challenge validation we should perform some
  120. // external validation using the identifier value and the attestation data. From
  121. // a validation service we can get the list of SANs to set in the final
  122. // certificate.
  123. func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
  124. if err := o.UpdateStatus(ctx, db); err != nil {
  125. return err
  126. }
  127. switch o.Status {
  128. case StatusInvalid:
  129. return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
  130. case StatusValid:
  131. return nil
  132. case StatusPending:
  133. return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
  134. case StatusReady:
  135. break
  136. default:
  137. return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
  138. }
  139. // canonicalize the CSR to allow for comparison
  140. csr = canonicalize(csr)
  141. // Template data
  142. data := x509util.NewTemplateData()
  143. data.SetCommonName(csr.Subject.CommonName)
  144. // Custom sign options passed to authority.Sign
  145. var extraOptions []provisioner.SignOption
  146. // TODO: support for multiple identifiers?
  147. var permanentIdentifier string
  148. for i := range o.Identifiers {
  149. if o.Identifiers[i].Type == PermanentIdentifier {
  150. permanentIdentifier = o.Identifiers[i].Value
  151. break
  152. }
  153. }
  154. var defaultTemplate string
  155. if permanentIdentifier != "" {
  156. defaultTemplate = x509util.DefaultAttestedLeafTemplate
  157. data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
  158. Type: x509util.PermanentIdentifierType,
  159. Value: permanentIdentifier,
  160. })
  161. extraOptions = append(extraOptions, provisioner.AttestationData{
  162. PermanentIdentifier: permanentIdentifier,
  163. })
  164. } else {
  165. defaultTemplate = x509util.DefaultLeafTemplate
  166. sans, err := o.sans(csr)
  167. if err != nil {
  168. return err
  169. }
  170. data.SetSubjectAlternativeNames(sans...)
  171. }
  172. deviceIDs, err := o.deviceIDs(csr)
  173. if err != nil {
  174. return err
  175. }
  176. // Get authorizations from the ACME provisioner.
  177. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  178. signOps, err := p.AuthorizeSign(ctx, "")
  179. if err != nil {
  180. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  181. }
  182. templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
  183. if err != nil {
  184. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  185. }
  186. // Build extra signing options.
  187. signOps = append(signOps, templateOptions)
  188. signOps = append(signOps, extraOptions...)
  189. // Sign a new certificate.
  190. certChain, err := auth.Sign(csr, provisioner.SignOptions{
  191. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  192. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  193. }, signOps...)
  194. if err != nil {
  195. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  196. }
  197. cert := &Certificate{
  198. AccountID: o.AccountID,
  199. OrderID: o.ID,
  200. Leaf: certChain[0],
  201. Intermediates: certChain[1:],
  202. }
  203. if err := db.CreateCertificate(ctx, cert); err != nil {
  204. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  205. }
  206. o.CertificateID = cert.ID
  207. o.Status = StatusValid
  208. if err = db.UpdateOrder(ctx, o); err != nil {
  209. return WrapErrorISE(err, "error updating order %s", o.ID)
  210. }
  211. return nil
  212. }
  213. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  214. var sans []x509util.SubjectAlternativeName
  215. if len(csr.EmailAddresses) > 0 || len(csr.URIs) > 0 {
  216. return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
  217. }
  218. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  219. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
  220. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  221. orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
  222. indexDNS, indexIP, indexPID := 0, 0, 0
  223. for _, n := range o.Identifiers {
  224. switch n.Type {
  225. case DNS:
  226. orderNames[indexDNS] = n.Value
  227. indexDNS++
  228. case IP:
  229. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  230. indexIP++
  231. case PermanentIdentifier:
  232. orderPIDs[indexPID] = n.Value
  233. indexPID++
  234. default:
  235. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  236. }
  237. }
  238. orderNames = uniqueSortedLowerNames(orderNames)
  239. orderIPs = uniqueSortedIPs(orderIPs)
  240. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses)
  241. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  242. index := 0
  243. // Validate identifier names against CSR alternative names.
  244. //
  245. // Note that with certificate templates we are not going to check for the
  246. // absence of other SANs as they will only be set if the template allows
  247. // them.
  248. if len(csr.DNSNames) != len(orderNames) {
  249. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  250. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  251. }
  252. for i := range csr.DNSNames {
  253. if csr.DNSNames[i] != orderNames[i] {
  254. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  255. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  256. }
  257. sans[index] = x509util.SubjectAlternativeName{
  258. Type: x509util.DNSType,
  259. Value: csr.DNSNames[i],
  260. }
  261. index++
  262. }
  263. if len(csr.IPAddresses) != len(orderIPs) {
  264. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  265. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  266. }
  267. for i := range csr.IPAddresses {
  268. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  269. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  270. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  271. }
  272. sans[index] = x509util.SubjectAlternativeName{
  273. Type: x509util.IPType,
  274. Value: csr.IPAddresses[i].String(),
  275. }
  276. index++
  277. }
  278. return sans, nil
  279. }
  280. func (o *Order) deviceIDs(csr *x509.CertificateRequest) ([]x509util.PermanentIdentifier, error) {
  281. var permIDs []x509util.PermanentIdentifier
  282. for _, ext := range csr.Extensions {
  283. if ext.Id.Equal(oid.SubjectAltName) {
  284. san, err := attest_x509.ParseSubjectAltName(ext)
  285. if err != nil {
  286. return nil, err
  287. }
  288. for _, pi := range san.PermanentIdentifiers {
  289. permIDs = append(permIDs, x509util.PermanentIdentifier{
  290. Value: pi.IdentifierValue,
  291. Assigner: pi.Assigner,
  292. })
  293. }
  294. }
  295. }
  296. return permIDs, nil
  297. }
  298. // numberOfIdentifierType returns the number of Identifiers that
  299. // are of type typ.
  300. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  301. c := 0
  302. for _, id := range ids {
  303. if id.Type == typ {
  304. c++
  305. }
  306. }
  307. return c
  308. }
  309. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  310. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  311. // but may not be expected. It also adds a Subject Common Name to either the IP
  312. // addresses or DNS names slice, depending on whether it can be parsed as an IP
  313. // or not. This might result in an additional SAN in the final certificate.
  314. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  315. // for clarity only; we're operating on the same object by pointer
  316. canonicalized = csr
  317. // RFC8555: The CSR MUST indicate the exact same set of requested
  318. // identifiers as the initial newOrder request. Identifiers of type "dns"
  319. // MUST appear either in the commonName portion of the requested subject
  320. // name or in an extensionRequest attribute [RFC2985] requesting a
  321. // subjectAltName extension, or both. Subject Common Names that can be
  322. // parsed as an IP are included as an IP address for the equality check.
  323. // If these were excluded, a certificate could contain an IP as the
  324. // common name without having been challenged.
  325. if csr.Subject.CommonName != "" {
  326. if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
  327. canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
  328. } else {
  329. canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
  330. }
  331. }
  332. canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
  333. canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
  334. return canonicalized
  335. }
  336. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  337. // not considered equal. IPv6 representations of IPv4 addresses are
  338. // considered equal to the IPv4 address in this implementation, which is
  339. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  340. // is equal to "192.168.42.42". This is considered a known issue within
  341. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  342. func ipsAreEqual(x, y net.IP) bool {
  343. if x == nil || y == nil {
  344. return false
  345. }
  346. return x.Equal(y)
  347. }
  348. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  349. // of them are lowercased. The returned names will be in their lowercased form
  350. // and sorted alphabetically.
  351. func uniqueSortedLowerNames(names []string) (unique []string) {
  352. nameMap := make(map[string]int, len(names))
  353. for _, name := range names {
  354. nameMap[strings.ToLower(name)] = 1
  355. }
  356. unique = make([]string, 0, len(nameMap))
  357. for name := range nameMap {
  358. unique = append(unique, name)
  359. }
  360. sort.Strings(unique)
  361. return
  362. }
  363. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  364. // are sorted by their bytes (octet) representation.
  365. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  366. type entry struct {
  367. ip net.IP
  368. }
  369. ipEntryMap := make(map[string]entry, len(ips))
  370. for _, ip := range ips {
  371. // reparsing the IP results in the IP being represented using 16 bytes
  372. // for both IPv4 as well as IPv6, even when the ips slice contains IPs that
  373. // are represented by 4 bytes. This ensures a fair comparison and thus ordering.
  374. ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
  375. }
  376. unique = make([]net.IP, 0, len(ipEntryMap))
  377. for _, entry := range ipEntryMap {
  378. unique = append(unique, entry.ip)
  379. }
  380. sort.Slice(unique, func(i, j int) bool {
  381. return bytes.Compare(unique[i], unique[j]) < 0
  382. })
  383. return
  384. }