order.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 IdentifierType = "ip"
  17. DNS IdentifierType = "dns"
  18. )
  19. // Identifier encodes the type that an order pertains to.
  20. type Identifier struct {
  21. Type IdentifierType `json:"type"`
  22. Value string `json:"value"`
  23. }
  24. // Order contains order metadata for the ACME protocol order type.
  25. type Order struct {
  26. ID string `json:"id"`
  27. AccountID string `json:"-"`
  28. ProvisionerID string `json:"-"`
  29. Status Status `json:"status"`
  30. ExpiresAt time.Time `json:"expires"`
  31. Identifiers []Identifier `json:"identifiers"`
  32. NotBefore time.Time `json:"notBefore"`
  33. NotAfter time.Time `json:"notAfter"`
  34. Error *Error `json:"error,omitempty"`
  35. AuthorizationIDs []string `json:"-"`
  36. AuthorizationURLs []string `json:"authorizations"`
  37. FinalizeURL string `json:"finalize"`
  38. CertificateID string `json:"-"`
  39. CertificateURL string `json:"certificate,omitempty"`
  40. }
  41. // ToLog enables response logging.
  42. func (o *Order) ToLog() (interface{}, error) {
  43. b, err := json.Marshal(o)
  44. if err != nil {
  45. return nil, WrapErrorISE(err, "error marshaling order for logging")
  46. }
  47. return string(b), nil
  48. }
  49. // UpdateStatus updates the ACME Order Status if necessary.
  50. // Changes to the order are saved using the database interface.
  51. func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
  52. now := clock.Now()
  53. switch o.Status {
  54. case StatusInvalid:
  55. return nil
  56. case StatusValid:
  57. return nil
  58. case StatusReady:
  59. // Check expiry
  60. if now.After(o.ExpiresAt) {
  61. o.Status = StatusInvalid
  62. o.Error = NewError(ErrorMalformedType, "order has expired")
  63. break
  64. }
  65. return nil
  66. case StatusPending:
  67. // Check expiry
  68. if now.After(o.ExpiresAt) {
  69. o.Status = StatusInvalid
  70. o.Error = NewError(ErrorMalformedType, "order has expired")
  71. break
  72. }
  73. var count = map[Status]int{
  74. StatusValid: 0,
  75. StatusInvalid: 0,
  76. StatusPending: 0,
  77. }
  78. for _, azID := range o.AuthorizationIDs {
  79. az, err := db.GetAuthorization(ctx, azID)
  80. if err != nil {
  81. return WrapErrorISE(err, "error getting authorization ID %s", azID)
  82. }
  83. if err = az.UpdateStatus(ctx, db); err != nil {
  84. return WrapErrorISE(err, "error updating authorization ID %s", azID)
  85. }
  86. st := az.Status
  87. count[st]++
  88. }
  89. switch {
  90. case count[StatusInvalid] > 0:
  91. o.Status = StatusInvalid
  92. // No change in the order status, so just return the order as is -
  93. // without writing any changes.
  94. case count[StatusPending] > 0:
  95. return nil
  96. case count[StatusValid] == len(o.AuthorizationIDs):
  97. o.Status = StatusReady
  98. default:
  99. return NewErrorISE("unexpected authz status")
  100. }
  101. default:
  102. return NewErrorISE("unrecognized order status: %s", o.Status)
  103. }
  104. if err := db.UpdateOrder(ctx, o); err != nil {
  105. return WrapErrorISE(err, "error updating order")
  106. }
  107. return nil
  108. }
  109. // Finalize signs a certificate if the necessary conditions for Order completion
  110. // have been met.
  111. func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
  112. if err := o.UpdateStatus(ctx, db); err != nil {
  113. return err
  114. }
  115. switch o.Status {
  116. case StatusInvalid:
  117. return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
  118. case StatusValid:
  119. return nil
  120. case StatusPending:
  121. return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
  122. case StatusReady:
  123. break
  124. default:
  125. return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
  126. }
  127. // canonicalize the CSR to allow for comparison
  128. csr = canonicalize(csr)
  129. // retrieve the requested SANs for the Order
  130. sans, err := o.sans(csr)
  131. if err != nil {
  132. return err
  133. }
  134. // Get authorizations from the ACME provisioner.
  135. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  136. signOps, err := p.AuthorizeSign(ctx, "")
  137. if err != nil {
  138. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  139. }
  140. // Template data
  141. data := x509util.NewTemplateData()
  142. data.SetCommonName(csr.Subject.CommonName)
  143. data.Set(x509util.SANsKey, sans)
  144. templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
  145. if err != nil {
  146. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  147. }
  148. signOps = append(signOps, templateOptions)
  149. // Sign a new certificate.
  150. certChain, err := auth.Sign(csr, provisioner.SignOptions{
  151. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  152. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  153. }, signOps...)
  154. if err != nil {
  155. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  156. }
  157. cert := &Certificate{
  158. AccountID: o.AccountID,
  159. OrderID: o.ID,
  160. Leaf: certChain[0],
  161. Intermediates: certChain[1:],
  162. }
  163. if err := db.CreateCertificate(ctx, cert); err != nil {
  164. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  165. }
  166. o.CertificateID = cert.ID
  167. o.Status = StatusValid
  168. if err = db.UpdateOrder(ctx, o); err != nil {
  169. return WrapErrorISE(err, "error updating order %s", o.ID)
  170. }
  171. return nil
  172. }
  173. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  174. var sans []x509util.SubjectAlternativeName
  175. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  176. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
  177. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  178. indexDNS, indexIP := 0, 0
  179. for _, n := range o.Identifiers {
  180. switch n.Type {
  181. case DNS:
  182. orderNames[indexDNS] = n.Value
  183. indexDNS++
  184. case IP:
  185. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  186. indexIP++
  187. default:
  188. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  189. }
  190. }
  191. orderNames = uniqueSortedLowerNames(orderNames)
  192. orderIPs = uniqueSortedIPs(orderIPs)
  193. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses)
  194. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  195. index := 0
  196. // Validate identifier names against CSR alternative names.
  197. //
  198. // Note that with certificate templates we are not going to check for the
  199. // absence of other SANs as they will only be set if the template allows
  200. // them.
  201. if len(csr.DNSNames) != len(orderNames) {
  202. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  203. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  204. }
  205. for i := range csr.DNSNames {
  206. if csr.DNSNames[i] != orderNames[i] {
  207. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  208. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  209. }
  210. sans[index] = x509util.SubjectAlternativeName{
  211. Type: x509util.DNSType,
  212. Value: csr.DNSNames[i],
  213. }
  214. index++
  215. }
  216. if len(csr.IPAddresses) != len(orderIPs) {
  217. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  218. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  219. }
  220. for i := range csr.IPAddresses {
  221. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  222. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  223. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  224. }
  225. sans[index] = x509util.SubjectAlternativeName{
  226. Type: x509util.IPType,
  227. Value: csr.IPAddresses[i].String(),
  228. }
  229. index++
  230. }
  231. return sans, nil
  232. }
  233. // numberOfIdentifierType returns the number of Identifiers that
  234. // are of type typ.
  235. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  236. c := 0
  237. for _, id := range ids {
  238. if id.Type == typ {
  239. c++
  240. }
  241. }
  242. return c
  243. }
  244. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  245. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  246. // but may not be expected.
  247. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  248. // for clarity only; we're operating on the same object by pointer
  249. canonicalized = csr
  250. // RFC8555: The CSR MUST indicate the exact same set of requested
  251. // identifiers as the initial newOrder request. Identifiers of type "dns"
  252. // MUST appear either in the commonName portion of the requested subject
  253. // name or in an extensionRequest attribute [RFC2985] requesting a
  254. // subjectAltName extension, or both.
  255. if csr.Subject.CommonName != "" {
  256. canonicalized.DNSNames = append(csr.DNSNames, csr.Subject.CommonName)
  257. }
  258. canonicalized.DNSNames = uniqueSortedLowerNames(csr.DNSNames)
  259. canonicalized.IPAddresses = uniqueSortedIPs(csr.IPAddresses)
  260. return canonicalized
  261. }
  262. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  263. // not considered equal. IPv6 representations of IPv4 addresses are
  264. // considered equal to the IPv4 address in this implementation, which is
  265. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  266. // is equal to "192.168.42.42". This is considered a known issue within
  267. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  268. func ipsAreEqual(x, y net.IP) bool {
  269. if x == nil || y == nil {
  270. return false
  271. }
  272. return x.Equal(y)
  273. }
  274. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  275. // of them are lowercased. The returned names will be in their lowercased form
  276. // and sorted alphabetically.
  277. func uniqueSortedLowerNames(names []string) (unique []string) {
  278. nameMap := make(map[string]int, len(names))
  279. for _, name := range names {
  280. nameMap[strings.ToLower(name)] = 1
  281. }
  282. unique = make([]string, 0, len(nameMap))
  283. for name := range nameMap {
  284. unique = append(unique, name)
  285. }
  286. sort.Strings(unique)
  287. return
  288. }
  289. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  290. // are sorted by their bytes (octet) representation.
  291. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  292. type entry struct {
  293. ip net.IP
  294. }
  295. ipEntryMap := make(map[string]entry, len(ips))
  296. for _, ip := range ips {
  297. ipEntryMap[ip.String()] = entry{ip: ip}
  298. }
  299. unique = make([]net.IP, 0, len(ipEntryMap))
  300. for _, entry := range ipEntryMap {
  301. unique = append(unique, entry.ip)
  302. }
  303. sort.Slice(unique, func(i, j int) bool {
  304. return bytes.Compare(unique[i], unique[j]) < 0
  305. })
  306. return
  307. }