order.go 13 KB

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