order.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/json"
  9. "fmt"
  10. "net"
  11. "net/url"
  12. "sort"
  13. "strings"
  14. "time"
  15. "go.step.sm/crypto/keyutil"
  16. "go.step.sm/crypto/x509util"
  17. "github.com/smallstep/certificates/acme/wire"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. )
  20. type IdentifierType string
  21. const (
  22. // IP is the ACME ip identifier type
  23. IP IdentifierType = "ip"
  24. // DNS is the ACME dns identifier type
  25. DNS IdentifierType = "dns"
  26. // PermanentIdentifier is the ACME permanent-identifier identifier type
  27. // defined in https://datatracker.ietf.org/doc/html/draft-bweeks-acme-device-attest-00
  28. PermanentIdentifier IdentifierType = "permanent-identifier"
  29. // WireID is the Wire user identifier type
  30. WireID IdentifierType = "wireapp-id"
  31. )
  32. // Identifier encodes the type that an order pertains to.
  33. type Identifier struct {
  34. Type IdentifierType `json:"type"`
  35. Value string `json:"value"`
  36. }
  37. // Order contains order metadata for the ACME protocol order type.
  38. type Order struct {
  39. ID string `json:"id"`
  40. AccountID string `json:"-"`
  41. ProvisionerID string `json:"-"`
  42. Status Status `json:"status"`
  43. ExpiresAt time.Time `json:"expires"`
  44. Identifiers []Identifier `json:"identifiers"`
  45. NotBefore time.Time `json:"notBefore"`
  46. NotAfter time.Time `json:"notAfter"`
  47. Error *Error `json:"error,omitempty"`
  48. AuthorizationIDs []string `json:"-"`
  49. AuthorizationURLs []string `json:"authorizations"`
  50. FinalizeURL string `json:"finalize"`
  51. CertificateID string `json:"-"`
  52. CertificateURL string `json:"certificate,omitempty"`
  53. }
  54. // ToLog enables response logging.
  55. func (o *Order) ToLog() (interface{}, error) {
  56. b, err := json.Marshal(o)
  57. if err != nil {
  58. return nil, WrapErrorISE(err, "error marshaling order for logging")
  59. }
  60. return string(b), nil
  61. }
  62. // UpdateStatus updates the ACME Order Status if necessary.
  63. // Changes to the order are saved using the database interface.
  64. func (o *Order) UpdateStatus(ctx context.Context, db DB) error {
  65. now := clock.Now()
  66. switch o.Status {
  67. case StatusInvalid:
  68. return nil
  69. case StatusValid:
  70. return nil
  71. case StatusReady:
  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. return nil
  79. case StatusPending:
  80. // Check expiry
  81. if now.After(o.ExpiresAt) {
  82. o.Status = StatusInvalid
  83. o.Error = NewError(ErrorMalformedType, "order has expired")
  84. break
  85. }
  86. var count = map[Status]int{
  87. StatusValid: 0,
  88. StatusInvalid: 0,
  89. StatusPending: 0,
  90. }
  91. for _, azID := range o.AuthorizationIDs {
  92. az, err := db.GetAuthorization(ctx, azID)
  93. if err != nil {
  94. return WrapErrorISE(err, "error getting authorization ID %s", azID)
  95. }
  96. if err = az.UpdateStatus(ctx, db); err != nil {
  97. return WrapErrorISE(err, "error updating authorization ID %s", azID)
  98. }
  99. st := az.Status
  100. count[st]++
  101. }
  102. switch {
  103. case count[StatusInvalid] > 0:
  104. o.Status = StatusInvalid
  105. // No change in the order status, so just return the order as is -
  106. // without writing any changes.
  107. case count[StatusPending] > 0:
  108. return nil
  109. case count[StatusValid] == len(o.AuthorizationIDs):
  110. o.Status = StatusReady
  111. default:
  112. return NewErrorISE("unexpected authz status")
  113. }
  114. default:
  115. return NewErrorISE("unrecognized order status: %s", o.Status)
  116. }
  117. if err := db.UpdateOrder(ctx, o); err != nil {
  118. return WrapErrorISE(err, "error updating order")
  119. }
  120. return nil
  121. }
  122. // getKeyFingerprint returns a fingerprint from the list of authorizations. This
  123. // fingerprint is used on the device-attest-01 flow to verify the attestation
  124. // certificate public key with the CSR public key.
  125. //
  126. // There's no point on reading all the authorizations as there will be only one
  127. // for a permanent identifier.
  128. func (o *Order) getAuthorizationFingerprint(ctx context.Context, db DB) (string, error) {
  129. for _, azID := range o.AuthorizationIDs {
  130. az, err := db.GetAuthorization(ctx, azID)
  131. if err != nil {
  132. return "", WrapErrorISE(err, "error getting authorization %q", azID)
  133. }
  134. // There's no point on reading all the authorizations as there will
  135. // be only one for a permanent identifier.
  136. if az.Fingerprint != "" {
  137. return az.Fingerprint, nil
  138. }
  139. }
  140. return "", nil
  141. }
  142. // Finalize signs a certificate if the necessary conditions for Order completion
  143. // have been met.
  144. //
  145. // TODO(mariano): Here or in the challenge validation we should perform some
  146. // external validation using the identifier value and the attestation data. From
  147. // a validation service we can get the list of SANs to set in the final
  148. // certificate.
  149. func (o *Order) Finalize(ctx context.Context, db DB, csr *x509.CertificateRequest, auth CertificateAuthority, p Provisioner) error {
  150. if err := o.UpdateStatus(ctx, db); err != nil {
  151. return err
  152. }
  153. switch o.Status {
  154. case StatusInvalid:
  155. return NewError(ErrorOrderNotReadyType, "order %s has been abandoned", o.ID)
  156. case StatusValid:
  157. return nil
  158. case StatusPending:
  159. return NewError(ErrorOrderNotReadyType, "order %s is not ready", o.ID)
  160. case StatusReady:
  161. break
  162. default:
  163. return NewErrorISE("unexpected status %s for order %s", o.Status, o.ID)
  164. }
  165. // Get key fingerprint if any. And then compare it with the CSR fingerprint.
  166. //
  167. // In device-attest-01 challenges we should check that the keys in the CSR
  168. // and the attestation certificate are the same.
  169. fingerprint, err := o.getAuthorizationFingerprint(ctx, db)
  170. if err != nil {
  171. return err
  172. }
  173. if fingerprint != "" {
  174. fp, err := keyutil.Fingerprint(csr.PublicKey)
  175. if err != nil {
  176. return WrapErrorISE(err, "error calculating key fingerprint")
  177. }
  178. if subtle.ConstantTimeCompare([]byte(fingerprint), []byte(fp)) == 0 {
  179. return NewError(ErrorUnauthorizedType, "order %s csr does not match the attested key", o.ID)
  180. }
  181. }
  182. // canonicalize the CSR to allow for comparison
  183. csr = canonicalize(csr)
  184. // Template data
  185. data := x509util.NewTemplateData()
  186. if o.containsWireIdentifiers() {
  187. subject, err := createWireSubject(o, csr)
  188. if err != nil {
  189. return fmt.Errorf("failed creating Wire subject: %w", err)
  190. }
  191. data.SetSubject(subject)
  192. // Inject Wire's custom challenges into the template once they have been validated
  193. dpop, err := db.GetDpopToken(ctx, o.ID)
  194. if err != nil {
  195. return fmt.Errorf("failed getting Wire DPoP token: %w", err)
  196. }
  197. data.Set("Dpop", dpop)
  198. oidc, err := db.GetOidcToken(ctx, o.ID)
  199. if err != nil {
  200. return fmt.Errorf("failed getting Wire OIDC token: %w", err)
  201. }
  202. data.Set("Oidc", oidc)
  203. } else {
  204. data.SetCommonName(csr.Subject.CommonName)
  205. }
  206. // Custom sign options passed to authority.Sign
  207. var extraOptions []provisioner.SignOption
  208. // TODO: support for multiple identifiers?
  209. var permanentIdentifier string
  210. for i := range o.Identifiers {
  211. if o.Identifiers[i].Type == PermanentIdentifier {
  212. permanentIdentifier = o.Identifiers[i].Value
  213. // the first (and only) Permanent Identifier that gets added to the certificate
  214. // should be equal to the Subject Common Name if it's set. If not equal, the CSR
  215. // is rejected, because the Common Name hasn't been challenged in that case. This
  216. // could result in unauthorized access if a relying system relies on the Common
  217. // Name in its authorization logic.
  218. if csr.Subject.CommonName != "" && csr.Subject.CommonName != permanentIdentifier {
  219. return NewError(ErrorBadCSRType, "CSR Subject Common Name does not match identifiers exactly: "+
  220. "CSR Subject Common Name = %s, Order Permanent Identifier = %s", csr.Subject.CommonName, permanentIdentifier)
  221. }
  222. break
  223. }
  224. }
  225. var defaultTemplate string
  226. if permanentIdentifier != "" {
  227. defaultTemplate = x509util.DefaultAttestedLeafTemplate
  228. data.SetSubjectAlternativeNames(x509util.SubjectAlternativeName{
  229. Type: x509util.PermanentIdentifierType,
  230. Value: permanentIdentifier,
  231. })
  232. extraOptions = append(extraOptions, provisioner.AttestationData{
  233. PermanentIdentifier: permanentIdentifier,
  234. })
  235. } else {
  236. defaultTemplate = x509util.DefaultLeafTemplate
  237. sans, err := o.sans(csr)
  238. if err != nil {
  239. return err
  240. }
  241. data.SetSubjectAlternativeNames(sans...)
  242. }
  243. // Get authorizations from the ACME provisioner.
  244. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  245. signOps, err := p.AuthorizeSign(ctx, "")
  246. if err != nil {
  247. return WrapErrorISE(err, "error retrieving authorization options from ACME provisioner")
  248. }
  249. // Unlike most of the provisioners, ACME's AuthorizeSign method doesn't
  250. // define the templates, and the template data used in WebHooks is not
  251. // available.
  252. for _, signOp := range signOps {
  253. if wc, ok := signOp.(*provisioner.WebhookController); ok {
  254. wc.TemplateData = data
  255. }
  256. }
  257. templateOptions, err := provisioner.CustomTemplateOptions(p.GetOptions(), data, defaultTemplate)
  258. if err != nil {
  259. return WrapErrorISE(err, "error creating template options from ACME provisioner")
  260. }
  261. // Build extra signing options.
  262. signOps = append(signOps, templateOptions)
  263. signOps = append(signOps, extraOptions...)
  264. // Sign a new certificate.
  265. certChain, err := auth.Sign(csr, provisioner.SignOptions{
  266. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  267. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  268. }, signOps...)
  269. if err != nil {
  270. return WrapErrorISE(err, "error signing certificate for order %s", o.ID)
  271. }
  272. cert := &Certificate{
  273. AccountID: o.AccountID,
  274. OrderID: o.ID,
  275. Leaf: certChain[0],
  276. Intermediates: certChain[1:],
  277. }
  278. if err := db.CreateCertificate(ctx, cert); err != nil {
  279. return WrapErrorISE(err, "error creating certificate for order %s", o.ID)
  280. }
  281. o.CertificateID = cert.ID
  282. o.Status = StatusValid
  283. if err = db.UpdateOrder(ctx, o); err != nil {
  284. return WrapErrorISE(err, "error updating order %s", o.ID)
  285. }
  286. return nil
  287. }
  288. // containsWireIdentifiers checks if [Order] contains ACME
  289. // identifiers for the WireID type.
  290. func (o *Order) containsWireIdentifiers() bool {
  291. for _, i := range o.Identifiers {
  292. if i.Type == WireID {
  293. return true
  294. }
  295. }
  296. return false
  297. }
  298. // createWireSubject creates the subject for an [Order] with WireID identifiers.
  299. func createWireSubject(o *Order, csr *x509.CertificateRequest) (subject x509util.Subject, err error) {
  300. wireIDs, otherIDs := 0, 0
  301. for _, identifier := range o.Identifiers {
  302. switch identifier.Type {
  303. case WireID:
  304. wireID, err := wire.ParseID([]byte(identifier.Value))
  305. if err != nil {
  306. return subject, NewErrorISE("unmarshal wireID: %s", err)
  307. }
  308. // TODO: temporarily using a custom OIDC for carrying the display name without having it listed as a DNS SAN.
  309. // reusing LDAP's OID for diplay name see http://oid-info.com/get/2.16.840.1.113730.3.1.241
  310. displayNameOid := asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 3, 1, 241}
  311. var foundDisplayName = false
  312. for _, entry := range csr.Subject.Names {
  313. if entry.Type.Equal(displayNameOid) {
  314. foundDisplayName = true
  315. displayName := entry.Value.(string)
  316. if displayName != wireID.Name {
  317. return subject, NewErrorISE("expected displayName %v, found %v", wireID.Name, displayName)
  318. }
  319. }
  320. }
  321. if !foundDisplayName {
  322. return subject, NewErrorISE("CSR must contain the display name in 2.16.840.1.113730.3.1.241 OID")
  323. }
  324. if len(csr.Subject.Organization) == 0 || !strings.EqualFold(csr.Subject.Organization[0], wireID.Domain) {
  325. return subject, NewErrorISE("expected Organization [%s], found %v", wireID.Domain, csr.Subject.Organization)
  326. }
  327. subject.CommonName = wireID.Name
  328. subject.Organization = []string{wireID.Domain}
  329. wireIDs++
  330. default:
  331. otherIDs++
  332. }
  333. }
  334. if wireIDs > 0 && otherIDs > 0 || wireIDs > 1 {
  335. return subject, NewErrorISE("at most one WireID can be signed along with no other ID, found %d WireIDs and %d other IDs", wireIDs, otherIDs)
  336. }
  337. return
  338. }
  339. func (o *Order) sans(csr *x509.CertificateRequest) ([]x509util.SubjectAlternativeName, error) {
  340. var sans []x509util.SubjectAlternativeName
  341. if len(csr.EmailAddresses) > 0 {
  342. return sans, NewError(ErrorBadCSRType, "Only DNS names and IP addresses are allowed")
  343. }
  344. // order the DNS names and IP addresses, so that they can be compared against the canonicalized CSR
  345. orderNames := make([]string, numberOfIdentifierType(DNS, o.Identifiers)+2*numberOfIdentifierType(WireID, o.Identifiers))
  346. orderIPs := make([]net.IP, numberOfIdentifierType(IP, o.Identifiers))
  347. orderPIDs := make([]string, numberOfIdentifierType(PermanentIdentifier, o.Identifiers))
  348. tmpOrderURIs := make([]*url.URL, 2*numberOfIdentifierType(WireID, o.Identifiers))
  349. indexDNS, indexIP, indexPID, indexURI := 0, 0, 0, 0
  350. for _, n := range o.Identifiers {
  351. switch n.Type {
  352. case DNS:
  353. orderNames[indexDNS] = n.Value
  354. indexDNS++
  355. case IP:
  356. orderIPs[indexIP] = net.ParseIP(n.Value) // NOTE: this assumes are all valid IPs at this time; or will result in nil entries
  357. indexIP++
  358. case PermanentIdentifier:
  359. orderPIDs[indexPID] = n.Value
  360. indexPID++
  361. case WireID:
  362. wireID, err := wire.ParseID([]byte(n.Value))
  363. if err != nil {
  364. return sans, NewErrorISE("unsupported identifier value in order: %s", n.Value)
  365. }
  366. clientID, err := url.Parse(wireID.ClientID)
  367. if err != nil {
  368. return sans, NewErrorISE("clientId must be a URI: %s", wireID.ClientID)
  369. }
  370. tmpOrderURIs[indexURI] = clientID
  371. indexURI++
  372. handle, err := url.Parse(wireID.Handle)
  373. if err != nil {
  374. return sans, NewErrorISE("handle must be a URI: %s", wireID.Handle)
  375. }
  376. tmpOrderURIs[indexURI] = handle
  377. indexURI++
  378. default:
  379. return sans, NewErrorISE("unsupported identifier type in order: %s", n.Type)
  380. }
  381. }
  382. orderNames = uniqueSortedLowerNames(orderNames)
  383. orderIPs = uniqueSortedIPs(orderIPs)
  384. orderURIs := uniqueSortedURIStrings(tmpOrderURIs)
  385. totalNumberOfSANs := len(csr.DNSNames) + len(csr.IPAddresses) + len(csr.URIs)
  386. sans = make([]x509util.SubjectAlternativeName, totalNumberOfSANs)
  387. index := 0
  388. // Validate identifier names against CSR alternative names.
  389. //
  390. // Note that with certificate templates we are not going to check for the
  391. // absence of other SANs as they will only be set if the template allows
  392. // them.
  393. if len(csr.DNSNames) != len(orderNames) {
  394. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  395. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  396. }
  397. for i := range csr.DNSNames {
  398. if csr.DNSNames[i] != orderNames[i] {
  399. return sans, NewError(ErrorBadCSRType, "CSR names do not match identifiers exactly: "+
  400. "CSR names = %v, Order names = %v", csr.DNSNames, orderNames)
  401. }
  402. sans[index] = x509util.SubjectAlternativeName{
  403. Type: x509util.DNSType,
  404. Value: csr.DNSNames[i],
  405. }
  406. index++
  407. }
  408. if len(csr.IPAddresses) != len(orderIPs) {
  409. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  410. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  411. }
  412. for i := range csr.IPAddresses {
  413. if !ipsAreEqual(csr.IPAddresses[i], orderIPs[i]) {
  414. return sans, NewError(ErrorBadCSRType, "CSR IPs do not match identifiers exactly: "+
  415. "CSR IPs = %v, Order IPs = %v", csr.IPAddresses, orderIPs)
  416. }
  417. sans[index] = x509util.SubjectAlternativeName{
  418. Type: x509util.IPType,
  419. Value: csr.IPAddresses[i].String(),
  420. }
  421. index++
  422. }
  423. if len(csr.URIs) != len(tmpOrderURIs) {
  424. return sans, NewError(ErrorBadCSRType, "CSR URIs do not match identifiers exactly: "+
  425. "CSR URIs = %v, Order URIs = %v", csr.URIs, tmpOrderURIs)
  426. }
  427. // sort URI list
  428. csrURIs := uniqueSortedURIStrings(csr.URIs)
  429. for i := range csrURIs {
  430. if csrURIs[i] != orderURIs[i] {
  431. return sans, NewError(ErrorBadCSRType, "CSR URIs do not match identifiers exactly: "+
  432. "CSR URIs = %v, Order URIs = %v", csr.URIs, tmpOrderURIs)
  433. }
  434. sans[index] = x509util.SubjectAlternativeName{
  435. Type: x509util.URIType,
  436. Value: orderURIs[i],
  437. }
  438. index++
  439. }
  440. return sans, nil
  441. }
  442. // numberOfIdentifierType returns the number of Identifiers that
  443. // are of type typ.
  444. func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int {
  445. c := 0
  446. for _, id := range ids {
  447. if id.Type == typ {
  448. c++
  449. }
  450. }
  451. return c
  452. }
  453. // canonicalize canonicalizes a CSR so that it can be compared against an Order
  454. // NOTE: this effectively changes the order of SANs in the CSR, which may be OK,
  455. // but may not be expected. It also adds a Subject Common Name to either the IP
  456. // addresses or DNS names slice, depending on whether it can be parsed as an IP
  457. // or not. This might result in an additional SAN in the final certificate.
  458. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) {
  459. // for clarity only; we're operating on the same object by pointer
  460. canonicalized = csr
  461. // RFC8555: The CSR MUST indicate the exact same set of requested
  462. // identifiers as the initial newOrder request. Identifiers of type "dns"
  463. // MUST appear either in the commonName portion of the requested subject
  464. // name or in an extensionRequest attribute [RFC2985] requesting a
  465. // subjectAltName extension, or both. Subject Common Names that can be
  466. // parsed as an IP are included as an IP address for the equality check.
  467. // If these were excluded, a certificate could contain an IP as the
  468. // common name without having been challenged.
  469. if csr.Subject.CommonName != "" {
  470. if ip := net.ParseIP(csr.Subject.CommonName); ip != nil {
  471. canonicalized.IPAddresses = append(canonicalized.IPAddresses, ip)
  472. } else {
  473. canonicalized.DNSNames = append(canonicalized.DNSNames, csr.Subject.CommonName)
  474. }
  475. }
  476. canonicalized.DNSNames = uniqueSortedLowerNames(canonicalized.DNSNames)
  477. canonicalized.IPAddresses = uniqueSortedIPs(canonicalized.IPAddresses)
  478. return canonicalized
  479. }
  480. // ipsAreEqual compares IPs to be equal. Nil values (i.e. invalid IPs) are
  481. // not considered equal. IPv6 representations of IPv4 addresses are
  482. // considered equal to the IPv4 address in this implementation, which is
  483. // standard Go behavior. An example is "::ffff:192.168.42.42", which
  484. // is equal to "192.168.42.42". This is considered a known issue within
  485. // step and is tracked here too: https://github.com/golang/go/issues/37921.
  486. func ipsAreEqual(x, y net.IP) bool {
  487. if x == nil || y == nil {
  488. return false
  489. }
  490. return x.Equal(y)
  491. }
  492. // uniqueSortedLowerNames returns the set of all unique names in the input after all
  493. // of them are lowercased. The returned names will be in their lowercased form
  494. // and sorted alphabetically.
  495. func uniqueSortedLowerNames(names []string) (unique []string) {
  496. nameMap := make(map[string]int, len(names))
  497. for _, name := range names {
  498. nameMap[strings.ToLower(name)] = 1
  499. }
  500. unique = make([]string, 0, len(nameMap))
  501. for name := range nameMap {
  502. if len(name) > 0 {
  503. unique = append(unique, name)
  504. }
  505. }
  506. sort.Strings(unique)
  507. return
  508. }
  509. func uniqueSortedURIStrings(uris []*url.URL) (unique []string) {
  510. uriMap := make(map[string]struct{}, len(uris))
  511. for _, name := range uris {
  512. uriMap[name.String()] = struct{}{}
  513. }
  514. unique = make([]string, 0, len(uriMap))
  515. for name := range uriMap {
  516. unique = append(unique, name)
  517. }
  518. sort.Strings(unique)
  519. return
  520. }
  521. // uniqueSortedIPs returns the set of all unique net.IPs in the input. They
  522. // are sorted by their bytes (octet) representation.
  523. func uniqueSortedIPs(ips []net.IP) (unique []net.IP) {
  524. type entry struct {
  525. ip net.IP
  526. }
  527. ipEntryMap := make(map[string]entry, len(ips))
  528. for _, ip := range ips {
  529. // reparsing the IP results in the IP being represented using 16 bytes
  530. // for both IPv4 as well as IPv6, even when the ips slice contains IPs that
  531. // are represented by 4 bytes. This ensures a fair comparison and thus ordering.
  532. ipEntryMap[ip.String()] = entry{ip: net.ParseIP(ip.String())}
  533. }
  534. unique = make([]net.IP, 0, len(ipEntryMap))
  535. for _, entry := range ipEntryMap {
  536. unique = append(unique, entry.ip)
  537. }
  538. sort.Slice(unique, func(i, j int) bool {
  539. return bytes.Compare(unique[i], unique[j]) < 0
  540. })
  541. return
  542. }