challenge.go 54 KB

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