challenge.go 55 KB

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