challenge.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. package acme
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/rsa"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "encoding/asn1"
  14. "encoding/base64"
  15. "encoding/hex"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "net"
  21. "net/url"
  22. "reflect"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/fxamacker/cbor/v2"
  27. "github.com/google/go-tpm/legacy/tpm2"
  28. "golang.org/x/exp/slices"
  29. "github.com/smallstep/go-attestation/attest"
  30. "go.step.sm/crypto/jose"
  31. "go.step.sm/crypto/keyutil"
  32. "go.step.sm/crypto/pemutil"
  33. "go.step.sm/crypto/x509util"
  34. "github.com/smallstep/certificates/authority/provisioner"
  35. )
  36. type ChallengeType string
  37. const (
  38. // HTTP01 is the http-01 ACME challenge type
  39. HTTP01 ChallengeType = "http-01"
  40. // DNS01 is the dns-01 ACME challenge type
  41. DNS01 ChallengeType = "dns-01"
  42. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  43. TLSALPN01 ChallengeType = "tls-alpn-01"
  44. // DEVICEATTEST01 is the device-attest-01 ACME challenge type
  45. DEVICEATTEST01 ChallengeType = "device-attest-01"
  46. )
  47. var (
  48. // InsecurePortHTTP01 is the port used to verify http-01 challenges. If not set it
  49. // defaults to 80.
  50. InsecurePortHTTP01 int
  51. // InsecurePortTLSALPN01 is the port used to verify tls-alpn-01 challenges. If not
  52. // set it defaults to 443.
  53. //
  54. // This variable can be used for testing purposes.
  55. InsecurePortTLSALPN01 int
  56. )
  57. // Challenge represents an ACME response Challenge type.
  58. type Challenge struct {
  59. ID string `json:"-"`
  60. AccountID string `json:"-"`
  61. AuthorizationID string `json:"-"`
  62. Value string `json:"-"`
  63. Type ChallengeType `json:"type"`
  64. Status Status `json:"status"`
  65. Token string `json:"token"`
  66. ValidatedAt string `json:"validated,omitempty"`
  67. URL string `json:"url"`
  68. Error *Error `json:"error,omitempty"`
  69. }
  70. // ToLog enables response logging.
  71. func (ch *Challenge) ToLog() (interface{}, error) {
  72. b, err := json.Marshal(ch)
  73. if err != nil {
  74. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  75. }
  76. return string(b), nil
  77. }
  78. // Validate attempts to validate the Challenge. Stores changes to the Challenge
  79. // type using the DB interface. If the Challenge is validated, the 'status' and
  80. // 'validated' attributes are updated.
  81. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  82. // If already valid or invalid then return without performing validation.
  83. if ch.Status != StatusPending {
  84. return nil
  85. }
  86. switch ch.Type {
  87. case HTTP01:
  88. return http01Validate(ctx, ch, db, jwk)
  89. case DNS01:
  90. return dns01Validate(ctx, ch, db, jwk)
  91. case TLSALPN01:
  92. return tlsalpn01Validate(ctx, ch, db, jwk)
  93. case DEVICEATTEST01:
  94. return deviceAttest01Validate(ctx, ch, db, jwk, payload)
  95. default:
  96. return NewErrorISE("unexpected challenge type '%s'", ch.Type)
  97. }
  98. }
  99. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  100. u := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  101. // Append insecure port if set.
  102. // Only used for testing purposes.
  103. if InsecurePortHTTP01 != 0 {
  104. u.Host += ":" + strconv.Itoa(InsecurePortHTTP01)
  105. }
  106. vc := MustClientFromContext(ctx)
  107. resp, err := vc.Get(u.String())
  108. if err != nil {
  109. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  110. "error doing http GET for url %s", u))
  111. }
  112. defer resp.Body.Close()
  113. if resp.StatusCode >= 400 {
  114. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  115. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  116. }
  117. body, err := io.ReadAll(resp.Body)
  118. if err != nil {
  119. return WrapErrorISE(err, "error reading "+
  120. "response body for url %s", u)
  121. }
  122. keyAuth := strings.TrimSpace(string(body))
  123. expected, err := KeyAuthorization(ch.Token, jwk)
  124. if err != nil {
  125. return err
  126. }
  127. if keyAuth != expected {
  128. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  129. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  130. }
  131. // Update and store the challenge.
  132. ch.Status = StatusValid
  133. ch.Error = nil
  134. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  135. if err = db.UpdateChallenge(ctx, ch); err != nil {
  136. return WrapErrorISE(err, "error updating challenge")
  137. }
  138. return nil
  139. }
  140. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  141. // and adds square brackets if that's the case, so that it can be used
  142. // as a hostname. Returns the original Challenge value as the host to
  143. // use in other cases.
  144. func http01ChallengeHost(value string) string {
  145. if ip := net.ParseIP(value); ip != nil && ip.To4() == nil {
  146. value = "[" + value + "]"
  147. }
  148. return value
  149. }
  150. func tlsAlert(err error) uint8 {
  151. var opErr *net.OpError
  152. if errors.As(err, &opErr) {
  153. v := reflect.ValueOf(opErr.Err)
  154. if v.Kind() == reflect.Uint8 {
  155. return uint8(v.Uint())
  156. }
  157. }
  158. return 0
  159. }
  160. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  161. config := &tls.Config{
  162. NextProtos: []string{"acme-tls/1"},
  163. // https://tools.ietf.org/html/rfc8737#section-4
  164. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  165. // [RFC5246] or higher when connecting to clients for validation.
  166. MinVersion: tls.VersionTLS12,
  167. ServerName: serverName(ch),
  168. InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate
  169. }
  170. var hostPort string
  171. // Allow to change TLS port for testing purposes.
  172. if port := InsecurePortTLSALPN01; port == 0 {
  173. hostPort = net.JoinHostPort(ch.Value, "443")
  174. } else {
  175. hostPort = net.JoinHostPort(ch.Value, strconv.Itoa(port))
  176. }
  177. vc := MustClientFromContext(ctx)
  178. conn, err := vc.TLSDial("tcp", hostPort, config)
  179. if err != nil {
  180. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  181. // client and server protocols. When this happens the connection is
  182. // closed with the error no_application_protocol(120) as required by
  183. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  184. if tlsAlert(err) == 120 {
  185. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  186. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  187. }
  188. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  189. "error doing TLS dial for %s", hostPort))
  190. }
  191. defer conn.Close()
  192. cs := conn.ConnectionState()
  193. certs := cs.PeerCertificates
  194. if len(certs) == 0 {
  195. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  196. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  197. }
  198. if cs.NegotiatedProtocol != "acme-tls/1" {
  199. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  200. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  201. }
  202. leafCert := certs[0]
  203. // if no DNS names present, look for IP address and verify that exactly one exists
  204. if len(leafCert.DNSNames) == 0 {
  205. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  206. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  207. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  208. }
  209. } else {
  210. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], ch.Value) {
  211. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  212. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  213. }
  214. }
  215. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  216. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  217. foundIDPeAcmeIdentifierV1Obsolete := false
  218. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  219. if err != nil {
  220. return err
  221. }
  222. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  223. for _, ext := range leafCert.Extensions {
  224. if idPeAcmeIdentifier.Equal(ext.Id) {
  225. if !ext.Critical {
  226. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  227. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  228. }
  229. var extValue []byte
  230. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  231. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  232. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  233. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  234. }
  235. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  236. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  237. "incorrect certificate for tls-alpn-01 challenge: "+
  238. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  239. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  240. }
  241. ch.Status = StatusValid
  242. ch.Error = nil
  243. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  244. if err = db.UpdateChallenge(ctx, ch); err != nil {
  245. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  246. }
  247. return nil
  248. }
  249. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  250. foundIDPeAcmeIdentifierV1Obsolete = true
  251. }
  252. }
  253. if foundIDPeAcmeIdentifierV1Obsolete {
  254. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  255. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  256. }
  257. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  258. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  259. }
  260. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  261. // Normalize domain for wildcard DNS names
  262. // This is done to avoid making TXT lookups for domains like
  263. // _acme-challenge.*.example.com
  264. // Instead perform txt lookup for _acme-challenge.example.com
  265. domain := strings.TrimPrefix(ch.Value, "*.")
  266. vc := MustClientFromContext(ctx)
  267. txtRecords, err := vc.LookupTxt("_acme-challenge." + domain)
  268. if err != nil {
  269. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  270. "error looking up TXT records for domain %s", domain))
  271. }
  272. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  273. if err != nil {
  274. return err
  275. }
  276. h := sha256.Sum256([]byte(expectedKeyAuth))
  277. expected := base64.RawURLEncoding.EncodeToString(h[:])
  278. var found bool
  279. for _, r := range txtRecords {
  280. if r == expected {
  281. found = true
  282. break
  283. }
  284. }
  285. if !found {
  286. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  287. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  288. }
  289. // Update and store the challenge.
  290. ch.Status = StatusValid
  291. ch.Error = nil
  292. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  293. if err = db.UpdateChallenge(ctx, ch); err != nil {
  294. return WrapErrorISE(err, "error updating challenge")
  295. }
  296. return nil
  297. }
  298. type payloadType struct {
  299. AttObj string `json:"attObj"`
  300. Error string `json:"error"`
  301. }
  302. type attestationObject struct {
  303. Format string `json:"fmt"`
  304. AttStatement map[string]interface{} `json:"attStmt,omitempty"`
  305. }
  306. // TODO(bweeks): move attestation verification to a shared package.
  307. func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  308. // Load authorization to store the key fingerprint.
  309. az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
  310. if err != nil {
  311. return WrapErrorISE(err, "error loading authorization")
  312. }
  313. // Parse payload.
  314. var p payloadType
  315. if err := json.Unmarshal(payload, &p); err != nil {
  316. return WrapErrorISE(err, "error unmarshalling JSON")
  317. }
  318. if p.Error != "" {
  319. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  320. "payload contained error: %v", p.Error))
  321. }
  322. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  323. if err != nil {
  324. return WrapErrorISE(err, "error base64 decoding attObj")
  325. }
  326. att := attestationObject{}
  327. if err := cbor.Unmarshal(attObj, &att); err != nil {
  328. return WrapErrorISE(err, "error unmarshalling CBOR")
  329. }
  330. format := att.Format
  331. prov := MustProvisionerFromContext(ctx)
  332. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(format)) {
  333. if format != "apple" && format != "step" && format != "tpm" {
  334. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  335. }
  336. return storeError(ctx, db, ch, true,
  337. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", format))
  338. }
  339. switch format {
  340. case "apple":
  341. data, err := doAppleAttestationFormat(ctx, prov, ch, &att)
  342. if err != nil {
  343. var acmeError *Error
  344. if errors.As(err, &acmeError) {
  345. if acmeError.Status == 500 {
  346. return acmeError
  347. }
  348. return storeError(ctx, db, ch, true, acmeError)
  349. }
  350. return WrapErrorISE(err, "error validating attestation")
  351. }
  352. // Validate nonce with SHA-256 of the token.
  353. if len(data.Nonce) != 0 {
  354. sum := sha256.Sum256([]byte(ch.Token))
  355. if subtle.ConstantTimeCompare(data.Nonce, sum[:]) != 1 {
  356. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "challenge token does not match"))
  357. }
  358. }
  359. // Validate Apple's ClientIdentifier (Identifier.Value) with device
  360. // identifiers.
  361. //
  362. // Note: We might want to use an external service for this.
  363. if data.UDID != ch.Value && data.SerialNumber != ch.Value {
  364. subproblem := NewSubproblemWithIdentifier(
  365. ErrorRejectedIdentifierType,
  366. Identifier{Type: "permanent-identifier", Value: ch.Value},
  367. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{data.UDID, data.SerialNumber},
  368. )
  369. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  370. }
  371. // Update attestation key fingerprint to compare against the CSR
  372. az.Fingerprint = data.Fingerprint
  373. case "step":
  374. data, err := doStepAttestationFormat(ctx, prov, ch, jwk, &att)
  375. if err != nil {
  376. var acmeError *Error
  377. if errors.As(err, &acmeError) {
  378. if acmeError.Status == 500 {
  379. return acmeError
  380. }
  381. return storeError(ctx, db, ch, true, acmeError)
  382. }
  383. return WrapErrorISE(err, "error validating attestation")
  384. }
  385. // Validate the YubiKey serial number from the attestation
  386. // certificate with the challenged Order value.
  387. //
  388. // Note: We might want to use an external service for this.
  389. if data.SerialNumber != ch.Value {
  390. subproblem := NewSubproblemWithIdentifier(
  391. ErrorRejectedIdentifierType,
  392. Identifier{Type: "permanent-identifier", Value: ch.Value},
  393. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  394. )
  395. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  396. }
  397. // Update attestation key fingerprint to compare against the CSR
  398. az.Fingerprint = data.Fingerprint
  399. case "tpm":
  400. data, err := doTPMAttestationFormat(ctx, prov, ch, jwk, &att)
  401. if err != nil {
  402. var acmeError *Error
  403. if errors.As(err, &acmeError) {
  404. if acmeError.Status == 500 {
  405. return acmeError
  406. }
  407. return storeError(ctx, db, ch, true, acmeError)
  408. }
  409. return WrapErrorISE(err, "error validating attestation")
  410. }
  411. // TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
  412. // extracted from the AK certificate. This is currently the case for AK certs from the CLI, as we
  413. // haven't implemented a way for AK certs requested by the CLI to always contain the requested
  414. // PermanentIdentifier. Omitting the check below doesn't allow just any request, as the Order can
  415. // still fail if the challenge value isn't equal to the CSR subject.
  416. if len(data.PermanentIdentifiers) > 0 && !slices.Contains(data.PermanentIdentifiers, ch.Value) { // TODO(hs): add support for HardwareModuleName
  417. subproblem := NewSubproblemWithIdentifier(
  418. ErrorRejectedIdentifierType,
  419. Identifier{Type: "permanent-identifier", Value: ch.Value},
  420. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, data.PermanentIdentifiers,
  421. )
  422. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  423. }
  424. // Update attestation key fingerprint to compare against the CSR
  425. az.Fingerprint = data.Fingerprint
  426. default:
  427. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  428. }
  429. // Update and store the challenge.
  430. ch.Status = StatusValid
  431. ch.Error = nil
  432. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  433. // Store the fingerprint in the authorization.
  434. //
  435. // TODO: add method to update authorization and challenge atomically.
  436. if az.Fingerprint != "" {
  437. if err := db.UpdateAuthorization(ctx, az); err != nil {
  438. return WrapErrorISE(err, "error updating authorization")
  439. }
  440. }
  441. if err := db.UpdateChallenge(ctx, ch); err != nil {
  442. return WrapErrorISE(err, "error updating challenge")
  443. }
  444. return nil
  445. }
  446. var (
  447. oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
  448. )
  449. type tpmAttestationData struct {
  450. Certificate *x509.Certificate
  451. VerifiedChains [][]*x509.Certificate
  452. PermanentIdentifiers []string
  453. Fingerprint string
  454. }
  455. // coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
  456. // Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
  457. type coseAlgorithmIdentifier int32
  458. const (
  459. coseAlgES256 coseAlgorithmIdentifier = -7
  460. coseAlgRS256 coseAlgorithmIdentifier = -257
  461. )
  462. func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
  463. ver, ok := att.AttStatement["ver"].(string)
  464. if !ok {
  465. return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
  466. }
  467. if ver != "2.0" {
  468. return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
  469. }
  470. x5c, ok := att.AttStatement["x5c"].([]interface{})
  471. if !ok {
  472. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  473. }
  474. if len(x5c) == 0 {
  475. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  476. }
  477. akCertBytes, ok := x5c[0].([]byte)
  478. if !ok {
  479. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  480. }
  481. akCert, err := x509.ParseCertificate(akCertBytes)
  482. if err != nil {
  483. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  484. }
  485. intermediates := x509.NewCertPool()
  486. for _, v := range x5c[1:] {
  487. intCertBytes, vok := v.([]byte)
  488. if !vok {
  489. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  490. }
  491. intCert, err := x509.ParseCertificate(intCertBytes)
  492. if err != nil {
  493. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  494. }
  495. intermediates.AddCert(intCert)
  496. }
  497. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  498. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  499. // but I doubt that will happen.
  500. if len(akCert.UnhandledCriticalExtensions) > 0 {
  501. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  502. for _, extOID := range akCert.UnhandledCriticalExtensions {
  503. if !extOID.Equal(oidSubjectAlternativeName) {
  504. // critical extensions other than the Subject Alternative Name remain unhandled
  505. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  506. }
  507. }
  508. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  509. }
  510. roots, ok := prov.GetAttestationRoots()
  511. if !ok {
  512. return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
  513. }
  514. // verify that the AK certificate was signed by a trusted root,
  515. // chained to by the intermediates provided by the client. As part
  516. // of building the verified certificate chain, the signature over the
  517. // AK certificate is checked to be a valid signature of one of the
  518. // provided intermediates. Signatures over the intermediates are in
  519. // turn also verified to be valid signatures from one of the trusted
  520. // roots.
  521. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  522. Roots: roots,
  523. Intermediates: intermediates,
  524. CurrentTime: time.Now().Truncate(time.Second),
  525. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  526. })
  527. if err != nil {
  528. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  529. }
  530. // validate additional AK certificate requirements
  531. if err := validateAKCertificate(akCert); err != nil {
  532. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
  533. }
  534. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  535. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  536. if err != nil {
  537. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
  538. }
  539. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  540. for i, pi := range sans.PermanentIdentifiers {
  541. permanentIdentifiers[i] = pi.Identifier
  542. }
  543. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  544. pubArea, ok := att.AttStatement["pubArea"].([]byte)
  545. if !ok {
  546. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
  547. }
  548. if len(pubArea) == 0 {
  549. return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
  550. }
  551. sig, ok := att.AttStatement["sig"].([]byte)
  552. if !ok {
  553. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
  554. }
  555. if len(sig) == 0 {
  556. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
  557. }
  558. certInfo, ok := att.AttStatement["certInfo"].([]byte)
  559. if !ok {
  560. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
  561. }
  562. if len(certInfo) == 0 {
  563. return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
  564. }
  565. alg, ok := att.AttStatement["alg"].(int64)
  566. if !ok {
  567. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
  568. }
  569. // only RS256 and ES256 are allowed
  570. coseAlg := coseAlgorithmIdentifier(alg)
  571. if coseAlg != coseAlgRS256 && coseAlg != coseAlgES256 {
  572. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
  573. }
  574. // set the hash algorithm to use to SHA256
  575. hash := crypto.SHA256
  576. // recreate the generated key certification parameter values and verify
  577. // the attested key using the public key of the AK.
  578. certificationParameters := &attest.CertificationParameters{
  579. Public: pubArea, // the public key that was attested
  580. CreateAttestation: certInfo, // the attested properties of the key
  581. CreateSignature: sig, // signature over the attested properties
  582. }
  583. verifyOpts := attest.VerifyOpts{
  584. Public: akCert.PublicKey, // public key of the AK that attested the key
  585. Hash: hash,
  586. }
  587. if err = certificationParameters.Verify(verifyOpts); err != nil {
  588. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
  589. }
  590. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  591. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  592. if err != nil {
  593. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
  594. }
  595. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  596. if err != nil {
  597. return nil, WrapErrorISE(err, "failed creating key auth digest")
  598. }
  599. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  600. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  601. // within the encoded `certInfo` property of the attestation statement.
  602. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  603. return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
  604. }
  605. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  606. pub, err := tpm2.DecodePublic(pubArea)
  607. if err != nil {
  608. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
  609. }
  610. publicKey, err := pub.Key()
  611. if err != nil {
  612. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
  613. }
  614. data := &tpmAttestationData{
  615. Certificate: akCert,
  616. VerifiedChains: verifiedChains,
  617. PermanentIdentifiers: permanentIdentifiers,
  618. }
  619. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  620. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  621. }
  622. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  623. return data, nil
  624. }
  625. var (
  626. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  627. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  628. )
  629. // validateAKCertifiate validates the X.509 AK certificate to be
  630. // in accordance with the required properties. The requirements come from:
  631. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  632. //
  633. // - Version MUST be set to 3.
  634. // - Subject field MUST be set to empty.
  635. // - The Subject Alternative Name extension MUST be set as defined
  636. // in [TPMv2-EK-Profile] section 3.2.9.
  637. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  638. // ("joint-iso-itu-t(2) internationalorganizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  639. // - The Basic Constraints extension MUST have the CA component set to false.
  640. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  641. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  642. // the status of many attestation certificates is available through metadata
  643. // services. See, for example, the FIDO Metadata Service.
  644. func validateAKCertificate(c *x509.Certificate) error {
  645. if c.Version != 3 {
  646. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  647. }
  648. if c.Subject.String() != "" {
  649. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  650. }
  651. if c.IsCA {
  652. return errors.New("AK certificate must not be a CA")
  653. }
  654. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  655. return err
  656. }
  657. return validateAKCertificateSubjectAlternativeNames(c)
  658. }
  659. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  660. // has TPM hardware details set.
  661. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  662. sans, err := x509util.ParseSubjectAlternativeNames(c)
  663. if err != nil {
  664. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  665. }
  666. details := sans.TPMHardwareDetails
  667. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  668. switch {
  669. case manufacturer == "":
  670. return errors.New("missing TPM manufacturer")
  671. case model == "":
  672. return errors.New("missing TPM model")
  673. case version == "":
  674. return errors.New("missing TPM version")
  675. }
  676. return nil
  677. }
  678. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  679. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  680. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  681. var (
  682. valid = false
  683. ekus []asn1.ObjectIdentifier
  684. )
  685. for _, ext := range c.Extensions {
  686. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  687. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  688. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  689. }
  690. valid = true
  691. }
  692. }
  693. if !valid {
  694. return errors.New("AK certificate is missing Extended Key Usage extension")
  695. }
  696. return nil
  697. }
  698. // Apple Enterprise Attestation Root CA from
  699. // https://www.apple.com/certificateauthority/private/
  700. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  701. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  702. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  703. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  704. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  705. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  706. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  707. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  708. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  709. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  710. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  711. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  712. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  713. -----END CERTIFICATE-----`
  714. var (
  715. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  716. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  717. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  718. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  719. )
  720. type appleAttestationData struct {
  721. Nonce []byte
  722. SerialNumber string
  723. UDID string
  724. SEPVersion string
  725. Certificate *x509.Certificate
  726. Fingerprint string
  727. }
  728. func doAppleAttestationFormat(_ context.Context, prov Provisioner, _ *Challenge, att *attestationObject) (*appleAttestationData, error) {
  729. // Use configured or default attestation roots if none is configured.
  730. roots, ok := prov.GetAttestationRoots()
  731. if !ok {
  732. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  733. if err != nil {
  734. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  735. }
  736. roots = x509.NewCertPool()
  737. roots.AddCert(root)
  738. }
  739. x5c, ok := att.AttStatement["x5c"].([]interface{})
  740. if !ok {
  741. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  742. }
  743. if len(x5c) == 0 {
  744. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  745. }
  746. der, ok := x5c[0].([]byte)
  747. if !ok {
  748. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  749. }
  750. leaf, err := x509.ParseCertificate(der)
  751. if err != nil {
  752. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  753. }
  754. intermediates := x509.NewCertPool()
  755. for _, v := range x5c[1:] {
  756. der, ok = v.([]byte)
  757. if !ok {
  758. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  759. }
  760. cert, err := x509.ParseCertificate(der)
  761. if err != nil {
  762. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  763. }
  764. intermediates.AddCert(cert)
  765. }
  766. if _, err := leaf.Verify(x509.VerifyOptions{
  767. Intermediates: intermediates,
  768. Roots: roots,
  769. CurrentTime: time.Now().Truncate(time.Second),
  770. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  771. }); err != nil {
  772. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  773. }
  774. data := &appleAttestationData{
  775. Certificate: leaf,
  776. }
  777. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  778. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  779. }
  780. for _, ext := range leaf.Extensions {
  781. switch {
  782. case ext.Id.Equal(oidAppleSerialNumber):
  783. data.SerialNumber = string(ext.Value)
  784. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  785. data.UDID = string(ext.Value)
  786. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  787. data.SEPVersion = string(ext.Value)
  788. case ext.Id.Equal(oidAppleNonce):
  789. data.Nonce = ext.Value
  790. }
  791. }
  792. return data, nil
  793. }
  794. // Yubico PIV Root CA Serial 263751
  795. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  796. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  797. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  798. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  799. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  800. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  801. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  802. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  803. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  804. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  805. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  806. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  807. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  808. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  809. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  810. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  811. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  812. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  813. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  814. -----END CERTIFICATE-----`
  815. // Serial number of the YubiKey, encoded as an integer.
  816. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  817. var oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  818. type stepAttestationData struct {
  819. Certificate *x509.Certificate
  820. SerialNumber string
  821. Fingerprint string
  822. }
  823. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  824. // Use configured or default attestation roots if none is configured.
  825. roots, ok := prov.GetAttestationRoots()
  826. if !ok {
  827. root, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  828. if err != nil {
  829. return nil, WrapErrorISE(err, "error parsing root ca")
  830. }
  831. roots = x509.NewCertPool()
  832. roots.AddCert(root)
  833. }
  834. // Extract x5c and verify certificate
  835. x5c, ok := att.AttStatement["x5c"].([]interface{})
  836. if !ok {
  837. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  838. }
  839. if len(x5c) == 0 {
  840. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  841. }
  842. der, ok := x5c[0].([]byte)
  843. if !ok {
  844. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  845. }
  846. leaf, err := x509.ParseCertificate(der)
  847. if err != nil {
  848. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  849. }
  850. intermediates := x509.NewCertPool()
  851. for _, v := range x5c[1:] {
  852. der, ok = v.([]byte)
  853. if !ok {
  854. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  855. }
  856. cert, err := x509.ParseCertificate(der)
  857. if err != nil {
  858. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  859. }
  860. intermediates.AddCert(cert)
  861. }
  862. if _, err := leaf.Verify(x509.VerifyOptions{
  863. Intermediates: intermediates,
  864. Roots: roots,
  865. CurrentTime: time.Now().Truncate(time.Second),
  866. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  867. }); err != nil {
  868. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  869. }
  870. // Verify proof of possession of private key validating the key
  871. // authorization. Per recommendation at
  872. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  873. // signature is CBOR-encoded.
  874. var sig []byte
  875. csig, ok := att.AttStatement["sig"].([]byte)
  876. if !ok {
  877. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  878. }
  879. if err := cbor.Unmarshal(csig, &sig); err != nil {
  880. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  881. }
  882. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  883. if err != nil {
  884. return nil, err
  885. }
  886. switch pub := leaf.PublicKey.(type) {
  887. case *ecdsa.PublicKey:
  888. if pub.Curve != elliptic.P256() {
  889. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  890. }
  891. sum := sha256.Sum256([]byte(keyAuth))
  892. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  893. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  894. }
  895. case *rsa.PublicKey:
  896. sum := sha256.Sum256([]byte(keyAuth))
  897. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  898. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  899. }
  900. case ed25519.PublicKey:
  901. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  902. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  903. }
  904. default:
  905. return nil, NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  906. }
  907. // Parse attestation data:
  908. // TODO(mariano): add support for other extensions.
  909. data := &stepAttestationData{
  910. Certificate: leaf,
  911. }
  912. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  913. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  914. }
  915. for _, ext := range leaf.Extensions {
  916. if !ext.Id.Equal(oidYubicoSerialNumber) {
  917. continue
  918. }
  919. var serialNumber int
  920. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  921. if err != nil || len(rest) > 0 {
  922. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  923. }
  924. data.SerialNumber = strconv.Itoa(serialNumber)
  925. break
  926. }
  927. return data, nil
  928. }
  929. // serverName determines the SNI HostName to set based on an acme.Challenge
  930. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  931. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  932. // It also references TLS Extensions [RFC6066].
  933. func serverName(ch *Challenge) string {
  934. var serverName string
  935. ip := net.ParseIP(ch.Value)
  936. if ip != nil {
  937. serverName = reverseAddr(ip)
  938. } else {
  939. serverName = ch.Value
  940. }
  941. return serverName
  942. }
  943. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  944. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  945. // to parse the IP address.
  946. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  947. func reverseAddr(ip net.IP) (arpa string) {
  948. if ip.To4() != nil {
  949. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  950. }
  951. // Must be IPv6
  952. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  953. // Add it, in reverse, to the buffer
  954. for i := len(ip) - 1; i >= 0; i-- {
  955. v := ip[i]
  956. buf = append(buf, hexit[v&0xF],
  957. '.',
  958. hexit[v>>4],
  959. '.')
  960. }
  961. // Append "ip6.arpa." and return (buf already has the final .)
  962. buf = append(buf, "ip6.arpa."...)
  963. return string(buf)
  964. }
  965. // Convert unsigned integer to decimal string.
  966. // Implementation taken from https://golang.org/src/net/parse.go
  967. func uitoa(val uint) string {
  968. if val == 0 { // avoid string allocation
  969. return "0"
  970. }
  971. var buf [20]byte // big enough for 64bit value base 10
  972. i := len(buf) - 1
  973. for val >= 10 {
  974. v := val / 10
  975. buf[i] = byte('0' + val - v*10)
  976. i--
  977. val = v
  978. }
  979. // val < 10
  980. buf[i] = byte('0' + val)
  981. return string(buf[i:])
  982. }
  983. const hexit = "0123456789abcdef"
  984. // KeyAuthorization creates the ACME key authorization value from a token
  985. // and a jwk.
  986. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  987. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  988. if err != nil {
  989. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  990. }
  991. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  992. return fmt.Sprintf("%s.%s", token, encPrint), nil
  993. }
  994. // storeError the given error to an ACME error and saves using the DB interface.
  995. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  996. ch.Error = err
  997. if markInvalid {
  998. ch.Status = StatusInvalid
  999. }
  1000. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1001. return WrapErrorISE(err, "failure saving error to acme challenge")
  1002. }
  1003. return nil
  1004. }