order.go 11 KB

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