challenge.go 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. package acme
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/ecdsa"
  7. "crypto/ed25519"
  8. "crypto/elliptic"
  9. "crypto/rsa"
  10. "crypto/sha256"
  11. "crypto/subtle"
  12. "crypto/tls"
  13. "crypto/x509"
  14. "encoding/asn1"
  15. "encoding/base64"
  16. "encoding/hex"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/url"
  23. "reflect"
  24. "slices"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/coreos/go-oidc/v3/oidc"
  29. "github.com/fxamacker/cbor/v2"
  30. "github.com/google/go-tpm/legacy/tpm2"
  31. attestation "github.com/smallstep/android-attestation"
  32. "github.com/smallstep/go-attestation/attest"
  33. "go.step.sm/crypto/jose"
  34. "go.step.sm/crypto/keyutil"
  35. "go.step.sm/crypto/mldsa"
  36. "go.step.sm/crypto/pemutil"
  37. "go.step.sm/crypto/x509util"
  38. "github.com/smallstep/certificates/acme/wire"
  39. "github.com/smallstep/certificates/authority/provisioner"
  40. wireprovisioner "github.com/smallstep/certificates/authority/provisioner/wire"
  41. "github.com/smallstep/certificates/internal/cast"
  42. )
  43. type ChallengeType string
  44. const (
  45. // HTTP01 is the http-01 ACME challenge type
  46. HTTP01 ChallengeType = "http-01"
  47. // DNS01 is the dns-01 ACME challenge type
  48. DNS01 ChallengeType = "dns-01"
  49. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  50. TLSALPN01 ChallengeType = "tls-alpn-01"
  51. // DEVICEATTEST01 is the device-attest-01 ACME challenge type
  52. DEVICEATTEST01 ChallengeType = "device-attest-01"
  53. // WIREOIDC01 is the Wire OIDC challenge type
  54. WIREOIDC01 ChallengeType = "wire-oidc-01"
  55. // WIREDPOP01 is the Wire DPoP challenge type
  56. WIREDPOP01 ChallengeType = "wire-dpop-01"
  57. )
  58. var (
  59. // InsecurePortHTTP01 is the port used to verify http-01 challenges. If not set it
  60. // defaults to 80.
  61. InsecurePortHTTP01 int
  62. // InsecurePortTLSALPN01 is the port used to verify tls-alpn-01 challenges. If not
  63. // set it defaults to 443.
  64. //
  65. // This variable can be used for testing purposes.
  66. InsecurePortTLSALPN01 int
  67. // StrictFQDN allows to enforce a fully qualified domain name in the DNS
  68. // resolution. By default it allows domain resolution using a search list
  69. // defined in the resolv.conf or similar configuration.
  70. StrictFQDN bool
  71. )
  72. // Challenge represents an ACME response Challenge type.
  73. type Challenge struct {
  74. ID string `json:"-"`
  75. AccountID string `json:"-"`
  76. AuthorizationID string `json:"-"`
  77. Value string `json:"-"`
  78. Type ChallengeType `json:"type"`
  79. Status Status `json:"status"`
  80. Token string `json:"token"`
  81. ValidatedAt string `json:"validated,omitempty"`
  82. URL string `json:"url"`
  83. Target string `json:"target,omitempty"`
  84. Error *Error `json:"error,omitempty"`
  85. Payload []byte `json:"-"`
  86. PayloadFormat string `json:"-"`
  87. }
  88. // ToLog enables response logging.
  89. func (ch *Challenge) ToLog() (any, error) {
  90. b, err := json.Marshal(ch)
  91. if err != nil {
  92. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  93. }
  94. return string(b), nil
  95. }
  96. // Validate attempts to validate the Challenge. Stores changes to the Challenge
  97. // type using the DB interface. If the Challenge is validated, the 'status' and
  98. // 'validated' attributes are updated.
  99. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  100. // If already valid or invalid then return without performing validation.
  101. if ch.Status != StatusPending {
  102. return nil
  103. }
  104. switch ch.Type {
  105. case HTTP01:
  106. return http01Validate(ctx, ch, db, jwk)
  107. case DNS01:
  108. return dns01Validate(ctx, ch, db, jwk)
  109. case TLSALPN01:
  110. return tlsalpn01Validate(ctx, ch, db, jwk)
  111. case DEVICEATTEST01:
  112. return deviceAttest01Validate(ctx, ch, db, jwk, payload)
  113. case WIREOIDC01:
  114. wireDB, ok := db.(WireDB)
  115. if !ok {
  116. return NewErrorISE("db %T is not a WireDB", db)
  117. }
  118. return wireOIDC01Validate(ctx, ch, wireDB, jwk, payload)
  119. case WIREDPOP01:
  120. wireDB, ok := db.(WireDB)
  121. if !ok {
  122. return NewErrorISE("db %T is not a WireDB", db)
  123. }
  124. return wireDPOP01Validate(ctx, ch, wireDB, jwk, payload)
  125. default:
  126. return NewErrorISE("unexpected challenge type %q", ch.Type)
  127. }
  128. }
  129. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  130. u := &url.URL{Scheme: "http", Host: ch.Value, Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  131. challengeURL := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  132. // Append insecure port if set.
  133. // Only used for testing purposes.
  134. if InsecurePortHTTP01 != 0 {
  135. insecurePort := strconv.Itoa(InsecurePortHTTP01)
  136. u.Host += ":" + insecurePort
  137. challengeURL.Host += ":" + insecurePort
  138. }
  139. vc := MustClientFromContext(ctx)
  140. resp, err := vc.Get(challengeURL.String())
  141. if err != nil {
  142. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  143. "error doing http GET for url %s", u))
  144. }
  145. defer resp.Body.Close()
  146. if resp.StatusCode >= 400 {
  147. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  148. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  149. }
  150. body, err := io.ReadAll(resp.Body)
  151. if err != nil {
  152. return WrapErrorISE(err, "error reading "+
  153. "response body for url %s", u)
  154. }
  155. keyAuth := strings.TrimSpace(string(body))
  156. expected, err := KeyAuthorization(ch.Token, jwk)
  157. if err != nil {
  158. return err
  159. }
  160. if keyAuth != expected {
  161. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  162. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  163. }
  164. // Update and store the challenge.
  165. ch.Status = StatusValid
  166. ch.Error = nil
  167. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  168. if err = db.UpdateChallenge(ctx, ch); err != nil {
  169. return WrapErrorISE(err, "error updating challenge")
  170. }
  171. return nil
  172. }
  173. // rootedName adds a trailing "." to a given domain name.
  174. func rootedName(name string) string {
  175. if StrictFQDN {
  176. if name == "" || name[len(name)-1] != '.' {
  177. return name + "."
  178. }
  179. }
  180. return name
  181. }
  182. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  183. // and adds square brackets if that's the case, so that it can be used
  184. // as a hostname. Returns the original Challenge value as the host to
  185. // use in other cases.
  186. func http01ChallengeHost(value string) string {
  187. if ip := net.ParseIP(value); ip != nil {
  188. if ip.To4() == nil {
  189. value = "[" + value + "]"
  190. }
  191. return value
  192. }
  193. return rootedName(value)
  194. }
  195. // tlsAlpn01ChallengeHost returns the rooted DNS used on TLS-ALPN-01
  196. // validations.
  197. func tlsAlpn01ChallengeHost(name string) string {
  198. if ip := net.ParseIP(name); ip != nil {
  199. return name
  200. }
  201. return rootedName(name)
  202. }
  203. // dns01ChallengeHost returns the TXT record used in DNS-01 validations.
  204. func dns01ChallengeHost(domain string) string {
  205. return "_acme-challenge." + rootedName(domain)
  206. }
  207. func tlsAlert(err error) uint8 {
  208. if opErr, ok := errors.AsType[*net.OpError](err); ok {
  209. v := reflect.ValueOf(opErr.Err)
  210. if v.Kind() == reflect.Uint8 {
  211. return cast.Uint8(v.Uint())
  212. }
  213. }
  214. return 0
  215. }
  216. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  217. config := &tls.Config{
  218. NextProtos: []string{"acme-tls/1"},
  219. // https://tools.ietf.org/html/rfc8737#section-4
  220. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  221. // [RFC5246] or higher when connecting to clients for validation.
  222. MinVersion: tls.VersionTLS12,
  223. ServerName: serverName(ch),
  224. InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate
  225. }
  226. // Allow to change TLS port for testing purposes.
  227. hostPort := tlsAlpn01ChallengeHost(ch.Value)
  228. if port := InsecurePortTLSALPN01; port == 0 {
  229. hostPort = net.JoinHostPort(hostPort, "443")
  230. } else {
  231. hostPort = net.JoinHostPort(hostPort, strconv.Itoa(port))
  232. }
  233. vc := MustClientFromContext(ctx)
  234. conn, err := vc.TLSDial("tcp", hostPort, config)
  235. if err != nil {
  236. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  237. // client and server protocols. When this happens the connection is
  238. // closed with the error no_application_protocol(120) as required by
  239. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  240. if tlsAlert(err) == 120 {
  241. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  242. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  243. }
  244. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  245. "error doing TLS dial for %s", ch.Value))
  246. }
  247. defer conn.Close()
  248. cs := conn.ConnectionState()
  249. certs := cs.PeerCertificates
  250. if len(certs) == 0 {
  251. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  252. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  253. }
  254. if cs.NegotiatedProtocol != "acme-tls/1" {
  255. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  256. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  257. }
  258. leafCert := certs[0]
  259. // if no DNS names present, look for IP address and verify that exactly one exists
  260. if len(leafCert.DNSNames) == 0 {
  261. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  262. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  263. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  264. }
  265. } else {
  266. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], 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. }
  271. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  272. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  273. foundIDPeAcmeIdentifierV1Obsolete := false
  274. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  275. if err != nil {
  276. return err
  277. }
  278. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  279. for _, ext := range leafCert.Extensions {
  280. if idPeAcmeIdentifier.Equal(ext.Id) {
  281. if !ext.Critical {
  282. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  283. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  284. }
  285. var extValue []byte
  286. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  287. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  288. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  289. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  290. }
  291. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  292. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  293. "incorrect certificate for tls-alpn-01 challenge: "+
  294. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  295. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  296. }
  297. ch.Status = StatusValid
  298. ch.Error = nil
  299. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  300. if err = db.UpdateChallenge(ctx, ch); err != nil {
  301. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  302. }
  303. return nil
  304. }
  305. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  306. foundIDPeAcmeIdentifierV1Obsolete = true
  307. }
  308. }
  309. if foundIDPeAcmeIdentifierV1Obsolete {
  310. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  311. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  312. }
  313. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  314. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  315. }
  316. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  317. // Normalize domain for wildcard DNS names
  318. // This is done to avoid making TXT lookups for domains like
  319. // _acme-challenge.*.example.com
  320. // Instead perform txt lookup for _acme-challenge.example.com
  321. domain := strings.TrimPrefix(ch.Value, "*.")
  322. vc := MustClientFromContext(ctx)
  323. txtRecords, err := vc.LookupTxt(dns01ChallengeHost(domain))
  324. if err != nil {
  325. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  326. "error looking up TXT records for domain %s", domain))
  327. }
  328. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  329. if err != nil {
  330. return err
  331. }
  332. h := sha256.Sum256([]byte(expectedKeyAuth))
  333. expected := base64.RawURLEncoding.EncodeToString(h[:])
  334. var found bool
  335. if slices.Contains(txtRecords, expected) {
  336. found = true
  337. }
  338. if !found {
  339. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  340. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  341. }
  342. // Update and store the challenge.
  343. ch.Status = StatusValid
  344. ch.Error = nil
  345. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  346. if err = db.UpdateChallenge(ctx, ch); err != nil {
  347. return WrapErrorISE(err, "error updating challenge")
  348. }
  349. return nil
  350. }
  351. type wireOidcPayload struct {
  352. // IDToken contains the OIDC identity token
  353. IDToken string `json:"id_token"`
  354. }
  355. func wireOIDC01Validate(ctx context.Context, ch *Challenge, db WireDB, jwk *jose.JSONWebKey, payload []byte) error {
  356. prov, ok := ProvisionerFromContext(ctx)
  357. if !ok {
  358. return NewErrorISE("missing provisioner")
  359. }
  360. wireOptions, err := prov.GetOptions().GetWireOptions()
  361. if err != nil {
  362. return WrapErrorISE(err, "failed getting Wire options")
  363. }
  364. linker, ok := LinkerFromContext(ctx)
  365. if !ok {
  366. return NewErrorISE("missing linker")
  367. }
  368. var oidcPayload wireOidcPayload
  369. if err := json.Unmarshal(payload, &oidcPayload); err != nil {
  370. return WrapError(ErrorMalformedType, err, "error unmarshalling Wire OIDC challenge payload")
  371. }
  372. wireID, err := wire.ParseUserID(ch.Value)
  373. if err != nil {
  374. return WrapErrorISE(err, "error unmarshalling challenge data")
  375. }
  376. oidcOptions := wireOptions.GetOIDCOptions()
  377. verifier, err := oidcOptions.GetVerifier(ctx)
  378. if err != nil {
  379. return WrapErrorISE(err, "no OIDC verifier available")
  380. }
  381. idToken, err := verifier.Verify(ctx, oidcPayload.IDToken)
  382. if err != nil {
  383. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  384. "error verifying ID token signature"))
  385. }
  386. var claims struct {
  387. Name string `json:"preferred_username,omitempty"`
  388. Handle string `json:"name"`
  389. Issuer string `json:"iss,omitempty"`
  390. GivenName string `json:"given_name,omitempty"`
  391. KeyAuth string `json:"keyauth"`
  392. ACMEAudience string `json:"acme_aud,omitempty"`
  393. }
  394. if err := idToken.Claims(&claims); err != nil {
  395. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  396. "error retrieving claims from ID token"))
  397. }
  398. // TODO(hs): move this into validation below?
  399. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  400. if err != nil {
  401. return WrapErrorISE(err, "error determining key authorization")
  402. }
  403. if expectedKeyAuth != claims.KeyAuth {
  404. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  405. "keyAuthorization does not match; expected %q, but got %q", expectedKeyAuth, claims.KeyAuth))
  406. }
  407. // audience is the full URL to the challenge
  408. acmeAudience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
  409. if claims.ACMEAudience != acmeAudience {
  410. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  411. "invalid 'acme_aud' %q", claims.ACMEAudience))
  412. }
  413. transformedIDToken, err := validateWireOIDCClaims(oidcOptions, idToken, wireID)
  414. if err != nil {
  415. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err, "claims in OIDC ID token don't match"))
  416. }
  417. // Update and store the challenge.
  418. ch.Status = StatusValid
  419. ch.Error = nil
  420. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  421. if err = db.UpdateChallenge(ctx, ch); err != nil {
  422. return WrapErrorISE(err, "error updating challenge")
  423. }
  424. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  425. if err != nil {
  426. return WrapErrorISE(err, "could not retrieve current order by account id")
  427. }
  428. if len(orders) == 0 {
  429. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  430. }
  431. order := orders[len(orders)-1]
  432. if err := db.CreateOidcToken(ctx, order, transformedIDToken); err != nil {
  433. return WrapErrorISE(err, "failed storing OIDC id token")
  434. }
  435. return nil
  436. }
  437. func validateWireOIDCClaims(o *wireprovisioner.OIDCOptions, token *oidc.IDToken, wireID wire.UserID) (map[string]any, error) {
  438. var m map[string]any
  439. if err := token.Claims(&m); err != nil {
  440. return nil, fmt.Errorf("failed extracting OIDC ID token claims: %w", err)
  441. }
  442. transformed, err := o.Transform(m)
  443. if err != nil {
  444. return nil, fmt.Errorf("failed transforming OIDC ID token: %w", err)
  445. }
  446. name, ok := transformed["name"]
  447. if !ok {
  448. return nil, fmt.Errorf("transformed OIDC ID token does not contain 'name'")
  449. }
  450. if wireID.Name != name {
  451. return nil, fmt.Errorf("invalid 'name' %q after transformation", name)
  452. }
  453. preferredUsername, ok := transformed["preferred_username"]
  454. if !ok {
  455. return nil, fmt.Errorf("transformed OIDC ID token does not contain 'preferred_username'")
  456. }
  457. if wireID.Handle != preferredUsername {
  458. return nil, fmt.Errorf("invalid 'preferred_username' %q after transformation", preferredUsername)
  459. }
  460. return transformed, nil
  461. }
  462. type wireDpopPayload struct {
  463. // AccessToken is the token generated by wire-server
  464. AccessToken string `json:"access_token"`
  465. }
  466. func wireDPOP01Validate(ctx context.Context, ch *Challenge, db WireDB, accountJWK *jose.JSONWebKey, payload []byte) error {
  467. prov, ok := ProvisionerFromContext(ctx)
  468. if !ok {
  469. return NewErrorISE("missing provisioner")
  470. }
  471. wireOptions, err := prov.GetOptions().GetWireOptions()
  472. if err != nil {
  473. return WrapErrorISE(err, "failed getting Wire options")
  474. }
  475. linker, ok := LinkerFromContext(ctx)
  476. if !ok {
  477. return NewErrorISE("missing linker")
  478. }
  479. var dpopPayload wireDpopPayload
  480. if err := json.Unmarshal(payload, &dpopPayload); err != nil {
  481. return WrapError(ErrorMalformedType, err, "error unmarshalling Wire DPoP challenge payload")
  482. }
  483. wireID, err := wire.ParseDeviceID(ch.Value)
  484. if err != nil {
  485. return WrapErrorISE(err, "error unmarshalling challenge data")
  486. }
  487. clientID, err := wire.ParseClientID(wireID.ClientID)
  488. if err != nil {
  489. return WrapErrorISE(err, "error parsing device id")
  490. }
  491. dpopOptions := wireOptions.GetDPOPOptions()
  492. issuer, err := dpopOptions.EvaluateTarget(clientID.DeviceID)
  493. if err != nil {
  494. return WrapErrorISE(err, "invalid Go template registered for 'target'")
  495. }
  496. // audience is the full URL to the challenge
  497. audience := linker.GetLink(ctx, ChallengeLinkType, ch.AuthorizationID, ch.ID)
  498. params := wireVerifyParams{
  499. token: dpopPayload.AccessToken,
  500. tokenKey: dpopOptions.GetSigningKey(),
  501. dpopKey: accountJWK.Public(),
  502. dpopKeyID: accountJWK.KeyID,
  503. issuer: issuer,
  504. audience: audience,
  505. wireID: wireID,
  506. chToken: ch.Token,
  507. t: clock.Now().UTC(),
  508. }
  509. _, dpop, err := parseAndVerifyWireAccessToken(params)
  510. if err != nil {
  511. return storeError(ctx, db, ch, true, WrapError(ErrorRejectedIdentifierType, err,
  512. "failed validating Wire access token"))
  513. }
  514. // Update and store the challenge.
  515. ch.Status = StatusValid
  516. ch.Error = nil
  517. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  518. if err = db.UpdateChallenge(ctx, ch); err != nil {
  519. return WrapErrorISE(err, "error updating challenge")
  520. }
  521. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  522. if err != nil {
  523. return WrapErrorISE(err, "could not find current order by account id")
  524. }
  525. if len(orders) == 0 {
  526. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  527. }
  528. order := orders[len(orders)-1]
  529. if err := db.CreateDpopToken(ctx, order, map[string]any(*dpop)); err != nil {
  530. return WrapErrorISE(err, "failed storing DPoP token")
  531. }
  532. return nil
  533. }
  534. type wireCnf struct {
  535. Kid string `json:"kid"`
  536. }
  537. type wireAccessToken struct {
  538. jose.Claims
  539. Challenge string `json:"chal"`
  540. Nonce string `json:"nonce"`
  541. Cnf wireCnf `json:"cnf"`
  542. Proof string `json:"proof"`
  543. ClientID string `json:"client_id"`
  544. APIVersion int `json:"api_version"`
  545. Scope string `json:"scope"`
  546. }
  547. type wireDpopJwt struct {
  548. jose.Claims
  549. ClientID string `json:"client_id"`
  550. Challenge string `json:"chal"`
  551. Nonce string `json:"nonce"`
  552. HTU string `json:"htu"`
  553. }
  554. type wireDpopToken map[string]any
  555. type wireVerifyParams struct {
  556. token string
  557. tokenKey crypto.PublicKey
  558. dpopKey crypto.PublicKey
  559. dpopKeyID string
  560. issuer string
  561. audience string
  562. wireID wire.DeviceID
  563. chToken string
  564. t time.Time
  565. }
  566. func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *wireDpopToken, error) {
  567. jwt, err := jose.ParseSigned(v.token)
  568. if err != nil {
  569. return nil, nil, fmt.Errorf("failed parsing token: %w", err)
  570. }
  571. if len(jwt.Headers) != 1 {
  572. return nil, nil, fmt.Errorf("token has wrong number of headers %d", len(jwt.Headers))
  573. }
  574. keyID, err := KeyToID(&jose.JSONWebKey{Key: v.tokenKey})
  575. if err != nil {
  576. return nil, nil, fmt.Errorf("failed calculating token key ID: %w", err)
  577. }
  578. jwtKeyID := jwt.Headers[0].KeyID
  579. if jwtKeyID == "" {
  580. if jwtKeyID, err = KeyToID(jwt.Headers[0].JSONWebKey); err != nil {
  581. return nil, nil, fmt.Errorf("failed extracting token key ID: %w", err)
  582. }
  583. }
  584. if jwtKeyID != keyID {
  585. return nil, nil, fmt.Errorf("invalid token key ID %q", jwtKeyID)
  586. }
  587. var accessToken wireAccessToken
  588. if err = jwt.Claims(v.tokenKey, &accessToken); err != nil {
  589. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  590. }
  591. if err := accessToken.ValidateWithLeeway(jose.Expected{
  592. Time: v.t,
  593. Issuer: v.issuer,
  594. AnyAudience: jose.Audience{v.audience},
  595. }, 1*time.Minute); err != nil {
  596. return nil, nil, fmt.Errorf("failed validation: %w", err)
  597. }
  598. if accessToken.Challenge == "" {
  599. return nil, nil, errors.New("access token challenge 'chal' must not be empty")
  600. }
  601. if accessToken.Cnf.Kid == "" || accessToken.Cnf.Kid != v.dpopKeyID {
  602. return nil, nil, fmt.Errorf("expected 'kid' %q; got %q", v.dpopKeyID, accessToken.Cnf.Kid)
  603. }
  604. if accessToken.ClientID != v.wireID.ClientID {
  605. return nil, nil, fmt.Errorf("invalid Wire 'client_id' %q", accessToken.ClientID)
  606. }
  607. if accessToken.Expiry.Time().After(v.t.Add(time.Hour)) {
  608. return nil, nil, fmt.Errorf("token expiry 'exp' %s is too far into the future", accessToken.Expiry.Time().String())
  609. }
  610. if accessToken.Scope != "wire_client_id" {
  611. return nil, nil, fmt.Errorf("invalid Wire 'scope' %q", accessToken.Scope)
  612. }
  613. dpopJWT, err := jose.ParseSigned(accessToken.Proof)
  614. if err != nil {
  615. return nil, nil, fmt.Errorf("invalid Wire DPoP token: %w", err)
  616. }
  617. if len(dpopJWT.Headers) != 1 {
  618. return nil, nil, fmt.Errorf("DPoP token has wrong number of headers %d", len(jwt.Headers))
  619. }
  620. dpopJwtKeyID := dpopJWT.Headers[0].KeyID
  621. if dpopJwtKeyID == "" {
  622. if dpopJwtKeyID, err = KeyToID(dpopJWT.Headers[0].JSONWebKey); err != nil {
  623. return nil, nil, fmt.Errorf("failed extracting DPoP token key ID: %w", err)
  624. }
  625. }
  626. if dpopJwtKeyID != v.dpopKeyID {
  627. return nil, nil, fmt.Errorf("invalid DPoP token key ID %q", dpopJWT.Headers[0].KeyID)
  628. }
  629. var wireDpop wireDpopJwt
  630. if err := dpopJWT.Claims(v.dpopKey, &wireDpop); err != nil {
  631. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  632. }
  633. if err := wireDpop.ValidateWithLeeway(jose.Expected{
  634. Time: v.t,
  635. AnyAudience: jose.Audience{v.audience},
  636. }, 1*time.Minute); err != nil {
  637. return nil, nil, fmt.Errorf("failed DPoP validation: %w", err)
  638. }
  639. if wireDpop.HTU == "" || wireDpop.HTU != v.issuer { // DPoP doesn't contains "iss" claim, but has it in the "htu" claim
  640. return nil, nil, fmt.Errorf("DPoP contains invalid issuer 'htu' %q", wireDpop.HTU)
  641. }
  642. if wireDpop.Expiry.Time().After(v.t.Add(time.Hour)) {
  643. return nil, nil, fmt.Errorf("'exp' %s is too far into the future", wireDpop.Expiry.Time().String())
  644. }
  645. if wireDpop.Subject != v.wireID.ClientID {
  646. return nil, nil, fmt.Errorf("DPoP contains invalid Wire client ID %q", wireDpop.ClientID)
  647. }
  648. if wireDpop.Nonce == "" || wireDpop.Nonce != accessToken.Nonce {
  649. return nil, nil, fmt.Errorf("DPoP contains invalid 'nonce' %q", wireDpop.Nonce)
  650. }
  651. if wireDpop.Challenge == "" || wireDpop.Challenge != accessToken.Challenge {
  652. return nil, nil, fmt.Errorf("DPoP contains invalid challenge 'chal' %q", wireDpop.Challenge)
  653. }
  654. // TODO(hs): can we use the wireDpopJwt and map that instead of doing Claims() twice?
  655. var dpopToken wireDpopToken
  656. if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil {
  657. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  658. }
  659. challenge, ok := dpopToken["chal"].(string)
  660. if !ok {
  661. return nil, nil, fmt.Errorf("invalid challenge 'chal' in Wire DPoP token")
  662. }
  663. if challenge == "" || challenge != v.chToken {
  664. return nil, nil, fmt.Errorf("invalid Wire DPoP challenge 'chal' %q", challenge)
  665. }
  666. handle, ok := dpopToken["handle"].(string)
  667. if !ok {
  668. return nil, nil, fmt.Errorf("invalid 'handle' in Wire DPoP token")
  669. }
  670. if handle == "" || handle != v.wireID.Handle {
  671. return nil, nil, fmt.Errorf("invalid Wire client 'handle' %q", handle)
  672. }
  673. name, ok := dpopToken["name"].(string)
  674. if !ok {
  675. return nil, nil, fmt.Errorf("invalid display 'name' in Wire DPoP token")
  676. }
  677. if name == "" || name != v.wireID.Name {
  678. return nil, nil, fmt.Errorf("invalid Wire client display 'name' %q", name)
  679. }
  680. return &accessToken, &dpopToken, nil
  681. }
  682. type payloadType struct {
  683. AttObj string `json:"attObj"`
  684. Error string `json:"error"`
  685. }
  686. type attestationObject struct {
  687. Format string `json:"fmt"`
  688. AttStatement map[string]any `json:"attStmt,omitempty"`
  689. }
  690. // TODO(bweeks): move attestation verification to a shared package.
  691. func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  692. // Update challenge with the payload
  693. ch.Payload = payload
  694. // Load authorization to store the key fingerprint.
  695. az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
  696. if err != nil {
  697. return WrapErrorISE(err, "error loading authorization")
  698. }
  699. // Parse payload.
  700. var p payloadType
  701. if err := json.Unmarshal(payload, &p); err != nil {
  702. return WrapErrorISE(err, "error unmarshalling JSON")
  703. }
  704. if p.Error != "" {
  705. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  706. "payload contained error: %v", p.Error))
  707. }
  708. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  709. if err != nil {
  710. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "failed base64 decoding attObj %q", p.AttObj))
  711. }
  712. if len(attObj) == 0 || bytes.Equal(attObj, []byte("{}")) {
  713. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj must not be empty"))
  714. }
  715. cborDecoderOptions := cbor.DecOptions{}
  716. cborDecoder, err := cborDecoderOptions.DecMode()
  717. if err != nil {
  718. return WrapErrorISE(err, "failed creating CBOR decoder")
  719. }
  720. if err := cborDecoder.Wellformed(attObj); err != nil {
  721. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj is not well formed CBOR: %v", err))
  722. }
  723. att := attestationObject{}
  724. if err := cborDecoder.Unmarshal(attObj, &att); err != nil {
  725. return WrapErrorISE(err, "failed unmarshalling CBOR")
  726. }
  727. format := att.Format
  728. prov := MustProvisionerFromContext(ctx)
  729. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(format)) {
  730. if format != "apple" && format != "step" && format != "tpm" && format != "android-key" {
  731. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  732. }
  733. return storeError(ctx, db, ch, true,
  734. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", format))
  735. }
  736. switch format {
  737. case "android-key":
  738. data, err := doAndroidKeyAttestationFormat(ctx, prov, ch, jwk, &att)
  739. if err != nil {
  740. if acmeError, ok := errors.AsType[*Error](err); ok {
  741. if acmeError.Status == 500 {
  742. return acmeError
  743. }
  744. return storeError(ctx, db, ch, true, acmeError)
  745. }
  746. return WrapErrorISE(err, "error validating attestation")
  747. }
  748. // Enforce hardware security level (TrustedEnvironment or StrongBox; Software not allowed)
  749. if data.Attestation.AttestationSecurityLevel < 1 {
  750. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "insufficient security level: %d", data.Attestation.AttestationSecurityLevel))
  751. }
  752. // Enforce hardware backed device serial
  753. if ch.Value != string(data.Attestation.TeeEnforced.AttestationIdSerial) {
  754. subproblem := NewSubproblemWithIdentifier(
  755. ErrorRejectedIdentifierType,
  756. Identifier{Type: "permanent-identifier", Value: ch.Value},
  757. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{string(data.Attestation.TeeEnforced.AttestationIdSerial)},
  758. )
  759. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  760. }
  761. // Update attestation key fingerprint to compare against the CSR
  762. az.Fingerprint = data.Fingerprint
  763. case "apple":
  764. data, err := doAppleAttestationFormat(ctx, prov, ch, &att)
  765. if err != nil {
  766. if acmeError, ok := errors.AsType[*Error](err); ok {
  767. if acmeError.Status == 500 {
  768. return acmeError
  769. }
  770. return storeError(ctx, db, ch, true, acmeError)
  771. }
  772. return WrapErrorISE(err, "error validating attestation")
  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. data, err := doStepAttestationFormat(ctx, prov, ch, jwk, &att)
  797. if err != nil {
  798. if acmeError, ok := errors.AsType[*Error](err); ok {
  799. if acmeError.Status == 500 {
  800. return acmeError
  801. }
  802. return storeError(ctx, db, ch, true, acmeError)
  803. }
  804. return WrapErrorISE(err, "error validating attestation")
  805. }
  806. // Validate the YubiKey serial number from the attestation
  807. // certificate with the challenged Order value.
  808. //
  809. // Note: We might want to use an external service for this.
  810. if data.SerialNumber != ch.Value {
  811. subproblem := NewSubproblemWithIdentifier(
  812. ErrorRejectedIdentifierType,
  813. Identifier{Type: "permanent-identifier", Value: ch.Value},
  814. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  815. )
  816. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  817. }
  818. // Update attestation key fingerprint to compare against the CSR
  819. az.Fingerprint = data.Fingerprint
  820. case "tpm":
  821. data, err := doTPMAttestationFormat(ctx, prov, ch, jwk, &att)
  822. if err != nil {
  823. if acmeError, ok := errors.AsType[*Error](err); ok {
  824. if acmeError.Status == 500 {
  825. return acmeError
  826. }
  827. return storeError(ctx, db, ch, true, acmeError)
  828. }
  829. return WrapErrorISE(err, "error validating attestation")
  830. }
  831. // TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
  832. // extracted from the AK certificate. This is currently the case for AK certs from the CLI, as we
  833. // haven't implemented a way for AK certs requested by the CLI to always contain the requested
  834. // PermanentIdentifier. Omitting the check below doesn't allow just any request, as the Order can
  835. // still fail if the challenge value isn't equal to the CSR subject.
  836. if len(data.PermanentIdentifiers) > 0 && !slices.Contains(data.PermanentIdentifiers, ch.Value) { // TODO(hs): add support for HardwareModuleName
  837. subproblem := NewSubproblemWithIdentifier(
  838. ErrorRejectedIdentifierType,
  839. Identifier{Type: "permanent-identifier", Value: ch.Value},
  840. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, data.PermanentIdentifiers,
  841. )
  842. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  843. }
  844. // Update attestation key fingerprint to compare against the CSR
  845. az.Fingerprint = data.Fingerprint
  846. default:
  847. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  848. }
  849. // Update and store the challenge.
  850. ch.Status = StatusValid
  851. ch.Error = nil
  852. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  853. ch.PayloadFormat = format
  854. // Store the fingerprint in the authorization.
  855. //
  856. // TODO: add method to update authorization and challenge atomically.
  857. if az.Fingerprint != "" {
  858. if err := db.UpdateAuthorization(ctx, az); err != nil {
  859. return WrapErrorISE(err, "error updating authorization")
  860. }
  861. }
  862. if err := db.UpdateChallenge(ctx, ch); err != nil {
  863. return WrapErrorISE(err, "error updating challenge")
  864. }
  865. return nil
  866. }
  867. var (
  868. oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
  869. )
  870. type tpmAttestationData struct {
  871. Certificate *x509.Certificate
  872. VerifiedChains [][]*x509.Certificate
  873. PermanentIdentifiers []string
  874. Fingerprint string
  875. }
  876. // coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
  877. // Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
  878. type coseAlgorithmIdentifier int32
  879. const (
  880. coseAlgES256 = coseAlgorithmIdentifier(-7)
  881. coseAlgRS256 = coseAlgorithmIdentifier(-257)
  882. coseAlgRS1 = coseAlgorithmIdentifier(-65535) // deprecated, but (still) often used in TPMs
  883. )
  884. func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
  885. ver, ok := att.AttStatement["ver"].(string)
  886. if !ok {
  887. return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
  888. }
  889. if ver != "2.0" {
  890. return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
  891. }
  892. x5c, ok := att.AttStatement["x5c"].([]any)
  893. if !ok {
  894. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  895. }
  896. if len(x5c) == 0 {
  897. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  898. }
  899. akCertBytes, ok := x5c[0].([]byte)
  900. if !ok {
  901. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  902. }
  903. akCert, err := x509.ParseCertificate(akCertBytes)
  904. if err != nil {
  905. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  906. }
  907. intermediates := x509.NewCertPool()
  908. for _, v := range x5c[1:] {
  909. intCertBytes, vok := v.([]byte)
  910. if !vok {
  911. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  912. }
  913. intCert, err := x509.ParseCertificate(intCertBytes)
  914. if err != nil {
  915. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  916. }
  917. intermediates.AddCert(intCert)
  918. }
  919. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  920. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  921. // but I doubt that will happen.
  922. if len(akCert.UnhandledCriticalExtensions) > 0 {
  923. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  924. for _, extOID := range akCert.UnhandledCriticalExtensions {
  925. if !extOID.Equal(oidSubjectAlternativeName) {
  926. // critical extensions other than the Subject Alternative Name remain unhandled
  927. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  928. }
  929. }
  930. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  931. }
  932. roots, ok := prov.GetAttestationRoots()
  933. if !ok {
  934. return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
  935. }
  936. // verify that the AK certificate was signed by a trusted root,
  937. // chained to by the intermediates provided by the client. As part
  938. // of building the verified certificate chain, the signature over the
  939. // AK certificate is checked to be a valid signature of one of the
  940. // provided intermediates. Signatures over the intermediates are in
  941. // turn also verified to be valid signatures from one of the trusted
  942. // roots.
  943. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  944. Roots: roots,
  945. Intermediates: intermediates,
  946. CurrentTime: time.Now().Truncate(time.Second),
  947. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  948. })
  949. if err != nil {
  950. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  951. }
  952. // validate additional AK certificate requirements
  953. if err := validateAKCertificate(akCert); err != nil {
  954. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
  955. }
  956. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  957. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  958. if err != nil {
  959. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
  960. }
  961. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  962. for i, pi := range sans.PermanentIdentifiers {
  963. permanentIdentifiers[i] = pi.Identifier
  964. }
  965. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  966. pubArea, ok := att.AttStatement["pubArea"].([]byte)
  967. if !ok {
  968. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
  969. }
  970. if len(pubArea) == 0 {
  971. return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
  972. }
  973. sig, ok := att.AttStatement["sig"].([]byte)
  974. if !ok {
  975. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
  976. }
  977. if len(sig) == 0 {
  978. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
  979. }
  980. certInfo, ok := att.AttStatement["certInfo"].([]byte)
  981. if !ok {
  982. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
  983. }
  984. if len(certInfo) == 0 {
  985. return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
  986. }
  987. alg, ok := att.AttStatement["alg"].(int64)
  988. if !ok {
  989. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
  990. }
  991. algI32, err := cast.SafeInt32(alg)
  992. if err != nil {
  993. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid alg %d in attestation statement", alg)
  994. }
  995. var hash crypto.Hash
  996. switch coseAlgorithmIdentifier(algI32) {
  997. case coseAlgRS256, coseAlgES256:
  998. hash = crypto.SHA256
  999. case coseAlgRS1:
  1000. hash = crypto.SHA1
  1001. default:
  1002. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
  1003. }
  1004. // recreate the generated key certification parameter values and verify
  1005. // the attested key using the public key of the AK.
  1006. certificationParameters := &attest.CertificationParameters{
  1007. Public: pubArea, // the public key that was attested
  1008. CreateAttestation: certInfo, // the attested properties of the key
  1009. CreateSignature: sig, // signature over the attested properties
  1010. }
  1011. verifyOpts := attest.VerifyOpts{
  1012. Public: akCert.PublicKey, // public key of the AK that attested the key
  1013. Hash: hash,
  1014. }
  1015. if err = certificationParameters.Verify(verifyOpts); err != nil {
  1016. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
  1017. }
  1018. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  1019. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  1020. if err != nil {
  1021. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
  1022. }
  1023. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1024. if err != nil {
  1025. return nil, WrapErrorISE(err, "failed creating key auth digest")
  1026. }
  1027. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  1028. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  1029. // within the encoded `certInfo` property of the attestation statement.
  1030. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  1031. return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
  1032. }
  1033. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  1034. pub, err := tpm2.DecodePublic(pubArea)
  1035. if err != nil {
  1036. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
  1037. }
  1038. publicKey, err := pub.Key()
  1039. if err != nil {
  1040. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
  1041. }
  1042. data := &tpmAttestationData{
  1043. Certificate: akCert,
  1044. VerifiedChains: verifiedChains,
  1045. PermanentIdentifiers: permanentIdentifiers,
  1046. }
  1047. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  1048. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1049. }
  1050. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  1051. return data, nil
  1052. }
  1053. var (
  1054. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  1055. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  1056. )
  1057. // validateAKCertificate validates the X.509 AK certificate to be
  1058. // in accordance with the required properties. The requirements come from:
  1059. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  1060. //
  1061. // - Version MUST be set to 3.
  1062. // - Subject field MUST be set to empty.
  1063. // - The Subject Alternative Name extension MUST be set as defined
  1064. // in [TPMv2-EK-Profile] section 3.2.9.
  1065. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  1066. // ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  1067. // - The Basic Constraints extension MUST have the CA component set to false.
  1068. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  1069. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  1070. // the status of many attestation certificates is available through metadata
  1071. // services. See, for example, the FIDO Metadata Service.
  1072. func validateAKCertificate(c *x509.Certificate) error {
  1073. if c.Version != 3 {
  1074. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  1075. }
  1076. if c.Subject.String() != "" {
  1077. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  1078. }
  1079. if c.IsCA {
  1080. return errors.New("AK certificate must not be a CA")
  1081. }
  1082. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  1083. return err
  1084. }
  1085. return validateAKCertificateSubjectAlternativeNames(c)
  1086. }
  1087. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  1088. // has TPM hardware details set.
  1089. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  1090. sans, err := x509util.ParseSubjectAlternativeNames(c)
  1091. if err != nil {
  1092. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  1093. }
  1094. details := sans.TPMHardwareDetails
  1095. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  1096. switch {
  1097. case manufacturer == "":
  1098. return errors.New("missing TPM manufacturer")
  1099. case model == "":
  1100. return errors.New("missing TPM model")
  1101. case version == "":
  1102. return errors.New("missing TPM version")
  1103. }
  1104. return nil
  1105. }
  1106. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  1107. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  1108. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  1109. var (
  1110. valid = false
  1111. ekus []asn1.ObjectIdentifier
  1112. )
  1113. for _, ext := range c.Extensions {
  1114. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  1115. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || len(ekus) == 0 || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  1116. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  1117. }
  1118. valid = true
  1119. }
  1120. }
  1121. if !valid {
  1122. return errors.New("AK certificate is missing Extended Key Usage extension")
  1123. }
  1124. return nil
  1125. }
  1126. // Apple Enterprise Attestation Root CA from
  1127. // https://www.apple.com/certificateauthority/private/
  1128. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  1129. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  1130. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  1131. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  1132. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  1133. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  1134. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  1135. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  1136. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  1137. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  1138. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  1139. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  1140. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  1141. -----END CERTIFICATE-----`
  1142. var (
  1143. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  1144. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  1145. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  1146. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  1147. )
  1148. type appleAttestationData struct {
  1149. Nonce []byte
  1150. SerialNumber string
  1151. UDID string
  1152. SEPVersion string
  1153. Certificate *x509.Certificate
  1154. Fingerprint string
  1155. }
  1156. func doAppleAttestationFormat(_ context.Context, prov Provisioner, _ *Challenge, att *attestationObject) (*appleAttestationData, error) {
  1157. // Use configured or default attestation roots if none is configured.
  1158. roots, ok := prov.GetAttestationRoots()
  1159. if !ok {
  1160. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  1161. if err != nil {
  1162. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  1163. }
  1164. roots = x509.NewCertPool()
  1165. roots.AddCert(root)
  1166. }
  1167. x5c, ok := att.AttStatement["x5c"].([]any)
  1168. if !ok {
  1169. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1170. }
  1171. if len(x5c) == 0 {
  1172. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  1173. }
  1174. der, ok := x5c[0].([]byte)
  1175. if !ok {
  1176. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1177. }
  1178. leaf, err := x509.ParseCertificate(der)
  1179. if err != nil {
  1180. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1181. }
  1182. intermediates := x509.NewCertPool()
  1183. for _, v := range x5c[1:] {
  1184. der, ok = v.([]byte)
  1185. if !ok {
  1186. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1187. }
  1188. cert, err := x509.ParseCertificate(der)
  1189. if err != nil {
  1190. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1191. }
  1192. intermediates.AddCert(cert)
  1193. }
  1194. if _, err := leaf.Verify(x509.VerifyOptions{
  1195. Intermediates: intermediates,
  1196. Roots: roots,
  1197. CurrentTime: time.Now().Truncate(time.Second),
  1198. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1199. }); err != nil {
  1200. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1201. }
  1202. data := &appleAttestationData{
  1203. Certificate: leaf,
  1204. }
  1205. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1206. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1207. }
  1208. for _, ext := range leaf.Extensions {
  1209. switch {
  1210. case ext.Id.Equal(oidAppleSerialNumber):
  1211. data.SerialNumber = string(ext.Value)
  1212. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  1213. data.UDID = string(ext.Value)
  1214. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  1215. data.SEPVersion = string(ext.Value)
  1216. case ext.Id.Equal(oidAppleNonce):
  1217. data.Nonce = ext.Value
  1218. }
  1219. }
  1220. return data, nil
  1221. }
  1222. // Android RSA Root CA
  1223. // https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate
  1224. var androidRSARootCA = `-----BEGIN CERTIFICATE-----
  1225. MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV
  1226. BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw
  1227. NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B
  1228. AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS
  1229. Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7
  1230. tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj
  1231. nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq
  1232. C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ
  1233. oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O
  1234. JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg
  1235. sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi
  1236. igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M
  1237. RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E
  1238. aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um
  1239. AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud
  1240. IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD
  1241. VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7
  1242. 174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC
  1243. W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G
  1244. tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx
  1245. oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG
  1246. 1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF
  1247. mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz
  1248. lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw
  1249. n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu
  1250. zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo
  1251. vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn
  1252. w1IdYIg2Wxg7yHcQZemFQg==
  1253. -----END CERTIFICATE-----`
  1254. // Android ECDSA (secp384r1) Root CA
  1255. var androidECDSARootCA = `-----BEGIN CERTIFICATE-----
  1256. MIICIjCCAaigAwIBAgIRAISp0Cl7DrWK5/8OgN52BgUwCgYIKoZIzj0EAwMwUjEc
  1257. MBoGA1UEAwwTS2V5IEF0dGVzdGF0aW9uIENBMTEQMA4GA1UECwwHQW5kcm9pZDET
  1258. MBEGA1UECgwKR29vZ2xlIExMQzELMAkGA1UEBhMCVVMwHhcNMjUwNzE3MjIzMjE4
  1259. WhcNMzUwNzE1MjIzMjE4WjBSMRwwGgYDVQQDDBNLZXkgQXR0ZXN0YXRpb24gQ0Ex
  1260. MRAwDgYDVQQLDAdBbmRyb2lkMRMwEQYDVQQKDApHb29nbGUgTExDMQswCQYDVQQG
  1261. EwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABCPaI3FO3z5bBQo8cuiEas4HjqCt
  1262. G/mLFfRT0MsIssPBEEU5Cfbt6sH5yOAxqEi5QagpU1yX4HwnGb7OtBYpDTB57uH5
  1263. Eczm34A5FNijV3s0/f0UPl7zbJcTx6xwqMIRq6NCMEAwDwYDVR0TAQH/BAUwAwEB
  1264. /zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFFIyuyz7RkOb3NaBqQ5lZuA0QepA
  1265. MAoGCCqGSM49BAMDA2gAMGUCMETfjPO/HwqReR2CS7p0ZWoD/LHs6hDi422opifH
  1266. EUaYLxwGlT9SLdjkVpz0UUOR5wIxAIoGyxGKRHVTpqpGRFiJtQEOOTp/+s1GcxeY
  1267. uR2zh/80lQyu9vAFCj6E4AXc+osmRg==
  1268. -----END CERTIFICATE-----`
  1269. // OID for Android Key Attestation
  1270. // https://source.android.com/docs/security/features/keystore/attestation#id-attestation
  1271. var oidAndroidAttestation = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 1, 17}
  1272. type androidKeyAttestationData struct {
  1273. Certificate *x509.Certificate
  1274. Fingerprint string
  1275. Attestation *attestation.KeyDescription
  1276. }
  1277. // findAndroidAttestationCert traverses the slice of [*x509.Certificate] from
  1278. // end to start (root -> intermediate -> leaf) to locate the certificate closest
  1279. // to the root carrying an Android Key Attestation extension.
  1280. //
  1281. // TODO(hs): implement the optional step of locating the provisioning information
  1282. // extension? That should immediately precede the cert with the key attestation
  1283. // extension.
  1284. func findAndroidAttestationCert(certs []*x509.Certificate) *x509.Certificate {
  1285. for _, cert := range slices.Backward(certs) {
  1286. for _, ext := range cert.Extensions {
  1287. if ext.Id.Equal(oidAndroidAttestation) {
  1288. return cert
  1289. }
  1290. }
  1291. }
  1292. return nil
  1293. }
  1294. // doAndroidKeyAttestationFormat handles ACME Device Attestation requests for
  1295. // the "android-key" attestation format. Its verification logic is based on
  1296. // the documentation at https://developer.android.com/privacy-and-security/security-key-attestation
  1297. //
  1298. // This function performs the below steps:
  1299. // - Verifies that the root public certificate is trustworthy and that each certificate signs
  1300. // the next certificate in the chain.
  1301. // - Checks each certificate's revocation status to ensure that none of the certificates have
  1302. // been revoked.
  1303. // - Find the nearest certificate to the root that contains the key attestation certificate
  1304. // extension.
  1305. // - Check the extension data that you've retrieved in the previous steps for consistency and
  1306. // compare with the set of values that you expect the hardware-backed key to contain.
  1307. func doAndroidKeyAttestationFormat(ctx context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*androidKeyAttestationData, error) {
  1308. acmeProv, ok := prov.(*provisioner.ACME)
  1309. if !ok {
  1310. return nil, NewErrorISE("provisioner in context is not an ACME provisioner")
  1311. }
  1312. roots, ok := prov.GetAttestationRoots()
  1313. if !ok {
  1314. rsaRoot, err := pemutil.ParseCertificate([]byte(androidRSARootCA))
  1315. if err != nil {
  1316. return nil, WrapErrorISE(err, "error parsing Android RSA root CA")
  1317. }
  1318. ecdsaRoot, err := pemutil.ParseCertificate([]byte(androidECDSARootCA))
  1319. if err != nil {
  1320. return nil, WrapErrorISE(err, "error parsing Android ECDSA root CA")
  1321. }
  1322. roots = x509.NewCertPool()
  1323. roots.AddCert(rsaRoot)
  1324. roots.AddCert(ecdsaRoot)
  1325. }
  1326. // extract x5c and verify certificate
  1327. x5c, ok := att.AttStatement["x5c"].([]any)
  1328. if !ok {
  1329. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1330. }
  1331. if len(x5c) == 0 {
  1332. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  1333. }
  1334. // Parse leaf, intermediates and root
  1335. intermediates := x509.NewCertPool()
  1336. var leaf, root *x509.Certificate
  1337. for i, v := range x5c {
  1338. der, dok := v.([]byte)
  1339. if !dok {
  1340. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c element is malformed")
  1341. }
  1342. cert, err := x509.ParseCertificate(der)
  1343. if err != nil {
  1344. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing certificate at index %d", i)
  1345. }
  1346. // Verify certificate serial number against CRL
  1347. revoked, err := acmeProv.IsAndroidCertificateRevoked(ctx, cert)
  1348. if err != nil {
  1349. return nil, WrapDetailedError(ErrorServerInternalType, err, "failed checking certificate revocation status")
  1350. }
  1351. if revoked {
  1352. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c element contains a revoked certificate")
  1353. }
  1354. switch i {
  1355. case 0: // leaf
  1356. leaf = cert
  1357. case len(x5c) - 1: // root
  1358. root = cert
  1359. default: // intermediates
  1360. intermediates.AddCert(cert)
  1361. }
  1362. }
  1363. // Require a leaf in the chain
  1364. if leaf == nil {
  1365. return nil, NewDetailedError(ErrorBadAttestationStatementType, "missing leaf certificate in x5c chain")
  1366. }
  1367. // Require a root in the chain
  1368. if root == nil {
  1369. return nil, NewDetailedError(ErrorBadAttestationStatementType, "missing root certificate in x5c chain")
  1370. }
  1371. // Verify the root is one of the trusted roots
  1372. _, err := root.Verify(x509.VerifyOptions{
  1373. Roots: roots,
  1374. CurrentTime: time.Now().Truncate(time.Second),
  1375. })
  1376. if err != nil {
  1377. return nil, NewDetailedError(ErrorBadAttestationStatementType, "root certificate in chain is not trusted")
  1378. }
  1379. // Validate the full chain including root as trust anchor
  1380. chains, err := leaf.Verify(x509.VerifyOptions{
  1381. Intermediates: intermediates,
  1382. Roots: roots,
  1383. CurrentTime: time.Now().Truncate(time.Second),
  1384. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1385. })
  1386. if err != nil {
  1387. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c chain verification failed")
  1388. }
  1389. switch {
  1390. case len(chains) == 0:
  1391. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c does not contain a valid certificate chain")
  1392. case len(chains) > 1:
  1393. // currently we strictly prohibit multiple valid signing chains
  1394. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c contains multiple (%d) valid certificate chains", len(chains))
  1395. }
  1396. // Get signature
  1397. sig, ok := att.AttStatement["sig"].([]byte)
  1398. if !ok {
  1399. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  1400. }
  1401. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1402. if err != nil {
  1403. return nil, err
  1404. }
  1405. // Find the attestation certificate
  1406. attCert := findAndroidAttestationCert(chains[0])
  1407. if attCert == nil {
  1408. return nil, NewDetailedError(ErrorBadAttestationStatementType, "no attestation certificate with OID 1.3.6.1.4.1.11129.2.1.17 found in the cert chain")
  1409. }
  1410. // Verify attestation statement sig
  1411. if err := validateAttestationSignature(attCert, keyAuth, sig); err != nil {
  1412. return nil, err
  1413. }
  1414. data := &androidKeyAttestationData{
  1415. Certificate: attCert,
  1416. }
  1417. if data.Fingerprint, err = keyutil.Fingerprint(attCert.PublicKey); err != nil {
  1418. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1419. }
  1420. for _, ext := range attCert.Extensions {
  1421. if !ext.Id.Equal(oidAndroidAttestation) {
  1422. continue
  1423. }
  1424. keyDesc, err := attestation.ParseExtension(ext.Value)
  1425. if err != nil {
  1426. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing attestation")
  1427. }
  1428. data.Attestation = keyDesc
  1429. break
  1430. }
  1431. // Validate key authorization
  1432. if string(data.Attestation.AttestationChallenge) != keyAuth {
  1433. return nil, NewDetailedError(ErrorBadAttestationStatementType, "challenge mismatch; expected %q, got %q", keyAuth, string(data.Attestation.AttestationChallenge))
  1434. }
  1435. return data, nil
  1436. }
  1437. // Yubico PIV Root CA Serial 263751
  1438. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  1439. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  1440. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  1441. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  1442. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  1443. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  1444. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  1445. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  1446. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  1447. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  1448. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  1449. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  1450. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  1451. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  1452. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  1453. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  1454. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  1455. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  1456. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  1457. -----END CERTIFICATE-----`
  1458. // Yubico Attestation Root 1 (YubiKey 5.7.4+)
  1459. // https://developers.yubico.com/PKI/yubico-ca-1.pem
  1460. const yubicoAttestationRootCA = `-----BEGIN CERTIFICATE-----
  1461. MIIDPjCCAiagAwIBAgIUXzeiEDJEOTt14F5n0o6Zf/bBwiUwDQYJKoZIhvcNAQEN
  1462. BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
  1463. MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowJDEiMCAGA1UEAwwZWXViaWNvIEF0
  1464. dGVzdGF0aW9uIFJvb3QgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
  1465. AMZ6/TxM8rIT+EaoPvG81ontMOo/2mQ2RBwJHS0QZcxVaNXvl12LUhBZ5LmiBScI
  1466. Zd1Rnx1od585h+/dhK7hEm7JAALkKKts1fO53KGNLZujz5h3wGncr4hyKF0G74b/
  1467. U3K9hE5mGND6zqYchCRAHfrYMYRDF4YL0X4D5nGdxvppAy6nkEmtWmMnwO3i0TAu
  1468. csrbE485HvGM4r0VpgVdJpvgQjiTJCTIq+D35hwtT8QDIv+nGvpcyi5wcIfCkzyC
  1469. imJukhYy6KoqNMKQEdpNiSOvWyDMTMt1bwCvEzpw91u+msUt4rj0efnO9s0ZOwdw
  1470. MRDnH4xgUl5ZLwrrPkfC1/0CAwEAAaNmMGQwHQYDVR0OBBYEFNLu71oijTptXCOX
  1471. PfKF1SbxJXuSMB8GA1UdIwQYMBaAFNLu71oijTptXCOXPfKF1SbxJXuSMBIGA1Ud
  1472. EwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBDQUAA4IB
  1473. AQC3IW/sgB9pZ8apJNjxuGoX+FkILks0wMNrdXL/coUvsrhzsvl6mePMrbGJByJ1
  1474. XnquB5sgcRENFxdQFma3mio8Upf1owM1ZreXrJ0mADG2BplqbJnxiyYa+R11reIF
  1475. TWeIhMNcZKsDZrFAyPuFjCWSQvJmNWe9mFRYFgNhXJKkXIb5H1XgEDlwiedYRM7V
  1476. olBNlld6pRFKlX8ust6OTMOeADl2xNF0m1LThSdeuXvDyC1g9+ILfz3S6OIYgc3i
  1477. roRcFD354g7rKfu67qFAw9gC4yi0xBTPrY95rh4/HqaUYCA/L8ldRk6H7Xk35D+W
  1478. Vpmq2Sh/xT5HiFuhf4wJb0bK
  1479. -----END CERTIFICATE-----`
  1480. var (
  1481. // serial number of the YubiKey, encoded as an integer.
  1482. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  1483. oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  1484. // custom Smallstep managed device extension carrying a device ID or serial number
  1485. oidStepManagedDevice = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 4}
  1486. )
  1487. type stepAttestationData struct {
  1488. Certificate *x509.Certificate
  1489. SerialNumber string
  1490. Fingerprint string
  1491. }
  1492. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  1493. // Use configured or default attestation roots if none is configured.
  1494. roots, ok := prov.GetAttestationRoots()
  1495. if !ok {
  1496. pivRoot, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  1497. if err != nil {
  1498. return nil, WrapErrorISE(err, "error parsing root ca")
  1499. }
  1500. attRoot, err := pemutil.ParseCertificate([]byte(yubicoAttestationRootCA))
  1501. if err != nil {
  1502. return nil, WrapErrorISE(err, "error parsing root ca")
  1503. }
  1504. roots = x509.NewCertPool()
  1505. roots.AddCert(pivRoot)
  1506. roots.AddCert(attRoot)
  1507. }
  1508. // Extract x5c and verify certificate
  1509. x5c, ok := att.AttStatement["x5c"].([]any)
  1510. if !ok {
  1511. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1512. }
  1513. if len(x5c) == 0 {
  1514. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  1515. }
  1516. der, ok := x5c[0].([]byte)
  1517. if !ok {
  1518. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1519. }
  1520. leaf, err := x509.ParseCertificate(der)
  1521. if err != nil {
  1522. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1523. }
  1524. intermediates := x509.NewCertPool()
  1525. for _, v := range x5c[1:] {
  1526. der, ok = v.([]byte)
  1527. if !ok {
  1528. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1529. }
  1530. cert, err := x509.ParseCertificate(der)
  1531. if err != nil {
  1532. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1533. }
  1534. intermediates.AddCert(cert)
  1535. }
  1536. if _, err := leaf.Verify(x509.VerifyOptions{
  1537. Intermediates: intermediates,
  1538. Roots: roots,
  1539. CurrentTime: time.Now().Truncate(time.Second),
  1540. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1541. }); err != nil {
  1542. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1543. }
  1544. // Verify proof of possession of private key validating the key
  1545. // authorization. Per recommendation at
  1546. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  1547. // signature is CBOR-encoded.
  1548. var sig []byte
  1549. csig, ok := att.AttStatement["sig"].([]byte)
  1550. if !ok {
  1551. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  1552. }
  1553. if err := cbor.Unmarshal(csig, &sig); err != nil {
  1554. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  1555. }
  1556. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1557. if err != nil {
  1558. return nil, err
  1559. }
  1560. // Verify attestation statement sig
  1561. if err := validateAttestationSignature(leaf, keyAuth, sig); err != nil {
  1562. return nil, err
  1563. }
  1564. // Parse attestation data:
  1565. // TODO(mariano): add support for other extensions.
  1566. data := &stepAttestationData{
  1567. Certificate: leaf,
  1568. }
  1569. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1570. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1571. }
  1572. if data.SerialNumber, err = searchSerialNumber(leaf); err != nil {
  1573. return nil, WrapErrorISE(err, "error finding serial number")
  1574. }
  1575. return data, nil
  1576. }
  1577. // validateAttestationSignature verifies that sig is a signature of the key
  1578. // authorization made with the private key of the given attestation certificate.
  1579. func validateAttestationSignature(cert *x509.Certificate, keyAuth string, sig []byte) error {
  1580. switch pub := cert.PublicKey.(type) {
  1581. case *ecdsa.PublicKey:
  1582. if pub.Curve != elliptic.P256() {
  1583. return NewDetailedError(ErrorBadAttestationStatementType, "unsupported elliptic curve %s", pub.Curve)
  1584. }
  1585. sum := sha256.Sum256([]byte(keyAuth))
  1586. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  1587. return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
  1588. }
  1589. case *rsa.PublicKey:
  1590. sum := sha256.Sum256([]byte(keyAuth))
  1591. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  1592. return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
  1593. }
  1594. case ed25519.PublicKey:
  1595. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  1596. return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
  1597. }
  1598. case *mldsa.PublicKey:
  1599. if err := mldsa.Verify(pub, []byte(keyAuth), sig, nil); err != nil {
  1600. return NewDetailedError(ErrorBadAttestationStatementType, "failed validating signature")
  1601. }
  1602. default:
  1603. return NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  1604. }
  1605. return nil
  1606. }
  1607. // searchSerialNumber searches the certificate extensions, looking for a serial
  1608. // number encoded in one of them. It is not guaranteed that a certificate contains
  1609. // an extension carrying a serial number, so the result can be empty.
  1610. func searchSerialNumber(cert *x509.Certificate) (string, error) {
  1611. for _, ext := range cert.Extensions {
  1612. if ext.Id.Equal(oidYubicoSerialNumber) {
  1613. var serialNumber int
  1614. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  1615. if err != nil || len(rest) > 0 {
  1616. return "", WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1617. }
  1618. return strconv.Itoa(serialNumber), nil
  1619. }
  1620. if ext.Id.Equal(oidStepManagedDevice) {
  1621. type stepManagedDevice struct {
  1622. DeviceID string
  1623. }
  1624. var md stepManagedDevice
  1625. rest, err := asn1.Unmarshal(ext.Value, &md)
  1626. if err != nil || len(rest) > 0 {
  1627. return "", WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1628. }
  1629. return md.DeviceID, nil
  1630. }
  1631. }
  1632. return "", nil
  1633. }
  1634. // serverName determines the SNI HostName to set based on an acme.Challenge
  1635. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  1636. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  1637. // It also references TLS Extensions [RFC6066].
  1638. func serverName(ch *Challenge) string {
  1639. if ip := net.ParseIP(ch.Value); ip != nil {
  1640. return reverseAddr(ip)
  1641. }
  1642. return ch.Value
  1643. }
  1644. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  1645. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  1646. // to parse the IP address.
  1647. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  1648. func reverseAddr(ip net.IP) (arpa string) {
  1649. if ip.To4() != nil {
  1650. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  1651. }
  1652. // Must be IPv6
  1653. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  1654. // Add it, in reverse, to the buffer
  1655. for _, v := range slices.Backward(ip) {
  1656. buf = append(buf, hexit[v&0xF],
  1657. '.',
  1658. hexit[v>>4],
  1659. '.')
  1660. }
  1661. // Append "ip6.arpa." and return (buf already has the final .)
  1662. buf = append(buf, "ip6.arpa."...)
  1663. return string(buf)
  1664. }
  1665. // Convert unsigned integer to decimal string.
  1666. // Implementation taken from https://golang.org/src/net/parse.go
  1667. func uitoa(val uint) string {
  1668. if val == 0 { // avoid string allocation
  1669. return "0"
  1670. }
  1671. var buf [20]byte // big enough for 64bit value base 10
  1672. i := len(buf) - 1
  1673. for val >= 10 {
  1674. v := val / 10
  1675. buf[i] = byte('0' + val - v*10) //nolint:gosec // val - v*10 is always 0-9
  1676. i--
  1677. val = v
  1678. }
  1679. // val < 10
  1680. buf[i] = byte('0' + val)
  1681. return string(buf[i:])
  1682. }
  1683. const hexit = "0123456789abcdef"
  1684. // KeyAuthorization creates the ACME key authorization value from a token
  1685. // and a jwk.
  1686. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  1687. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  1688. if err != nil {
  1689. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  1690. }
  1691. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  1692. return fmt.Sprintf("%s.%s", token, encPrint), nil
  1693. }
  1694. // storeError the given error to an ACME error and saves using the DB interface.
  1695. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  1696. ch.Error = err
  1697. if markInvalid {
  1698. ch.Status = StatusInvalid
  1699. }
  1700. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1701. return WrapErrorISE(err, "failure saving error to acme challenge")
  1702. }
  1703. return nil
  1704. }