order.go 23 KB

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