order.go 13 KB

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