challenge.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/sha256"
  7. "crypto/subtle"
  8. "crypto/tls"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "encoding/json"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "net"
  18. "net/url"
  19. "reflect"
  20. "slices"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/coreos/go-oidc/v3/oidc"
  25. "github.com/fxamacker/cbor/v2"
  26. "go.step.sm/crypto/jose"
  27. "github.com/smallstep/certificates/acme/wire"
  28. "github.com/smallstep/certificates/attestation"
  29. "github.com/smallstep/certificates/attestation/androidkey"
  30. "github.com/smallstep/certificates/attestation/apple"
  31. "github.com/smallstep/certificates/attestation/tpm"
  32. "github.com/smallstep/certificates/attestation/yubikey"
  33. "github.com/smallstep/certificates/authority/provisioner"
  34. wireprovisioner "github.com/smallstep/certificates/authority/provisioner/wire"
  35. "github.com/smallstep/certificates/internal/cast"
  36. )
  37. type ChallengeType string
  38. const (
  39. // HTTP01 is the http-01 ACME challenge type
  40. HTTP01 ChallengeType = "http-01"
  41. // DNS01 is the dns-01 ACME challenge type
  42. DNS01 ChallengeType = "dns-01"
  43. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  44. TLSALPN01 ChallengeType = "tls-alpn-01"
  45. // DEVICEATTEST01 is the device-attest-01 ACME challenge type
  46. DEVICEATTEST01 ChallengeType = "device-attest-01"
  47. // WIREOIDC01 is the Wire OIDC challenge type
  48. WIREOIDC01 ChallengeType = "wire-oidc-01"
  49. // WIREDPOP01 is the Wire DPoP challenge type
  50. WIREDPOP01 ChallengeType = "wire-dpop-01"
  51. // REMOTEATTEST01 is the remote-attest-01 ACME challenge type defined in
  52. // https://datatracker.ietf.org/doc/html/draft-ietf-acme-rats-03
  53. REMOTEATTEST01 ChallengeType = "remote-attest-01"
  54. )
  55. var (
  56. // InsecurePortHTTP01 is the port used to verify http-01 challenges. If not set it
  57. // defaults to 80.
  58. InsecurePortHTTP01 int
  59. // InsecurePortTLSALPN01 is the port used to verify tls-alpn-01 challenges. If not
  60. // set it defaults to 443.
  61. //
  62. // This variable can be used for testing purposes.
  63. InsecurePortTLSALPN01 int
  64. // StrictFQDN allows to enforce a fully qualified domain name in the DNS
  65. // resolution. By default it allows domain resolution using a search list
  66. // defined in the resolv.conf or similar configuration.
  67. StrictFQDN bool
  68. )
  69. // Challenge represents an ACME response Challenge type.
  70. type Challenge struct {
  71. ID string `json:"-"`
  72. AccountID string `json:"-"`
  73. AuthorizationID string `json:"-"`
  74. Value string `json:"-"`
  75. Type ChallengeType `json:"type"`
  76. Status Status `json:"status"`
  77. Token string `json:"token"`
  78. ValidatedAt string `json:"validated,omitempty"`
  79. URL string `json:"url"`
  80. Target string `json:"target,omitempty"`
  81. // FreshnessNonce is the nonce the evidence of a remote-attest-01
  82. // challenge must include, through its key authorization.
  83. FreshnessNonce string `json:"freshnessNonce,omitempty"`
  84. // AttestClaimsHint names the claims a remote-attest-01 challenge asks
  85. // for.
  86. AttestClaimsHint []string `json:"attestClaimsHint,omitempty"`
  87. Error *Error `json:"error,omitempty"`
  88. Payload []byte `json:"-"`
  89. PayloadFormat string `json:"-"`
  90. }
  91. // ToLog enables response logging.
  92. func (ch *Challenge) ToLog() (any, error) {
  93. b, err := json.Marshal(ch)
  94. if err != nil {
  95. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  96. }
  97. return string(b), nil
  98. }
  99. // Validate attempts to validate the Challenge. Stores changes to the Challenge
  100. // type using the DB interface. If the Challenge is validated, the 'status' and
  101. // 'validated' attributes are updated.
  102. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  103. // If already valid or invalid then return without performing validation.
  104. if ch.Status != StatusPending {
  105. return nil
  106. }
  107. switch ch.Type {
  108. case HTTP01:
  109. return http01Validate(ctx, ch, db, jwk)
  110. case DNS01:
  111. return dns01Validate(ctx, ch, db, jwk)
  112. case TLSALPN01:
  113. return tlsalpn01Validate(ctx, ch, db, jwk)
  114. case DEVICEATTEST01:
  115. return deviceAttest01Validate(ctx, ch, db, jwk, payload)
  116. case WIREOIDC01:
  117. wireDB, ok := db.(WireDB)
  118. if !ok {
  119. return NewErrorISE("db %T is not a WireDB", db)
  120. }
  121. return wireOIDC01Validate(ctx, ch, wireDB, jwk, payload)
  122. case WIREDPOP01:
  123. wireDB, ok := db.(WireDB)
  124. if !ok {
  125. return NewErrorISE("db %T is not a WireDB", db)
  126. }
  127. return wireDPOP01Validate(ctx, ch, wireDB, jwk, payload)
  128. case REMOTEATTEST01:
  129. return remoteAttest01Validate(ctx, ch, db, jwk, payload)
  130. default:
  131. return NewErrorISE("unexpected challenge type %q", ch.Type)
  132. }
  133. }
  134. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  135. u := &url.URL{Scheme: "http", Host: ch.Value, Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  136. challengeURL := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  137. // Append insecure port if set.
  138. // Only used for testing purposes.
  139. if InsecurePortHTTP01 != 0 {
  140. insecurePort := strconv.Itoa(InsecurePortHTTP01)
  141. u.Host += ":" + insecurePort
  142. challengeURL.Host += ":" + insecurePort
  143. }
  144. vc := MustClientFromContext(ctx)
  145. resp, err := vc.Get(challengeURL.String())
  146. if err != nil {
  147. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  148. "error doing http GET for url %s", u))
  149. }
  150. defer resp.Body.Close()
  151. if resp.StatusCode >= 400 {
  152. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  153. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  154. }
  155. body, err := io.ReadAll(resp.Body)
  156. if err != nil {
  157. return WrapErrorISE(err, "error reading "+
  158. "response body for url %s", u)
  159. }
  160. keyAuth := strings.TrimSpace(string(body))
  161. expected, err := KeyAuthorization(ch.Token, jwk)
  162. if err != nil {
  163. return err
  164. }
  165. if keyAuth != expected {
  166. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  167. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  168. }
  169. // Update and store the challenge.
  170. ch.Status = StatusValid
  171. ch.Error = nil
  172. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  173. if err = db.UpdateChallenge(ctx, ch); err != nil {
  174. return WrapErrorISE(err, "error updating challenge")
  175. }
  176. return nil
  177. }
  178. // rootedName adds a trailing "." to a given domain name.
  179. func rootedName(name string) string {
  180. if StrictFQDN {
  181. if name == "" || name[len(name)-1] != '.' {
  182. return name + "."
  183. }
  184. }
  185. return name
  186. }
  187. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  188. // and adds square brackets if that's the case, so that it can be used
  189. // as a hostname. Returns the original Challenge value as the host to
  190. // use in other cases.
  191. func http01ChallengeHost(value string) string {
  192. if ip := net.ParseIP(value); ip != nil {
  193. if ip.To4() == nil {
  194. value = "[" + value + "]"
  195. }
  196. return value
  197. }
  198. return rootedName(value)
  199. }
  200. // tlsAlpn01ChallengeHost returns the rooted DNS used on TLS-ALPN-01
  201. // validations.
  202. func tlsAlpn01ChallengeHost(name string) string {
  203. if ip := net.ParseIP(name); ip != nil {
  204. return name
  205. }
  206. return rootedName(name)
  207. }
  208. // dns01ChallengeHost returns the TXT record used in DNS-01 validations.
  209. func dns01ChallengeHost(domain string) string {
  210. return "_acme-challenge." + rootedName(domain)
  211. }
  212. func tlsAlert(err error) uint8 {
  213. if opErr, ok := errors.AsType[*net.OpError](err); ok {
  214. v := reflect.ValueOf(opErr.Err)
  215. if v.Kind() == reflect.Uint8 {
  216. return cast.Uint8(v.Uint())
  217. }
  218. }
  219. return 0
  220. }
  221. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  222. config := &tls.Config{
  223. NextProtos: []string{"acme-tls/1"},
  224. // https://tools.ietf.org/html/rfc8737#section-4
  225. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  226. // [RFC5246] or higher when connecting to clients for validation.
  227. MinVersion: tls.VersionTLS12,
  228. ServerName: serverName(ch),
  229. InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate
  230. }
  231. // Allow to change TLS port for testing purposes.
  232. hostPort := tlsAlpn01ChallengeHost(ch.Value)
  233. if port := InsecurePortTLSALPN01; port == 0 {
  234. hostPort = net.JoinHostPort(hostPort, "443")
  235. } else {
  236. hostPort = net.JoinHostPort(hostPort, strconv.Itoa(port))
  237. }
  238. vc := MustClientFromContext(ctx)
  239. conn, err := vc.TLSDial("tcp", hostPort, config)
  240. if err != nil {
  241. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  242. // client and server protocols. When this happens the connection is
  243. // closed with the error no_application_protocol(120) as required by
  244. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  245. if tlsAlert(err) == 120 {
  246. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  247. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  248. }
  249. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  250. "error doing TLS dial for %s", ch.Value))
  251. }
  252. defer conn.Close()
  253. cs := conn.ConnectionState()
  254. certs := cs.PeerCertificates
  255. if len(certs) == 0 {
  256. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  257. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  258. }
  259. if cs.NegotiatedProtocol != "acme-tls/1" {
  260. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  261. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  262. }
  263. leafCert := certs[0]
  264. // if no DNS names present, look for IP address and verify that exactly one exists
  265. if len(leafCert.DNSNames) == 0 {
  266. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  267. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  268. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  269. }
  270. } else {
  271. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], ch.Value) {
  272. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  273. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  274. }
  275. }
  276. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  277. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  278. foundIDPeAcmeIdentifierV1Obsolete := false
  279. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  280. if err != nil {
  281. return err
  282. }
  283. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  284. for _, ext := range leafCert.Extensions {
  285. if idPeAcmeIdentifier.Equal(ext.Id) {
  286. if !ext.Critical {
  287. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  288. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  289. }
  290. var extValue []byte
  291. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  292. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  293. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  294. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  295. }
  296. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  297. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  298. "incorrect certificate for tls-alpn-01 challenge: "+
  299. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  300. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  301. }
  302. ch.Status = StatusValid
  303. ch.Error = nil
  304. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  305. if err = db.UpdateChallenge(ctx, ch); err != nil {
  306. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  307. }
  308. return nil
  309. }
  310. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  311. foundIDPeAcmeIdentifierV1Obsolete = true
  312. }
  313. }
  314. if foundIDPeAcmeIdentifierV1Obsolete {
  315. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  316. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  317. }
  318. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  319. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  320. }
  321. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  322. // Normalize domain for wildcard DNS names
  323. // This is done to avoid making TXT lookups for domains like
  324. // _acme-challenge.*.example.com
  325. // Instead perform txt lookup for _acme-challenge.example.com
  326. domain := strings.TrimPrefix(ch.Value, "*.")
  327. vc := MustClientFromContext(ctx)
  328. txtRecords, err := vc.LookupTxt(dns01ChallengeHost(domain))
  329. if err != nil {
  330. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  331. "error looking up TXT records for domain %s", domain))
  332. }
  333. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  334. if err != nil {
  335. return err
  336. }
  337. h := sha256.Sum256([]byte(expectedKeyAuth))
  338. expected := base64.RawURLEncoding.EncodeToString(h[:])
  339. var found bool
  340. if slices.Contains(txtRecords, expected) {
  341. found = true
  342. }
  343. if !found {
  344. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  345. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  346. }
  347. // Update and store the challenge.
  348. ch.Status = StatusValid
  349. ch.Error = nil
  350. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  351. if err = db.UpdateChallenge(ctx, ch); err != nil {
  352. return WrapErrorISE(err, "error updating challenge")
  353. }
  354. return nil
  355. }
  356. type wireOidcPayload struct {
  357. // IDToken contains the OIDC identity token
  358. IDToken string `json:"id_token"`
  359. }
  360. func wireOIDC01Validate(ctx context.Context, ch *Challenge, db WireDB, jwk *jose.JSONWebKey, payload []byte) error {
  361. prov, ok := ProvisionerFromContext(ctx)
  362. if !ok {
  363. return NewErrorISE("missing provisioner")
  364. }
  365. wireOptions, err := prov.GetOptions().GetWireOptions()
  366. if err != nil {
  367. return WrapErrorISE(err, "failed getting Wire options")
  368. }
  369. linker, ok := LinkerFromContext(ctx)
  370. if !ok {
  371. return NewErrorISE("missing linker")
  372. }
  373. var oidcPayload wireOidcPayload
  374. if err := json.Unmarshal(payload, &oidcPayload); err != nil {
  375. return WrapError(ErrorMalformedType, err, "error unmarshalling Wire OIDC challenge payload")
  376. }
  377. wireID, err := wire.ParseUserID(ch.Value)
  378. if err != nil {
  379. return WrapErrorISE(err, "error unmarshalling challenge data")
  380. }
  381. oidcOptions := wireOptions.GetOIDCOptions()
  382. verifier, err := oidcOptions.GetVerifier(ctx)
  383. if err != nil {
  384. return WrapErrorISE(err, "no OIDC verifier available")
  385. }
  386. idToken, err := verifier.Verify(ctx, oidcPayload.IDToken)
  387. if err != nil {
  388. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  389. "error verifying ID token signature"))
  390. }
  391. var claims struct {
  392. Name string `json:"preferred_username,omitempty"`
  393. Handle string `json:"name"`
  394. Issuer string `json:"iss,omitempty"`
  395. GivenName string `json:"given_name,omitempty"`
  396. KeyAuth string `json:"keyauth"`
  397. ACMEAudience string `json:"acme_aud,omitempty"`
  398. }
  399. if err := idToken.Claims(&claims); err != nil {
  400. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  401. "error retrieving claims from ID token"))
  402. }
  403. // TODO(hs): move this into validation below?
  404. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  405. if err != nil {
  406. return WrapErrorISE(err, "error determining key authorization")
  407. }
  408. if expectedKeyAuth != claims.KeyAuth {
  409. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  410. "keyAuthorization does not match; expected %q, but got %q", expectedKeyAuth, claims.KeyAuth))
  411. }
  412. // audience is the full URL to the challenge
  413. acmeAudience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
  414. if claims.ACMEAudience != acmeAudience {
  415. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  416. "invalid 'acme_aud' %q", claims.ACMEAudience))
  417. }
  418. transformedIDToken, err := validateWireOIDCClaims(oidcOptions, idToken, wireID)
  419. if err != nil {
  420. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err, "claims in OIDC ID token don't match"))
  421. }
  422. // Update and store the challenge.
  423. ch.Status = StatusValid
  424. ch.Error = nil
  425. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  426. if err = db.UpdateChallenge(ctx, ch); err != nil {
  427. return WrapErrorISE(err, "error updating challenge")
  428. }
  429. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  430. if err != nil {
  431. return WrapErrorISE(err, "could not retrieve current order by account id")
  432. }
  433. if len(orders) == 0 {
  434. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  435. }
  436. order := orders[len(orders)-1]
  437. if err := db.CreateOidcToken(ctx, order, transformedIDToken); err != nil {
  438. return WrapErrorISE(err, "failed storing OIDC id token")
  439. }
  440. return nil
  441. }
  442. func validateWireOIDCClaims(o *wireprovisioner.OIDCOptions, token *oidc.IDToken, wireID wire.UserID) (map[string]any, error) {
  443. var m map[string]any
  444. if err := token.Claims(&m); err != nil {
  445. return nil, fmt.Errorf("failed extracting OIDC ID token claims: %w", err)
  446. }
  447. transformed, err := o.Transform(m)
  448. if err != nil {
  449. return nil, fmt.Errorf("failed transforming OIDC ID token: %w", err)
  450. }
  451. name, ok := transformed["name"]
  452. if !ok {
  453. return nil, fmt.Errorf("transformed OIDC ID token does not contain 'name'")
  454. }
  455. if wireID.Name != name {
  456. return nil, fmt.Errorf("invalid 'name' %q after transformation", name)
  457. }
  458. preferredUsername, ok := transformed["preferred_username"]
  459. if !ok {
  460. return nil, fmt.Errorf("transformed OIDC ID token does not contain 'preferred_username'")
  461. }
  462. if wireID.Handle != preferredUsername {
  463. return nil, fmt.Errorf("invalid 'preferred_username' %q after transformation", preferredUsername)
  464. }
  465. return transformed, nil
  466. }
  467. type wireDpopPayload struct {
  468. // AccessToken is the token generated by wire-server
  469. AccessToken string `json:"access_token"`
  470. }
  471. func wireDPOP01Validate(ctx context.Context, ch *Challenge, db WireDB, accountJWK *jose.JSONWebKey, payload []byte) error {
  472. prov, ok := ProvisionerFromContext(ctx)
  473. if !ok {
  474. return NewErrorISE("missing provisioner")
  475. }
  476. wireOptions, err := prov.GetOptions().GetWireOptions()
  477. if err != nil {
  478. return WrapErrorISE(err, "failed getting Wire options")
  479. }
  480. linker, ok := LinkerFromContext(ctx)
  481. if !ok {
  482. return NewErrorISE("missing linker")
  483. }
  484. var dpopPayload wireDpopPayload
  485. if err := json.Unmarshal(payload, &dpopPayload); err != nil {
  486. return WrapError(ErrorMalformedType, err, "error unmarshalling Wire DPoP challenge payload")
  487. }
  488. wireID, err := wire.ParseDeviceID(ch.Value)
  489. if err != nil {
  490. return WrapErrorISE(err, "error unmarshalling challenge data")
  491. }
  492. clientID, err := wire.ParseClientID(wireID.ClientID)
  493. if err != nil {
  494. return WrapErrorISE(err, "error parsing device id")
  495. }
  496. dpopOptions := wireOptions.GetDPOPOptions()
  497. issuer, err := dpopOptions.EvaluateTarget(clientID.DeviceID)
  498. if err != nil {
  499. return WrapErrorISE(err, "invalid Go template registered for 'target'")
  500. }
  501. // audience is the full URL to the challenge
  502. audience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
  503. params := wireVerifyParams{
  504. token: dpopPayload.AccessToken,
  505. tokenKey: dpopOptions.GetSigningKey(),
  506. dpopKey: accountJWK.Public(),
  507. dpopKeyID: accountJWK.KeyID,
  508. issuer: issuer,
  509. audience: audience,
  510. wireID: wireID,
  511. chToken: ch.Token,
  512. t: clock.Now().UTC(),
  513. }
  514. _, dpop, err := parseAndVerifyWireAccessToken(params)
  515. if err != nil {
  516. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  517. "failed validating Wire access token"))
  518. }
  519. // Update and store the challenge.
  520. ch.Status = StatusValid
  521. ch.Error = nil
  522. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  523. if err = db.UpdateChallenge(ctx, ch); err != nil {
  524. return WrapErrorISE(err, "error updating challenge")
  525. }
  526. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  527. if err != nil {
  528. return WrapErrorISE(err, "could not find current order by account id")
  529. }
  530. if len(orders) == 0 {
  531. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  532. }
  533. order := orders[len(orders)-1]
  534. if err := db.CreateDpopToken(ctx, order, map[string]any(*dpop)); err != nil {
  535. return WrapErrorISE(err, "failed storing DPoP token")
  536. }
  537. return nil
  538. }
  539. type wireCnf struct {
  540. Kid string `json:"kid"`
  541. }
  542. type wireAccessToken struct {
  543. jose.Claims
  544. Challenge string `json:"chal"`
  545. Nonce string `json:"nonce"`
  546. Cnf wireCnf `json:"cnf"`
  547. Proof string `json:"proof"`
  548. ClientID string `json:"client_id"`
  549. APIVersion int `json:"api_version"`
  550. Scope string `json:"scope"`
  551. }
  552. type wireDpopJwt struct {
  553. jose.Claims
  554. ClientID string `json:"client_id"`
  555. Challenge string `json:"chal"`
  556. Nonce string `json:"nonce"`
  557. HTU string `json:"htu"`
  558. }
  559. type wireDpopToken map[string]any
  560. type wireVerifyParams struct {
  561. token string
  562. tokenKey crypto.PublicKey
  563. dpopKey crypto.PublicKey
  564. dpopKeyID string
  565. issuer string
  566. audience string
  567. wireID wire.DeviceID
  568. chToken string
  569. t time.Time
  570. }
  571. func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireDpopToken, error) {
  572. jwt, err := jose.ParseSigned(v.token)
  573. if err != nil {
  574. return nil, nil, fmt.Errorf("failed parsing token: %w", err)
  575. }
  576. if len(jwt.Headers) != 1 {
  577. return nil, nil, fmt.Errorf("token has wrong number of headers %d", len(jwt.Headers))
  578. }
  579. keyID, err := KeyToID(&jose.JSONWebKey{Key: v.tokenKey})
  580. if err != nil {
  581. return nil, nil, fmt.Errorf("failed calculating token key ID: %w", err)
  582. }
  583. jwtKeyID := jwt.Headers[0].KeyID
  584. if jwtKeyID == "" {
  585. if jwtKeyID, err = KeyToID(jwt.Headers[0].JSONWebKey); err != nil {
  586. return nil, nil, fmt.Errorf("failed extracting token key ID: %w", err)
  587. }
  588. }
  589. if jwtKeyID != keyID {
  590. return nil, nil, fmt.Errorf("invalid token key ID %q", jwtKeyID)
  591. }
  592. var accessToken wireAccessToken
  593. if err = jwt.Claims(v.tokenKey, &accessToken); err != nil {
  594. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  595. }
  596. if err := accessToken.ValidateWithLeeway(jose.Expected{
  597. Time: v.t,
  598. Issuer: v.issuer,
  599. Audience: jose.Audience{v.audience},
  600. }, 1*time.Minute); err != nil {
  601. return nil, nil, fmt.Errorf("failed validation: %w", err)
  602. }
  603. if accessToken.Challenge == "" {
  604. return nil, nil, errors.New("access token challenge 'chal' must not be empty")
  605. }
  606. if accessToken.Cnf.Kid == "" || accessToken.Cnf.Kid != v.dpopKeyID {
  607. return nil, nil, fmt.Errorf("expected 'kid' %q; got %q", v.dpopKeyID, accessToken.Cnf.Kid)
  608. }
  609. if accessToken.ClientID != v.wireID.ClientID {
  610. return nil, nil, fmt.Errorf("invalid Wire 'client_id' %q", accessToken.ClientID)
  611. }
  612. if accessToken.Expiry.Time().After(v.t.Add(time.Hour)) {
  613. return nil, nil, fmt.Errorf("token expiry 'exp' %s is too far into the future", accessToken.Expiry.Time().String())
  614. }
  615. if accessToken.Scope != "wire_client_id" {
  616. return nil, nil, fmt.Errorf("invalid Wire 'scope' %q", accessToken.Scope)
  617. }
  618. dpopJWT, err := jose.ParseSigned(accessToken.Proof)
  619. if err != nil {
  620. return nil, nil, fmt.Errorf("invalid Wire DPoP token: %w", err)
  621. }
  622. if len(dpopJWT.Headers) != 1 {
  623. return nil, nil, fmt.Errorf("DPoP token has wrong number of headers %d", len(jwt.Headers))
  624. }
  625. dpopJwtKeyID := dpopJWT.Headers[0].KeyID
  626. if dpopJwtKeyID == "" {
  627. if dpopJwtKeyID, err = KeyToID(dpopJWT.Headers[0].JSONWebKey); err != nil {
  628. return nil, nil, fmt.Errorf("failed extracting DPoP token key ID: %w", err)
  629. }
  630. }
  631. if dpopJwtKeyID != v.dpopKeyID {
  632. return nil, nil, fmt.Errorf("invalid DPoP token key ID %q", dpopJWT.Headers[0].KeyID)
  633. }
  634. var wireDpop wireDpopJwt
  635. if err := dpopJWT.Claims(v.dpopKey, &wireDpop); err != nil {
  636. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  637. }
  638. if err := wireDpop.ValidateWithLeeway(jose.Expected{
  639. Time: v.t,
  640. Audience: jose.Audience{v.audience},
  641. }, 1*time.Minute); err != nil {
  642. return nil, nil, fmt.Errorf("failed DPoP validation: %w", err)
  643. }
  644. if wireDpop.HTU == "" || wireDpop.HTU != v.issuer { // DPoP doesn't contains "iss" claim, but has it in the "htu" claim
  645. return nil, nil, fmt.Errorf("DPoP contains invalid issuer 'htu' %q", wireDpop.HTU)
  646. }
  647. if wireDpop.Expiry.Time().After(v.t.Add(time.Hour)) {
  648. return nil, nil, fmt.Errorf("'exp' %s is too far into the future", wireDpop.Expiry.Time().String())
  649. }
  650. if wireDpop.Subject != v.wireID.ClientID {
  651. return nil, nil, fmt.Errorf("DPoP contains invalid Wire client ID %q", wireDpop.ClientID)
  652. }
  653. if wireDpop.Nonce == "" || wireDpop.Nonce != accessToken.Nonce {
  654. return nil, nil, fmt.Errorf("DPoP contains invalid 'nonce' %q", wireDpop.Nonce)
  655. }
  656. if wireDpop.Challenge == "" || wireDpop.Challenge != accessToken.Challenge {
  657. return nil, nil, fmt.Errorf("DPoP contains invalid challenge 'chal' %q", wireDpop.Challenge)
  658. }
  659. // TODO(hs): can we use the wireDpopJwt and map that instead of doing Claims() twice?
  660. var dpopToken wireDpopToken
  661. if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil {
  662. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  663. }
  664. challenge, ok := dpopToken["chal"].(string)
  665. if !ok {
  666. return nil, nil, fmt.Errorf("invalid challenge 'chal' in Wire DPoP token")
  667. }
  668. if challenge == "" || challenge != v.chToken {
  669. return nil, nil, fmt.Errorf("invalid Wire DPoP challenge 'chal' %q", challenge)
  670. }
  671. handle, ok := dpopToken["handle"].(string)
  672. if !ok {
  673. return nil, nil, fmt.Errorf("invalid 'handle' in Wire DPoP token")
  674. }
  675. if handle == "" || handle != v.wireID.Handle {
  676. return nil, nil, fmt.Errorf("invalid Wire client 'handle' %q", handle)
  677. }
  678. name, ok := dpopToken["name"].(string)
  679. if !ok {
  680. return nil, nil, fmt.Errorf("invalid display 'name' in Wire DPoP token")
  681. }
  682. if name == "" || name != v.wireID.Name {
  683. return nil, nil, fmt.Errorf("invalid Wire client display 'name' %q", name)
  684. }
  685. return &accessToken, &dpopToken, nil
  686. }
  687. type payloadType struct {
  688. AttObj string `json:"attObj"`
  689. Error string `json:"error"`
  690. }
  691. type attestationObject struct {
  692. Format string `json:"fmt"`
  693. AttStatement map[string]any `json:"attStmt,omitempty"`
  694. }
  695. func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  696. // Update challenge with the payload
  697. ch.Payload = payload
  698. // Load authorization to store the key fingerprint.
  699. az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
  700. if err != nil {
  701. return WrapErrorISE(err, "error loading authorization")
  702. }
  703. // Parse payload.
  704. var p payloadType
  705. if err := json.Unmarshal(payload, &p); err != nil {
  706. return WrapErrorISE(err, "error unmarshalling JSON")
  707. }
  708. if p.Error != "" {
  709. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  710. "payload contained error: %v", p.Error))
  711. }
  712. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  713. if err != nil {
  714. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "failed base64 decoding attObj %q", p.AttObj))
  715. }
  716. if len(attObj) == 0 || bytes.Equal(attObj, []byte("{}")) {
  717. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj must not be empty"))
  718. }
  719. cborDecoderOptions := cbor.DecOptions{}
  720. cborDecoder, err := cborDecoderOptions.DecMode()
  721. if err != nil {
  722. return WrapErrorISE(err, "failed creating CBOR decoder")
  723. }
  724. if err := cborDecoder.Wellformed(attObj); err != nil {
  725. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj is not well formed CBOR: %v", err))
  726. }
  727. att := attestationObject{}
  728. if err := cborDecoder.Unmarshal(attObj, &att); err != nil {
  729. return WrapErrorISE(err, "failed unmarshalling CBOR")
  730. }
  731. format := att.Format
  732. prov := MustProvisionerFromContext(ctx)
  733. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(format)) {
  734. if format != "apple" && format != "step" && format != "tpm" && format != "android-key" {
  735. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  736. }
  737. return storeError(ctx, db, ch, true,
  738. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", format))
  739. }
  740. switch format {
  741. case "android-key":
  742. acmeProv, ok := prov.(*provisioner.ACME)
  743. if !ok {
  744. return NewErrorISE("provisioner in context is not an ACME provisioner")
  745. }
  746. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  747. if err != nil {
  748. return err
  749. }
  750. data, err := androidkey.Verify(ctx, att.AttStatement, attestationRoots(prov), []byte(keyAuth), acmeProv.IsAndroidCertificateRevoked)
  751. if err != nil {
  752. return storeAttestationError(ctx, db, ch, err)
  753. }
  754. // Enforce hardware security level (TrustedEnvironment or StrongBox; Software not allowed)
  755. if data.KeyDescription.AttestationSecurityLevel < 1 {
  756. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "insufficient security level: %d", data.KeyDescription.AttestationSecurityLevel))
  757. }
  758. // Enforce hardware backed device serial
  759. if ch.Value != string(data.KeyDescription.TeeEnforced.AttestationIdSerial) {
  760. subproblem := NewSubproblemWithIdentifier(
  761. ErrorRejectedIdentifierType,
  762. Identifier{Type: "permanent-identifier", Value: ch.Value},
  763. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{string(data.KeyDescription.TeeEnforced.AttestationIdSerial)},
  764. )
  765. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  766. }
  767. // Update attestation key fingerprint to compare against the CSR
  768. az.Fingerprint = data.Fingerprint
  769. case "apple":
  770. data, err := apple.Verify(att.AttStatement, attestationRoots(prov))
  771. if err != nil {
  772. return storeAttestationError(ctx, db, ch, err)
  773. }
  774. // Validate nonce with SHA-256 of the token.
  775. if len(data.Nonce) != 0 {
  776. sum := sha256.Sum256([]byte(ch.Token))
  777. if subtle.ConstantTimeCompare(data.Nonce, sum[:]) != 1 {
  778. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "challenge token does not match"))
  779. }
  780. }
  781. // Validate Apple's ClientIdentifier (Identifier.Value) with device
  782. // identifiers.
  783. //
  784. // Note: We might want to use an external service for this.
  785. if data.UDID != ch.Value && data.SerialNumber != ch.Value {
  786. subproblem := NewSubproblemWithIdentifier(
  787. ErrorRejectedIdentifierType,
  788. Identifier{Type: "permanent-identifier", Value: ch.Value},
  789. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{data.UDID, data.SerialNumber},
  790. )
  791. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  792. }
  793. // Update attestation key fingerprint to compare against the CSR
  794. az.Fingerprint = data.Fingerprint
  795. case "step":
  796. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  797. if err != nil {
  798. return err
  799. }
  800. data, err := yubikey.Verify(att.AttStatement, attestationRoots(prov), []byte(keyAuth))
  801. if err != nil {
  802. return storeAttestationError(ctx, db, ch, err)
  803. }
  804. // Validate the YubiKey serial number from the attestation
  805. // certificate with the challenged Order value.
  806. //
  807. // Note: We might want to use an external service for this.
  808. if data.SerialNumber != ch.Value {
  809. subproblem := NewSubproblemWithIdentifier(
  810. ErrorRejectedIdentifierType,
  811. Identifier{Type: "permanent-identifier", Value: ch.Value},
  812. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  813. )
  814. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  815. }
  816. // Update attestation key fingerprint to compare against the CSR
  817. az.Fingerprint = data.Fingerprint
  818. case "tpm":
  819. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  820. if err != nil {
  821. return WrapErrorISE(err, "failed creating key auth digest")
  822. }
  823. data, err := tpm.Verify(att.AttStatement, attestationRoots(prov), []byte(keyAuth))
  824. if err != nil {
  825. return storeAttestationError(ctx, db, ch, err)
  826. }
  827. // TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
  828. // extracted from the AK certificate. This is currently the case for AK certs from the CLI, as we
  829. // haven't implemented a way for AK certs requested by the CLI to always contain the requested
  830. // PermanentIdentifier. Omitting the check below doesn't allow just any request, as the Order can
  831. // still fail if the challenge value isn't equal to the CSR subject.
  832. if len(data.PermanentIdentifiers) > 0 && !slices.Contains(data.PermanentIdentifiers, ch.Value) { // TODO(hs): add support for HardwareModuleName
  833. subproblem := NewSubproblemWithIdentifier(
  834. ErrorRejectedIdentifierType,
  835. Identifier{Type: "permanent-identifier", Value: ch.Value},
  836. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, data.PermanentIdentifiers,
  837. )
  838. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  839. }
  840. // Update attestation key fingerprint to compare against the CSR
  841. az.Fingerprint = data.Fingerprint
  842. default:
  843. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  844. }
  845. // Update and store the challenge.
  846. ch.Status = StatusValid
  847. ch.Error = nil
  848. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  849. ch.PayloadFormat = format
  850. // Store the fingerprint in the authorization.
  851. //
  852. // TODO: add method to update authorization and challenge atomically.
  853. if az.Fingerprint != "" {
  854. if err := db.UpdateAuthorization(ctx, az); err != nil {
  855. return WrapErrorISE(err, "error updating authorization")
  856. }
  857. }
  858. if err := db.UpdateChallenge(ctx, ch); err != nil {
  859. return WrapErrorISE(err, "error updating challenge")
  860. }
  861. return nil
  862. }
  863. // attestationRoots returns the attestation roots configured in the
  864. // provisioner, or nil, which makes a verifier use its default roots.
  865. func attestationRoots(prov Provisioner) *x509.CertPool {
  866. if roots, ok := prov.GetAttestationRoots(); ok {
  867. return roots
  868. }
  869. return nil
  870. }
  871. // storeAttestationError handles an error of a device-attest-01 verifier. An
  872. // error of the attestation statement is stored in the challenge, which becomes
  873. // invalid, as a bad attestation statement with the error in its detail. Any
  874. // other error is returned as an internal error.
  875. //
  876. // The exceptions keep the errors the step and android-key formats have always
  877. // returned: an empty x5c is a rejected identifier, and a malformed serial number
  878. // or key description has no detail.
  879. func storeAttestationError(ctx context.Context, db DB, ch *Challenge, err error) error {
  880. var acmeErr *Error
  881. switch {
  882. case !errors.Is(err, attestation.ErrInvalidEvidence):
  883. return newError(ErrorServerInternalType, err)
  884. case errors.Is(err, yubikey.ErrEmptyX5C), errors.Is(err, androidkey.ErrEmptyX5C):
  885. acmeErr = newError(ErrorRejectedIdentifierType, err).withDetail()
  886. case errors.Is(err, yubikey.ErrSerialNumber), errors.Is(err, androidkey.ErrKeyDescription):
  887. acmeErr = newError(ErrorBadAttestationStatementType, err)
  888. default:
  889. acmeErr = newError(ErrorBadAttestationStatementType, err).withDetail()
  890. }
  891. return storeError(ctx, db, ch, true, acmeErr)
  892. }
  893. // serverName determines the SNI HostName to set based on an acme.Challenge
  894. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  895. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  896. // It also references TLS Extensions [RFC6066].
  897. func serverName(ch *Challenge) string {
  898. if ip := net.ParseIP(ch.Value); ip != nil {
  899. return reverseAddr(ip)
  900. }
  901. return ch.Value
  902. }
  903. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  904. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  905. // to parse the IP address.
  906. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  907. func reverseAddr(ip net.IP) (arpa string) {
  908. if ip.To4() != nil {
  909. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  910. }
  911. // Must be IPv6
  912. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  913. // Add it, in reverse, to the buffer
  914. for _, v := range slices.Backward(ip) {
  915. buf = append(buf, hexit[v&0xF],
  916. '.',
  917. hexit[v>>4],
  918. '.')
  919. }
  920. // Append "ip6.arpa." and return (buf already has the final .)
  921. buf = append(buf, "ip6.arpa."...)
  922. return string(buf)
  923. }
  924. // Convert unsigned integer to decimal string.
  925. // Implementation taken from https://golang.org/src/net/parse.go
  926. func uitoa(val uint) string {
  927. if val == 0 { // avoid string allocation
  928. return "0"
  929. }
  930. var buf [20]byte // big enough for 64bit value base 10
  931. i := len(buf) - 1
  932. for val >= 10 {
  933. v := val / 10
  934. buf[i] = byte('0' + val - v*10) //nolint:gosec // val - v*10 is always 0-9
  935. i--
  936. val = v
  937. }
  938. // val < 10
  939. buf[i] = byte('0' + val)
  940. return string(buf[i:])
  941. }
  942. const hexit = "0123456789abcdef"
  943. // KeyAuthorization creates the ACME key authorization value from a token
  944. // and a jwk.
  945. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  946. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  947. if err != nil {
  948. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  949. }
  950. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  951. return fmt.Sprintf("%s.%s", token, encPrint), nil
  952. }
  953. // storeError the given error to an ACME error and saves using the DB interface.
  954. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  955. ch.Error = err
  956. if markInvalid {
  957. ch.Status = StatusInvalid
  958. }
  959. if err := db.UpdateChallenge(ctx, ch); err != nil {
  960. return WrapErrorISE(err, "failure saving error to acme challenge")
  961. }
  962. return nil
  963. }