challenge.go 62 KB

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