challenge.go 57 KB

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