challenge.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  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 uint8(v.Uint()) //nolint:gosec // handled by checking its type
  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. // Load authorization to store the key fingerprint.
  695. az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
  696. if err != nil {
  697. return WrapErrorISE(err, "error loading authorization")
  698. }
  699. // Parse payload.
  700. var p payloadType
  701. if err := json.Unmarshal(payload, &p); err != nil {
  702. return WrapErrorISE(err, "error unmarshalling JSON")
  703. }
  704. if p.Error != "" {
  705. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  706. "payload contained error: %v", p.Error))
  707. }
  708. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  709. if err != nil {
  710. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "failed base64 decoding attObj %q", p.AttObj))
  711. }
  712. if len(attObj) == 0 || bytes.Equal(attObj, []byte("{}")) {
  713. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj must not be empty"))
  714. }
  715. cborDecoderOptions := cbor.DecOptions{}
  716. cborDecoder, err := cborDecoderOptions.DecMode()
  717. if err != nil {
  718. return WrapErrorISE(err, "failed creating CBOR decoder")
  719. }
  720. if err := cborDecoder.Wellformed(attObj); err != nil {
  721. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "attObj is not well formed CBOR: %v", err))
  722. }
  723. att := attestationObject{}
  724. if err := cborDecoder.Unmarshal(attObj, &att); err != nil {
  725. return WrapErrorISE(err, "failed unmarshalling CBOR")
  726. }
  727. format := att.Format
  728. prov := MustProvisionerFromContext(ctx)
  729. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(format)) {
  730. if format != "apple" && format != "step" && format != "tpm" {
  731. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  732. }
  733. return storeError(ctx, db, ch, true,
  734. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", format))
  735. }
  736. switch format {
  737. case "apple":
  738. data, err := doAppleAttestationFormat(ctx, prov, ch, &att)
  739. if err != nil {
  740. var acmeError *Error
  741. if errors.As(err, &acmeError) {
  742. if acmeError.Status == 500 {
  743. return acmeError
  744. }
  745. return storeError(ctx, db, ch, true, acmeError)
  746. }
  747. return WrapErrorISE(err, "error validating attestation")
  748. }
  749. // Validate nonce with SHA-256 of the token.
  750. if len(data.Nonce) != 0 {
  751. sum := sha256.Sum256([]byte(ch.Token))
  752. if subtle.ConstantTimeCompare(data.Nonce, sum[:]) != 1 {
  753. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "challenge token does not match"))
  754. }
  755. }
  756. // Validate Apple's ClientIdentifier (Identifier.Value) with device
  757. // identifiers.
  758. //
  759. // Note: We might want to use an external service for this.
  760. if data.UDID != ch.Value && data.SerialNumber != ch.Value {
  761. subproblem := NewSubproblemWithIdentifier(
  762. ErrorRejectedIdentifierType,
  763. Identifier{Type: "permanent-identifier", Value: ch.Value},
  764. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{data.UDID, data.SerialNumber},
  765. )
  766. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  767. }
  768. // Update attestation key fingerprint to compare against the CSR
  769. az.Fingerprint = data.Fingerprint
  770. case "step":
  771. data, err := doStepAttestationFormat(ctx, prov, ch, jwk, &att)
  772. if err != nil {
  773. var acmeError *Error
  774. if errors.As(err, &acmeError) {
  775. if acmeError.Status == 500 {
  776. return acmeError
  777. }
  778. return storeError(ctx, db, ch, true, acmeError)
  779. }
  780. return WrapErrorISE(err, "error validating attestation")
  781. }
  782. // Validate the YubiKey serial number from the attestation
  783. // certificate with the challenged Order value.
  784. //
  785. // Note: We might want to use an external service for this.
  786. if data.SerialNumber != ch.Value {
  787. subproblem := NewSubproblemWithIdentifier(
  788. ErrorRejectedIdentifierType,
  789. Identifier{Type: "permanent-identifier", Value: ch.Value},
  790. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  791. )
  792. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  793. }
  794. // Update attestation key fingerprint to compare against the CSR
  795. az.Fingerprint = data.Fingerprint
  796. case "tpm":
  797. data, err := doTPMAttestationFormat(ctx, prov, ch, jwk, &att)
  798. if err != nil {
  799. var acmeError *Error
  800. if errors.As(err, &acmeError) {
  801. if acmeError.Status == 500 {
  802. return acmeError
  803. }
  804. return storeError(ctx, db, ch, true, acmeError)
  805. }
  806. return WrapErrorISE(err, "error validating attestation")
  807. }
  808. // TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
  809. // extracted from the AK certificate. This is currently the case for AK certs from the CLI, as we
  810. // haven't implemented a way for AK certs requested by the CLI to always contain the requested
  811. // PermanentIdentifier. Omitting the check below doesn't allow just any request, as the Order can
  812. // still fail if the challenge value isn't equal to the CSR subject.
  813. if len(data.PermanentIdentifiers) > 0 && !slices.Contains(data.PermanentIdentifiers, ch.Value) { // TODO(hs): add support for HardwareModuleName
  814. subproblem := NewSubproblemWithIdentifier(
  815. ErrorRejectedIdentifierType,
  816. Identifier{Type: "permanent-identifier", Value: ch.Value},
  817. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, data.PermanentIdentifiers,
  818. )
  819. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  820. }
  821. // Update attestation key fingerprint to compare against the CSR
  822. az.Fingerprint = data.Fingerprint
  823. default:
  824. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  825. }
  826. // Update and store the challenge.
  827. ch.Status = StatusValid
  828. ch.Error = nil
  829. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  830. ch.Payload = payload
  831. ch.PayloadFormat = format
  832. // Store the fingerprint in the authorization.
  833. //
  834. // TODO: add method to update authorization and challenge atomically.
  835. if az.Fingerprint != "" {
  836. if err := db.UpdateAuthorization(ctx, az); err != nil {
  837. return WrapErrorISE(err, "error updating authorization")
  838. }
  839. }
  840. if err := db.UpdateChallenge(ctx, ch); err != nil {
  841. return WrapErrorISE(err, "error updating challenge")
  842. }
  843. return nil
  844. }
  845. var (
  846. oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
  847. )
  848. type tpmAttestationData struct {
  849. Certificate *x509.Certificate
  850. VerifiedChains [][]*x509.Certificate
  851. PermanentIdentifiers []string
  852. Fingerprint string
  853. }
  854. // coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
  855. // Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
  856. type coseAlgorithmIdentifier int32
  857. const (
  858. coseAlgES256 = coseAlgorithmIdentifier(-7)
  859. coseAlgRS256 = coseAlgorithmIdentifier(-257)
  860. coseAlgRS1 = coseAlgorithmIdentifier(-65535) // deprecated, but (still) often used in TPMs
  861. )
  862. func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
  863. ver, ok := att.AttStatement["ver"].(string)
  864. if !ok {
  865. return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
  866. }
  867. if ver != "2.0" {
  868. return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
  869. }
  870. x5c, ok := att.AttStatement["x5c"].([]interface{})
  871. if !ok {
  872. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  873. }
  874. if len(x5c) == 0 {
  875. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  876. }
  877. akCertBytes, ok := x5c[0].([]byte)
  878. if !ok {
  879. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  880. }
  881. akCert, err := x509.ParseCertificate(akCertBytes)
  882. if err != nil {
  883. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  884. }
  885. intermediates := x509.NewCertPool()
  886. for _, v := range x5c[1:] {
  887. intCertBytes, vok := v.([]byte)
  888. if !vok {
  889. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  890. }
  891. intCert, err := x509.ParseCertificate(intCertBytes)
  892. if err != nil {
  893. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  894. }
  895. intermediates.AddCert(intCert)
  896. }
  897. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  898. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  899. // but I doubt that will happen.
  900. if len(akCert.UnhandledCriticalExtensions) > 0 {
  901. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  902. for _, extOID := range akCert.UnhandledCriticalExtensions {
  903. if !extOID.Equal(oidSubjectAlternativeName) {
  904. // critical extensions other than the Subject Alternative Name remain unhandled
  905. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  906. }
  907. }
  908. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  909. }
  910. roots, ok := prov.GetAttestationRoots()
  911. if !ok {
  912. return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
  913. }
  914. // verify that the AK certificate was signed by a trusted root,
  915. // chained to by the intermediates provided by the client. As part
  916. // of building the verified certificate chain, the signature over the
  917. // AK certificate is checked to be a valid signature of one of the
  918. // provided intermediates. Signatures over the intermediates are in
  919. // turn also verified to be valid signatures from one of the trusted
  920. // roots.
  921. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  922. Roots: roots,
  923. Intermediates: intermediates,
  924. CurrentTime: time.Now().Truncate(time.Second),
  925. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  926. })
  927. if err != nil {
  928. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  929. }
  930. // validate additional AK certificate requirements
  931. if err := validateAKCertificate(akCert); err != nil {
  932. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
  933. }
  934. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  935. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  936. if err != nil {
  937. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
  938. }
  939. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  940. for i, pi := range sans.PermanentIdentifiers {
  941. permanentIdentifiers[i] = pi.Identifier
  942. }
  943. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  944. pubArea, ok := att.AttStatement["pubArea"].([]byte)
  945. if !ok {
  946. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
  947. }
  948. if len(pubArea) == 0 {
  949. return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
  950. }
  951. sig, ok := att.AttStatement["sig"].([]byte)
  952. if !ok {
  953. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
  954. }
  955. if len(sig) == 0 {
  956. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
  957. }
  958. certInfo, ok := att.AttStatement["certInfo"].([]byte)
  959. if !ok {
  960. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
  961. }
  962. if len(certInfo) == 0 {
  963. return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
  964. }
  965. alg, ok := att.AttStatement["alg"].(int64)
  966. if !ok {
  967. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
  968. }
  969. algI32, err := cast.SafeInt32(alg)
  970. if err != nil {
  971. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid alg %d in attestation statement", alg)
  972. }
  973. var hash crypto.Hash
  974. switch coseAlgorithmIdentifier(algI32) {
  975. case coseAlgRS256, coseAlgES256:
  976. hash = crypto.SHA256
  977. case coseAlgRS1:
  978. hash = crypto.SHA1
  979. default:
  980. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
  981. }
  982. // recreate the generated key certification parameter values and verify
  983. // the attested key using the public key of the AK.
  984. certificationParameters := &attest.CertificationParameters{
  985. Public: pubArea, // the public key that was attested
  986. CreateAttestation: certInfo, // the attested properties of the key
  987. CreateSignature: sig, // signature over the attested properties
  988. }
  989. verifyOpts := attest.VerifyOpts{
  990. Public: akCert.PublicKey, // public key of the AK that attested the key
  991. Hash: hash,
  992. }
  993. if err = certificationParameters.Verify(verifyOpts); err != nil {
  994. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
  995. }
  996. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  997. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  998. if err != nil {
  999. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
  1000. }
  1001. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1002. if err != nil {
  1003. return nil, WrapErrorISE(err, "failed creating key auth digest")
  1004. }
  1005. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  1006. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  1007. // within the encoded `certInfo` property of the attestation statement.
  1008. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  1009. return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
  1010. }
  1011. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  1012. pub, err := tpm2.DecodePublic(pubArea)
  1013. if err != nil {
  1014. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
  1015. }
  1016. publicKey, err := pub.Key()
  1017. if err != nil {
  1018. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
  1019. }
  1020. data := &tpmAttestationData{
  1021. Certificate: akCert,
  1022. VerifiedChains: verifiedChains,
  1023. PermanentIdentifiers: permanentIdentifiers,
  1024. }
  1025. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  1026. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1027. }
  1028. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  1029. return data, nil
  1030. }
  1031. var (
  1032. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  1033. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  1034. )
  1035. // validateAKCertificate validates the X.509 AK certificate to be
  1036. // in accordance with the required properties. The requirements come from:
  1037. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  1038. //
  1039. // - Version MUST be set to 3.
  1040. // - Subject field MUST be set to empty.
  1041. // - The Subject Alternative Name extension MUST be set as defined
  1042. // in [TPMv2-EK-Profile] section 3.2.9.
  1043. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  1044. // ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  1045. // - The Basic Constraints extension MUST have the CA component set to false.
  1046. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  1047. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  1048. // the status of many attestation certificates is available through metadata
  1049. // services. See, for example, the FIDO Metadata Service.
  1050. func validateAKCertificate(c *x509.Certificate) error {
  1051. if c.Version != 3 {
  1052. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  1053. }
  1054. if c.Subject.String() != "" {
  1055. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  1056. }
  1057. if c.IsCA {
  1058. return errors.New("AK certificate must not be a CA")
  1059. }
  1060. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  1061. return err
  1062. }
  1063. return validateAKCertificateSubjectAlternativeNames(c)
  1064. }
  1065. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  1066. // has TPM hardware details set.
  1067. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  1068. sans, err := x509util.ParseSubjectAlternativeNames(c)
  1069. if err != nil {
  1070. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  1071. }
  1072. details := sans.TPMHardwareDetails
  1073. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  1074. switch {
  1075. case manufacturer == "":
  1076. return errors.New("missing TPM manufacturer")
  1077. case model == "":
  1078. return errors.New("missing TPM model")
  1079. case version == "":
  1080. return errors.New("missing TPM version")
  1081. }
  1082. return nil
  1083. }
  1084. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  1085. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  1086. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  1087. var (
  1088. valid = false
  1089. ekus []asn1.ObjectIdentifier
  1090. )
  1091. for _, ext := range c.Extensions {
  1092. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  1093. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  1094. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  1095. }
  1096. valid = true
  1097. }
  1098. }
  1099. if !valid {
  1100. return errors.New("AK certificate is missing Extended Key Usage extension")
  1101. }
  1102. return nil
  1103. }
  1104. // Apple Enterprise Attestation Root CA from
  1105. // https://www.apple.com/certificateauthority/private/
  1106. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  1107. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  1108. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  1109. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  1110. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  1111. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  1112. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  1113. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  1114. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  1115. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  1116. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  1117. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  1118. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  1119. -----END CERTIFICATE-----`
  1120. var (
  1121. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  1122. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  1123. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  1124. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  1125. )
  1126. type appleAttestationData struct {
  1127. Nonce []byte
  1128. SerialNumber string
  1129. UDID string
  1130. SEPVersion string
  1131. Certificate *x509.Certificate
  1132. Fingerprint string
  1133. }
  1134. func doAppleAttestationFormat(_ context.Context, prov Provisioner, _ *Challenge, att *attestationObject) (*appleAttestationData, error) {
  1135. // Use configured or default attestation roots if none is configured.
  1136. roots, ok := prov.GetAttestationRoots()
  1137. if !ok {
  1138. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  1139. if err != nil {
  1140. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  1141. }
  1142. roots = x509.NewCertPool()
  1143. roots.AddCert(root)
  1144. }
  1145. x5c, ok := att.AttStatement["x5c"].([]interface{})
  1146. if !ok {
  1147. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1148. }
  1149. if len(x5c) == 0 {
  1150. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  1151. }
  1152. der, ok := x5c[0].([]byte)
  1153. if !ok {
  1154. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1155. }
  1156. leaf, err := x509.ParseCertificate(der)
  1157. if err != nil {
  1158. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1159. }
  1160. intermediates := x509.NewCertPool()
  1161. for _, v := range x5c[1:] {
  1162. der, ok = v.([]byte)
  1163. if !ok {
  1164. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1165. }
  1166. cert, err := x509.ParseCertificate(der)
  1167. if err != nil {
  1168. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1169. }
  1170. intermediates.AddCert(cert)
  1171. }
  1172. if _, err := leaf.Verify(x509.VerifyOptions{
  1173. Intermediates: intermediates,
  1174. Roots: roots,
  1175. CurrentTime: time.Now().Truncate(time.Second),
  1176. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1177. }); err != nil {
  1178. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1179. }
  1180. data := &appleAttestationData{
  1181. Certificate: leaf,
  1182. }
  1183. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1184. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1185. }
  1186. for _, ext := range leaf.Extensions {
  1187. switch {
  1188. case ext.Id.Equal(oidAppleSerialNumber):
  1189. data.SerialNumber = string(ext.Value)
  1190. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  1191. data.UDID = string(ext.Value)
  1192. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  1193. data.SEPVersion = string(ext.Value)
  1194. case ext.Id.Equal(oidAppleNonce):
  1195. data.Nonce = ext.Value
  1196. }
  1197. }
  1198. return data, nil
  1199. }
  1200. // Yubico PIV Root CA Serial 263751
  1201. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  1202. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  1203. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  1204. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  1205. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  1206. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  1207. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  1208. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  1209. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  1210. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  1211. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  1212. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  1213. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  1214. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  1215. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  1216. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  1217. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  1218. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  1219. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  1220. -----END CERTIFICATE-----`
  1221. // Yubico Attestation Root 1 (YubiKey 5.7.4+)
  1222. // https://developers.yubico.com/PKI/yubico-ca-1.pem
  1223. const yubicoAttestationRootCA = `-----BEGIN CERTIFICATE-----
  1224. MIIDPjCCAiagAwIBAgIUXzeiEDJEOTt14F5n0o6Zf/bBwiUwDQYJKoZIhvcNAQEN
  1225. BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy
  1226. MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowJDEiMCAGA1UEAwwZWXViaWNvIEF0
  1227. dGVzdGF0aW9uIFJvb3QgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
  1228. AMZ6/TxM8rIT+EaoPvG81ontMOo/2mQ2RBwJHS0QZcxVaNXvl12LUhBZ5LmiBScI
  1229. Zd1Rnx1od585h+/dhK7hEm7JAALkKKts1fO53KGNLZujz5h3wGncr4hyKF0G74b/
  1230. U3K9hE5mGND6zqYchCRAHfrYMYRDF4YL0X4D5nGdxvppAy6nkEmtWmMnwO3i0TAu
  1231. csrbE485HvGM4r0VpgVdJpvgQjiTJCTIq+D35hwtT8QDIv+nGvpcyi5wcIfCkzyC
  1232. imJukhYy6KoqNMKQEdpNiSOvWyDMTMt1bwCvEzpw91u+msUt4rj0efnO9s0ZOwdw
  1233. MRDnH4xgUl5ZLwrrPkfC1/0CAwEAAaNmMGQwHQYDVR0OBBYEFNLu71oijTptXCOX
  1234. PfKF1SbxJXuSMB8GA1UdIwQYMBaAFNLu71oijTptXCOXPfKF1SbxJXuSMBIGA1Ud
  1235. EwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBDQUAA4IB
  1236. AQC3IW/sgB9pZ8apJNjxuGoX+FkILks0wMNrdXL/coUvsrhzsvl6mePMrbGJByJ1
  1237. XnquB5sgcRENFxdQFma3mio8Upf1owM1ZreXrJ0mADG2BplqbJnxiyYa+R11reIF
  1238. TWeIhMNcZKsDZrFAyPuFjCWSQvJmNWe9mFRYFgNhXJKkXIb5H1XgEDlwiedYRM7V
  1239. olBNlld6pRFKlX8ust6OTMOeADl2xNF0m1LThSdeuXvDyC1g9+ILfz3S6OIYgc3i
  1240. roRcFD354g7rKfu67qFAw9gC4yi0xBTPrY95rh4/HqaUYCA/L8ldRk6H7Xk35D+W
  1241. Vpmq2Sh/xT5HiFuhf4wJb0bK
  1242. -----END CERTIFICATE-----`
  1243. var (
  1244. // serial number of the YubiKey, encoded as an integer.
  1245. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  1246. oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  1247. // custom Smallstep managed device extension carrying a device ID or serial number
  1248. oidStepManagedDevice = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 4}
  1249. )
  1250. type stepAttestationData struct {
  1251. Certificate *x509.Certificate
  1252. SerialNumber string
  1253. Fingerprint string
  1254. }
  1255. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  1256. // Use configured or default attestation roots if none is configured.
  1257. roots, ok := prov.GetAttestationRoots()
  1258. if !ok {
  1259. pivRoot, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  1260. if err != nil {
  1261. return nil, WrapErrorISE(err, "error parsing root ca")
  1262. }
  1263. attRoot, err := pemutil.ParseCertificate([]byte(yubicoAttestationRootCA))
  1264. if err != nil {
  1265. return nil, WrapErrorISE(err, "error parsing root ca")
  1266. }
  1267. roots = x509.NewCertPool()
  1268. roots.AddCert(pivRoot)
  1269. roots.AddCert(attRoot)
  1270. }
  1271. // Extract x5c and verify certificate
  1272. x5c, ok := att.AttStatement["x5c"].([]interface{})
  1273. if !ok {
  1274. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1275. }
  1276. if len(x5c) == 0 {
  1277. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  1278. }
  1279. der, ok := x5c[0].([]byte)
  1280. if !ok {
  1281. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1282. }
  1283. leaf, err := x509.ParseCertificate(der)
  1284. if err != nil {
  1285. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1286. }
  1287. intermediates := x509.NewCertPool()
  1288. for _, v := range x5c[1:] {
  1289. der, ok = v.([]byte)
  1290. if !ok {
  1291. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1292. }
  1293. cert, err := x509.ParseCertificate(der)
  1294. if err != nil {
  1295. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1296. }
  1297. intermediates.AddCert(cert)
  1298. }
  1299. if _, err := leaf.Verify(x509.VerifyOptions{
  1300. Intermediates: intermediates,
  1301. Roots: roots,
  1302. CurrentTime: time.Now().Truncate(time.Second),
  1303. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1304. }); err != nil {
  1305. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1306. }
  1307. // Verify proof of possession of private key validating the key
  1308. // authorization. Per recommendation at
  1309. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  1310. // signature is CBOR-encoded.
  1311. var sig []byte
  1312. csig, ok := att.AttStatement["sig"].([]byte)
  1313. if !ok {
  1314. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  1315. }
  1316. if err := cbor.Unmarshal(csig, &sig); err != nil {
  1317. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  1318. }
  1319. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1320. if err != nil {
  1321. return nil, err
  1322. }
  1323. switch pub := leaf.PublicKey.(type) {
  1324. case *ecdsa.PublicKey:
  1325. if pub.Curve != elliptic.P256() {
  1326. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  1327. }
  1328. sum := sha256.Sum256([]byte(keyAuth))
  1329. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  1330. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1331. }
  1332. case *rsa.PublicKey:
  1333. sum := sha256.Sum256([]byte(keyAuth))
  1334. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  1335. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1336. }
  1337. case ed25519.PublicKey:
  1338. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  1339. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1340. }
  1341. default:
  1342. return nil, NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  1343. }
  1344. // Parse attestation data:
  1345. // TODO(mariano): add support for other extensions.
  1346. data := &stepAttestationData{
  1347. Certificate: leaf,
  1348. }
  1349. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1350. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1351. }
  1352. if data.SerialNumber, err = searchSerialNumber(leaf); err != nil {
  1353. return nil, WrapErrorISE(err, "error finding serial number")
  1354. }
  1355. return data, nil
  1356. }
  1357. // searchSerialNumber searches the certificate extensions, looking for a serial
  1358. // number encoded in one of them. It is not guaranteed that a certificate contains
  1359. // an extension carrying a serial number, so the result can be empty.
  1360. func searchSerialNumber(cert *x509.Certificate) (string, error) {
  1361. for _, ext := range cert.Extensions {
  1362. if ext.Id.Equal(oidYubicoSerialNumber) {
  1363. var serialNumber int
  1364. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  1365. if err != nil || len(rest) > 0 {
  1366. return "", WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1367. }
  1368. return strconv.Itoa(serialNumber), nil
  1369. }
  1370. if ext.Id.Equal(oidStepManagedDevice) {
  1371. type stepManagedDevice struct {
  1372. DeviceID string
  1373. }
  1374. var md stepManagedDevice
  1375. rest, err := asn1.Unmarshal(ext.Value, &md)
  1376. if err != nil || len(rest) > 0 {
  1377. return "", WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1378. }
  1379. return md.DeviceID, nil
  1380. }
  1381. }
  1382. return "", nil
  1383. }
  1384. // serverName determines the SNI HostName to set based on an acme.Challenge
  1385. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  1386. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  1387. // It also references TLS Extensions [RFC6066].
  1388. func serverName(ch *Challenge) string {
  1389. if ip := net.ParseIP(ch.Value); ip != nil {
  1390. return reverseAddr(ip)
  1391. }
  1392. return ch.Value
  1393. }
  1394. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  1395. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  1396. // to parse the IP address.
  1397. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  1398. func reverseAddr(ip net.IP) (arpa string) {
  1399. if ip.To4() != nil {
  1400. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  1401. }
  1402. // Must be IPv6
  1403. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  1404. // Add it, in reverse, to the buffer
  1405. for i := len(ip) - 1; i >= 0; i-- {
  1406. v := ip[i]
  1407. buf = append(buf, hexit[v&0xF],
  1408. '.',
  1409. hexit[v>>4],
  1410. '.')
  1411. }
  1412. // Append "ip6.arpa." and return (buf already has the final .)
  1413. buf = append(buf, "ip6.arpa."...)
  1414. return string(buf)
  1415. }
  1416. // Convert unsigned integer to decimal string.
  1417. // Implementation taken from https://golang.org/src/net/parse.go
  1418. func uitoa(val uint) string {
  1419. if val == 0 { // avoid string allocation
  1420. return "0"
  1421. }
  1422. var buf [20]byte // big enough for 64bit value base 10
  1423. i := len(buf) - 1
  1424. for val >= 10 {
  1425. v := val / 10
  1426. buf[i] = byte('0' + val - v*10)
  1427. i--
  1428. val = v
  1429. }
  1430. // val < 10
  1431. buf[i] = byte('0' + val)
  1432. return string(buf[i:])
  1433. }
  1434. const hexit = "0123456789abcdef"
  1435. // KeyAuthorization creates the ACME key authorization value from a token
  1436. // and a jwk.
  1437. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  1438. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  1439. if err != nil {
  1440. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  1441. }
  1442. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  1443. return fmt.Sprintf("%s.%s", token, encPrint), nil
  1444. }
  1445. // storeError the given error to an ACME error and saves using the DB interface.
  1446. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  1447. ch.Error = err
  1448. if markInvalid {
  1449. ch.Status = StatusInvalid
  1450. }
  1451. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1452. return WrapErrorISE(err, "failure saving error to acme challenge")
  1453. }
  1454. return nil
  1455. }