challenge.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/coreos/go-oidc/v3/oidc"
  28. "github.com/fxamacker/cbor/v2"
  29. "github.com/google/go-tpm/legacy/tpm2"
  30. "github.com/smallstep/go-attestation/attest"
  31. "go.step.sm/crypto/jose"
  32. "go.step.sm/crypto/keyutil"
  33. "go.step.sm/crypto/pemutil"
  34. "go.step.sm/crypto/x509util"
  35. "golang.org/x/exp/slices"
  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. // Serial number of the YubiKey, encoded as an integer.
  1222. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  1223. var oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  1224. type stepAttestationData struct {
  1225. Certificate *x509.Certificate
  1226. SerialNumber string
  1227. Fingerprint string
  1228. }
  1229. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  1230. // Use configured or default attestation roots if none is configured.
  1231. roots, ok := prov.GetAttestationRoots()
  1232. if !ok {
  1233. root, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  1234. if err != nil {
  1235. return nil, WrapErrorISE(err, "error parsing root ca")
  1236. }
  1237. roots = x509.NewCertPool()
  1238. roots.AddCert(root)
  1239. }
  1240. // Extract x5c and verify certificate
  1241. x5c, ok := att.AttStatement["x5c"].([]interface{})
  1242. if !ok {
  1243. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1244. }
  1245. if len(x5c) == 0 {
  1246. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  1247. }
  1248. der, ok := x5c[0].([]byte)
  1249. if !ok {
  1250. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1251. }
  1252. leaf, err := x509.ParseCertificate(der)
  1253. if err != nil {
  1254. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1255. }
  1256. intermediates := x509.NewCertPool()
  1257. for _, v := range x5c[1:] {
  1258. der, ok = v.([]byte)
  1259. if !ok {
  1260. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1261. }
  1262. cert, err := x509.ParseCertificate(der)
  1263. if err != nil {
  1264. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1265. }
  1266. intermediates.AddCert(cert)
  1267. }
  1268. if _, err := leaf.Verify(x509.VerifyOptions{
  1269. Intermediates: intermediates,
  1270. Roots: roots,
  1271. CurrentTime: time.Now().Truncate(time.Second),
  1272. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1273. }); err != nil {
  1274. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1275. }
  1276. // Verify proof of possession of private key validating the key
  1277. // authorization. Per recommendation at
  1278. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  1279. // signature is CBOR-encoded.
  1280. var sig []byte
  1281. csig, ok := att.AttStatement["sig"].([]byte)
  1282. if !ok {
  1283. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  1284. }
  1285. if err := cbor.Unmarshal(csig, &sig); err != nil {
  1286. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  1287. }
  1288. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1289. if err != nil {
  1290. return nil, err
  1291. }
  1292. switch pub := leaf.PublicKey.(type) {
  1293. case *ecdsa.PublicKey:
  1294. if pub.Curve != elliptic.P256() {
  1295. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  1296. }
  1297. sum := sha256.Sum256([]byte(keyAuth))
  1298. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  1299. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1300. }
  1301. case *rsa.PublicKey:
  1302. sum := sha256.Sum256([]byte(keyAuth))
  1303. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  1304. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1305. }
  1306. case ed25519.PublicKey:
  1307. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  1308. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1309. }
  1310. default:
  1311. return nil, NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  1312. }
  1313. // Parse attestation data:
  1314. // TODO(mariano): add support for other extensions.
  1315. data := &stepAttestationData{
  1316. Certificate: leaf,
  1317. }
  1318. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1319. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1320. }
  1321. for _, ext := range leaf.Extensions {
  1322. if !ext.Id.Equal(oidYubicoSerialNumber) {
  1323. continue
  1324. }
  1325. var serialNumber int
  1326. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  1327. if err != nil || len(rest) > 0 {
  1328. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1329. }
  1330. data.SerialNumber = strconv.Itoa(serialNumber)
  1331. break
  1332. }
  1333. return data, nil
  1334. }
  1335. // serverName determines the SNI HostName to set based on an acme.Challenge
  1336. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  1337. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  1338. // It also references TLS Extensions [RFC6066].
  1339. func serverName(ch *Challenge) string {
  1340. if ip := net.ParseIP(ch.Value); ip != nil {
  1341. return reverseAddr(ip)
  1342. }
  1343. return ch.Value
  1344. }
  1345. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  1346. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  1347. // to parse the IP address.
  1348. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  1349. func reverseAddr(ip net.IP) (arpa string) {
  1350. if ip.To4() != nil {
  1351. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  1352. }
  1353. // Must be IPv6
  1354. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  1355. // Add it, in reverse, to the buffer
  1356. for i := len(ip) - 1; i >= 0; i-- {
  1357. v := ip[i]
  1358. buf = append(buf, hexit[v&0xF],
  1359. '.',
  1360. hexit[v>>4],
  1361. '.')
  1362. }
  1363. // Append "ip6.arpa." and return (buf already has the final .)
  1364. buf = append(buf, "ip6.arpa."...)
  1365. return string(buf)
  1366. }
  1367. // Convert unsigned integer to decimal string.
  1368. // Implementation taken from https://golang.org/src/net/parse.go
  1369. func uitoa(val uint) string {
  1370. if val == 0 { // avoid string allocation
  1371. return "0"
  1372. }
  1373. var buf [20]byte // big enough for 64bit value base 10
  1374. i := len(buf) - 1
  1375. for val >= 10 {
  1376. v := val / 10
  1377. buf[i] = byte('0' + val - v*10)
  1378. i--
  1379. val = v
  1380. }
  1381. // val < 10
  1382. buf[i] = byte('0' + val)
  1383. return string(buf[i:])
  1384. }
  1385. const hexit = "0123456789abcdef"
  1386. // KeyAuthorization creates the ACME key authorization value from a token
  1387. // and a jwk.
  1388. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  1389. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  1390. if err != nil {
  1391. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  1392. }
  1393. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  1394. return fmt.Sprintf("%s.%s", token, encPrint), nil
  1395. }
  1396. // storeError the given error to an ACME error and saves using the DB interface.
  1397. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  1398. ch.Error = err
  1399. if markInvalid {
  1400. ch.Status = StatusInvalid
  1401. }
  1402. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1403. return WrapErrorISE(err, "failure saving error to acme challenge")
  1404. }
  1405. return nil
  1406. }