order.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. // the first (and only) Permanent Identifier that gets added to the certificate
  150. // should be equal to the Subject Common Name if it's set. If not equal, the CSR
  151. // is rejected, because the Common Name hasn't been challenged in that case. This
  152. // could result in unauthorized access if a relying system relies on the Common
  153. // Name in its authorization logic.
  154. if csr.Subject.CommonName != "" && csr.Subject.CommonName != permanentIdentifier {
  155. return NewError(ErrorBadCSRType, "CSR Subject Common Name does not match identifiers exactly: "+
  156. "CSR Subject Common Name = %s, Order Permanent Identifier = %s", csr.Subject.CommonName, permanentIdentifier)
  157. }
  158. break
  159. }
  160. }
  161. var defaultTemplate string
  162. if permanentIdentifier != "" {
  163. defaultTemplate = x509util.DefaultAttestedLeafTemplate
  164. data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
  165. Type: x509util.PermanentIdentifierType,
  166. Value: permanentIdentifier,
  167. })
  168. extraOptions = append(extraOptions, provisioner.AttestationData{
  169. PermanentIdentifier: permanentIdentifier,
  170. })
  171. } else {
  172. defaultTemplate = x509util.DefaultLeafTemplate
  173. sans, err := o.sans(csr)
  174. if err != nil {
  175. return err
  176. }
  177. data.SetSubjectAlternativeNames(sans...)
  178. }
  179. // Get authorizations from the ACME provisioner.
  180. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  181. signOps, err := p.AuthorizeSign(ctx, "")
  182. if err != nil {
  183. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  184. }
  185. // Unlike most of the provisioners, ACME's AuthorizeSign method doesn't
  186. // define the templates, and the template data used in WebHooks is not
  187. // available.
  188. for _, signOp := range signOps {
  189. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  190. wc.TemplateData = data
  191. }
  192. }
  193. templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
  194. if err != nil {
  195. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  196. }
  197. // Build extra signing options.
  198. signOps = append(signOps, templateOptions)
  199. signOps = append(signOps, extraOptions...)
  200. // Sign a new certificate.
  201. certChain, err := auth.Sign(csr, provisioner.SignOptions{
  202. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  203. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  204. }, signOps...)
  205. if err != nil {
  206. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  207. }
  208. cert := &Certificate{
  209. AccountID: o.AccountID,
  210. OrderID: o.ID,
  211. Leaf: certChain[0],
  212. Intermediates: certChain[1:],
  213. }
  214. if err := db.CreateCertificate(ctx, cert); err != nil {
  215. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  216. }
  217. o.CertificateID = cert.ID
  218. o.Status = StatusValid
  219. if err = db.UpdateOrder(ctx, o); err != nil {
  220. return WrapErrorISE(err, "error updating order %s", o.ID)
  221. }
  222. return nil
  223. }
  224. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  225. var sans []x509util.SubjectAlternativeName
  226. if len(csr.EmailAddresses) > 0 || len(csr.URIs) > 0 {
  227. return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
  228. }
  229. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  230. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers))
  231. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  232. orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
  233. indexDNS, indexIP, indexPID := 0, 0, 0
  234. for _, n := range o.Identifiers {
  235. switch n.Type {
  236. case DNS:
  237. orderNames[indexDNS] = n.Value
  238. indexDNS++
  239. case IP:
  240. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  241. indexIP++
  242. case PermanentIdentifier:
  243. orderPIDs[indexPID] = n.Value
  244. indexPID++
  245. default:
  246. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  247. }
  248. }
  249. orderNames = uniqueSortedLowerNames(orderNames)
  250. orderIPs = uniqueSortedIPs(orderIPs)
  251. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses)
  252. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  253. index := 0
  254. // Validate identifier names against CSR alternative names.
  255. //
  256. // Note that with certificate templates we are not going to check for the
  257. // absence of other SANs as they will only be set if the template allows
  258. // them.
  259. if len(csr.DNSNames) != len(orderNames) {
  260. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  261. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  262. }
  263. for i := range csr.DNSNames {
  264. if csr.DNSNames[i] != orderNames[i] {
  265. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  266. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  267. }
  268. sans[index] = x509util.SubjectAlternativeName{
  269. Type: x509util.DNSType,
  270. Value: csr.DNSNames[i],
  271. }
  272. index++
  273. }
  274. if len(csr.IPAddresses) != len(orderIPs) {
  275. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  276. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  277. }
  278. for i := range csr.IPAddresses {
  279. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  280. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  281. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  282. }
  283. sans[index] = x509util.SubjectAlternativeName{
  284. Type: x509util.IPType,
  285. Value: csr.IPAddresses[i].String(),
  286. }
  287. index++
  288. }
  289. return sans, nil
  290. }
  291. // numberOfIdentifierType returns the number of Identifiers that
  292. // are of type typ.
  293. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  294. c := 0
  295. for _, id := range ids {
  296. if id.Type == typ {
  297. c++
  298. }
  299. }
  300. return c
  301. }
  302. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  303. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  304. // but may not be expected. It also adds a Subject Common Name to either the IP
  305. // addresses or DNS names slice, depending on whether it can be parsed as an IP
  306. // or not. This might result in an additional SAN in the final certificate.
  307. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  308. // for clarity only; we're operating on the same object by pointer
  309. canonicalized = csr
  310. // RFC8555: The CSR MUST indicate the exact same set of requested
  311. // identifiers as the initial newOrder request. Identifiers of type "dns"
  312. // MUST appear either in the commonName portion of the requested subject
  313. // name or in an extensionRequest attribute [RFC2985] requesting a
  314. // subjectAltName extension, or both. Subject Common Names that can be
  315. // parsed as an IP are included as an IP address for the equality check.
  316. // If these were excluded, a certificate could contain an IP as the
  317. // common name without having been challenged.
  318. if csr.Subject.CommonName != "" {
  319. if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
  320. canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
  321. } else {
  322. canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
  323. }
  324. }
  325. canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
  326. canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
  327. return canonicalized
  328. }
  329. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  330. // not considered equal. IPv6 representations of IPv4 addresses are
  331. // considered equal to the IPv4 address in this implementation, which is
  332. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  333. // is equal to "192.168.42.42". This is considered a known issue within
  334. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  335. func ipsAreEqual(x, y net.IP) bool {
  336. if x == nil || y == nil {
  337. return false
  338. }
  339. return x.Equal(y)
  340. }
  341. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  342. // of them are lowercased. The returned names will be in their lowercased form
  343. // and sorted alphabetically.
  344. func uniqueSortedLowerNames(names []string) (unique []string) {
  345. nameMap := make(map[string]int, len(names))
  346. for _, name := range names {
  347. nameMap[strings.ToLower(name)] = 1
  348. }
  349. unique = make([]string, 0, len(nameMap))
  350. for name := range nameMap {
  351. unique = append(unique, name)
  352. }
  353. sort.Strings(unique)
  354. return
  355. }
  356. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  357. // are sorted by their bytes (octet) representation.
  358. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  359. type entry struct {
  360. ip net.IP
  361. }
  362. ipEntryMap := make(map[string]entry, len(ips))
  363. for _, ip := range ips {
  364. // reparsing the IP results in the IP being represented using 16 bytes
  365. // for both IPv4 as well as IPv6, even when the ips slice contains IPs that
  366. // are represented by 4 bytes. This ensures a fair comparison and thus ordering.
  367. ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
  368. }
  369. unique = make([]net.IP, 0, len(ipEntryMap))
  370. for _, entry := range ipEntryMap {
  371. unique = append(unique, entry.ip)
  372. }
  373. sort.Slice(unique, func(i, j int) bool {
  374. return bytes.Compare(unique[i], unique[j]) < 0
  375. })
  376. return
  377. }