challenge.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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. coseAlgRS1 coseAlgorithmIdentifier = -65535 // deprecated, but (still) often used in TPMs
  462. )
  463. func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
  464. ver, ok := att.AttStatement["ver"].(string)
  465. if !ok {
  466. return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
  467. }
  468. if ver != "2.0" {
  469. return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
  470. }
  471. x5c, ok := att.AttStatement["x5c"].([]interface{})
  472. if !ok {
  473. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  474. }
  475. if len(x5c) == 0 {
  476. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  477. }
  478. akCertBytes, ok := x5c[0].([]byte)
  479. if !ok {
  480. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  481. }
  482. akCert, err := x509.ParseCertificate(akCertBytes)
  483. if err != nil {
  484. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  485. }
  486. intermediates := x509.NewCertPool()
  487. for _, v := range x5c[1:] {
  488. intCertBytes, vok := v.([]byte)
  489. if !vok {
  490. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  491. }
  492. intCert, err := x509.ParseCertificate(intCertBytes)
  493. if err != nil {
  494. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  495. }
  496. intermediates.AddCert(intCert)
  497. }
  498. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  499. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  500. // but I doubt that will happen.
  501. if len(akCert.UnhandledCriticalExtensions) > 0 {
  502. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  503. for _, extOID := range akCert.UnhandledCriticalExtensions {
  504. if !extOID.Equal(oidSubjectAlternativeName) {
  505. // critical extensions other than the Subject Alternative Name remain unhandled
  506. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  507. }
  508. }
  509. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  510. }
  511. roots, ok := prov.GetAttestationRoots()
  512. if !ok {
  513. return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
  514. }
  515. // verify that the AK certificate was signed by a trusted root,
  516. // chained to by the intermediates provided by the client. As part
  517. // of building the verified certificate chain, the signature over the
  518. // AK certificate is checked to be a valid signature of one of the
  519. // provided intermediates. Signatures over the intermediates are in
  520. // turn also verified to be valid signatures from one of the trusted
  521. // roots.
  522. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  523. Roots: roots,
  524. Intermediates: intermediates,
  525. CurrentTime: time.Now().Truncate(time.Second),
  526. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  527. })
  528. if err != nil {
  529. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  530. }
  531. // validate additional AK certificate requirements
  532. if err := validateAKCertificate(akCert); err != nil {
  533. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
  534. }
  535. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  536. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  537. if err != nil {
  538. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
  539. }
  540. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  541. for i, pi := range sans.PermanentIdentifiers {
  542. permanentIdentifiers[i] = pi.Identifier
  543. }
  544. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  545. pubArea, ok := att.AttStatement["pubArea"].([]byte)
  546. if !ok {
  547. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
  548. }
  549. if len(pubArea) == 0 {
  550. return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
  551. }
  552. sig, ok := att.AttStatement["sig"].([]byte)
  553. if !ok {
  554. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
  555. }
  556. if len(sig) == 0 {
  557. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
  558. }
  559. certInfo, ok := att.AttStatement["certInfo"].([]byte)
  560. if !ok {
  561. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
  562. }
  563. if len(certInfo) == 0 {
  564. return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
  565. }
  566. alg, ok := att.AttStatement["alg"].(int64)
  567. if !ok {
  568. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
  569. }
  570. var hash crypto.Hash
  571. switch coseAlgorithmIdentifier(alg) {
  572. case coseAlgRS256, coseAlgES256:
  573. hash = crypto.SHA256
  574. case coseAlgRS1:
  575. hash = crypto.SHA1
  576. default:
  577. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
  578. }
  579. // recreate the generated key certification parameter values and verify
  580. // the attested key using the public key of the AK.
  581. certificationParameters := &attest.CertificationParameters{
  582. Public: pubArea, // the public key that was attested
  583. CreateAttestation: certInfo, // the attested properties of the key
  584. CreateSignature: sig, // signature over the attested properties
  585. }
  586. verifyOpts := attest.VerifyOpts{
  587. Public: akCert.PublicKey, // public key of the AK that attested the key
  588. Hash: hash,
  589. }
  590. if err = certificationParameters.Verify(verifyOpts); err != nil {
  591. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
  592. }
  593. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  594. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  595. if err != nil {
  596. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
  597. }
  598. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  599. if err != nil {
  600. return nil, WrapErrorISE(err, "failed creating key auth digest")
  601. }
  602. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  603. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  604. // within the encoded `certInfo` property of the attestation statement.
  605. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  606. return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
  607. }
  608. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  609. pub, err := tpm2.DecodePublic(pubArea)
  610. if err != nil {
  611. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
  612. }
  613. publicKey, err := pub.Key()
  614. if err != nil {
  615. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
  616. }
  617. data := &tpmAttestationData{
  618. Certificate: akCert,
  619. VerifiedChains: verifiedChains,
  620. PermanentIdentifiers: permanentIdentifiers,
  621. }
  622. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  623. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  624. }
  625. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  626. return data, nil
  627. }
  628. var (
  629. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  630. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  631. )
  632. // validateAKCertificate validates the X.509 AK certificate to be
  633. // in accordance with the required properties. The requirements come from:
  634. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  635. //
  636. // - Version MUST be set to 3.
  637. // - Subject field MUST be set to empty.
  638. // - The Subject Alternative Name extension MUST be set as defined
  639. // in [TPMv2-EK-Profile] section 3.2.9.
  640. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  641. // ("joint-iso-itu-t(2) international-organizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  642. // - The Basic Constraints extension MUST have the CA component set to false.
  643. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  644. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  645. // the status of many attestation certificates is available through metadata
  646. // services. See, for example, the FIDO Metadata Service.
  647. func validateAKCertificate(c *x509.Certificate) error {
  648. if c.Version != 3 {
  649. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  650. }
  651. if c.Subject.String() != "" {
  652. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  653. }
  654. if c.IsCA {
  655. return errors.New("AK certificate must not be a CA")
  656. }
  657. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  658. return err
  659. }
  660. return validateAKCertificateSubjectAlternativeNames(c)
  661. }
  662. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  663. // has TPM hardware details set.
  664. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  665. sans, err := x509util.ParseSubjectAlternativeNames(c)
  666. if err != nil {
  667. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  668. }
  669. details := sans.TPMHardwareDetails
  670. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  671. switch {
  672. case manufacturer == "":
  673. return errors.New("missing TPM manufacturer")
  674. case model == "":
  675. return errors.New("missing TPM model")
  676. case version == "":
  677. return errors.New("missing TPM version")
  678. }
  679. return nil
  680. }
  681. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  682. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  683. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  684. var (
  685. valid = false
  686. ekus []asn1.ObjectIdentifier
  687. )
  688. for _, ext := range c.Extensions {
  689. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  690. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  691. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  692. }
  693. valid = true
  694. }
  695. }
  696. if !valid {
  697. return errors.New("AK certificate is missing Extended Key Usage extension")
  698. }
  699. return nil
  700. }
  701. // Apple Enterprise Attestation Root CA from
  702. // https://www.apple.com/certificateauthority/private/
  703. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  704. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  705. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  706. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  707. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  708. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  709. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  710. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  711. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  712. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  713. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  714. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  715. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  716. -----END CERTIFICATE-----`
  717. var (
  718. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  719. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  720. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  721. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  722. )
  723. type appleAttestationData struct {
  724. Nonce []byte
  725. SerialNumber string
  726. UDID string
  727. SEPVersion string
  728. Certificate *x509.Certificate
  729. Fingerprint string
  730. }
  731. func doAppleAttestationFormat(_ context.Context, prov Provisioner, _ *Challenge, att *attestationObject) (*appleAttestationData, error) {
  732. // Use configured or default attestation roots if none is configured.
  733. roots, ok := prov.GetAttestationRoots()
  734. if !ok {
  735. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  736. if err != nil {
  737. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  738. }
  739. roots = x509.NewCertPool()
  740. roots.AddCert(root)
  741. }
  742. x5c, ok := att.AttStatement["x5c"].([]interface{})
  743. if !ok {
  744. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  745. }
  746. if len(x5c) == 0 {
  747. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  748. }
  749. der, ok := x5c[0].([]byte)
  750. if !ok {
  751. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  752. }
  753. leaf, err := x509.ParseCertificate(der)
  754. if err != nil {
  755. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  756. }
  757. intermediates := x509.NewCertPool()
  758. for _, v := range x5c[1:] {
  759. der, ok = v.([]byte)
  760. if !ok {
  761. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  762. }
  763. cert, err := x509.ParseCertificate(der)
  764. if err != nil {
  765. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  766. }
  767. intermediates.AddCert(cert)
  768. }
  769. if _, err := leaf.Verify(x509.VerifyOptions{
  770. Intermediates: intermediates,
  771. Roots: roots,
  772. CurrentTime: time.Now().Truncate(time.Second),
  773. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  774. }); err != nil {
  775. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  776. }
  777. data := &appleAttestationData{
  778. Certificate: leaf,
  779. }
  780. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  781. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  782. }
  783. for _, ext := range leaf.Extensions {
  784. switch {
  785. case ext.Id.Equal(oidAppleSerialNumber):
  786. data.SerialNumber = string(ext.Value)
  787. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  788. data.UDID = string(ext.Value)
  789. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  790. data.SEPVersion = string(ext.Value)
  791. case ext.Id.Equal(oidAppleNonce):
  792. data.Nonce = ext.Value
  793. }
  794. }
  795. return data, nil
  796. }
  797. // Yubico PIV Root CA Serial 263751
  798. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  799. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  800. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  801. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  802. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  803. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  804. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  805. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  806. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  807. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  808. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  809. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  810. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  811. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  812. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  813. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  814. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  815. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  816. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  817. -----END CERTIFICATE-----`
  818. // Serial number of the YubiKey, encoded as an integer.
  819. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  820. var oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  821. type stepAttestationData struct {
  822. Certificate *x509.Certificate
  823. SerialNumber string
  824. Fingerprint string
  825. }
  826. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  827. // Use configured or default attestation roots if none is configured.
  828. roots, ok := prov.GetAttestationRoots()
  829. if !ok {
  830. root, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  831. if err != nil {
  832. return nil, WrapErrorISE(err, "error parsing root ca")
  833. }
  834. roots = x509.NewCertPool()
  835. roots.AddCert(root)
  836. }
  837. // Extract x5c and verify certificate
  838. x5c, ok := att.AttStatement["x5c"].([]interface{})
  839. if !ok {
  840. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  841. }
  842. if len(x5c) == 0 {
  843. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  844. }
  845. der, ok := x5c[0].([]byte)
  846. if !ok {
  847. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  848. }
  849. leaf, err := x509.ParseCertificate(der)
  850. if err != nil {
  851. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  852. }
  853. intermediates := x509.NewCertPool()
  854. for _, v := range x5c[1:] {
  855. der, ok = v.([]byte)
  856. if !ok {
  857. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  858. }
  859. cert, err := x509.ParseCertificate(der)
  860. if err != nil {
  861. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  862. }
  863. intermediates.AddCert(cert)
  864. }
  865. if _, err := leaf.Verify(x509.VerifyOptions{
  866. Intermediates: intermediates,
  867. Roots: roots,
  868. CurrentTime: time.Now().Truncate(time.Second),
  869. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  870. }); err != nil {
  871. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  872. }
  873. // Verify proof of possession of private key validating the key
  874. // authorization. Per recommendation at
  875. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  876. // signature is CBOR-encoded.
  877. var sig []byte
  878. csig, ok := att.AttStatement["sig"].([]byte)
  879. if !ok {
  880. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  881. }
  882. if err := cbor.Unmarshal(csig, &sig); err != nil {
  883. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  884. }
  885. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  886. if err != nil {
  887. return nil, err
  888. }
  889. switch pub := leaf.PublicKey.(type) {
  890. case *ecdsa.PublicKey:
  891. if pub.Curve != elliptic.P256() {
  892. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  893. }
  894. sum := sha256.Sum256([]byte(keyAuth))
  895. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  896. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  897. }
  898. case *rsa.PublicKey:
  899. sum := sha256.Sum256([]byte(keyAuth))
  900. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  901. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  902. }
  903. case ed25519.PublicKey:
  904. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  905. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  906. }
  907. default:
  908. return nil, NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  909. }
  910. // Parse attestation data:
  911. // TODO(mariano): add support for other extensions.
  912. data := &stepAttestationData{
  913. Certificate: leaf,
  914. }
  915. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  916. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  917. }
  918. for _, ext := range leaf.Extensions {
  919. if !ext.Id.Equal(oidYubicoSerialNumber) {
  920. continue
  921. }
  922. var serialNumber int
  923. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  924. if err != nil || len(rest) > 0 {
  925. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  926. }
  927. data.SerialNumber = strconv.Itoa(serialNumber)
  928. break
  929. }
  930. return data, nil
  931. }
  932. // serverName determines the SNI HostName to set based on an acme.Challenge
  933. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  934. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  935. // It also references TLS Extensions [RFC6066].
  936. func serverName(ch *Challenge) string {
  937. var serverName string
  938. ip := net.ParseIP(ch.Value)
  939. if ip != nil {
  940. serverName = reverseAddr(ip)
  941. } else {
  942. serverName = ch.Value
  943. }
  944. return serverName
  945. }
  946. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  947. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  948. // to parse the IP address.
  949. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  950. func reverseAddr(ip net.IP) (arpa string) {
  951. if ip.To4() != nil {
  952. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  953. }
  954. // Must be IPv6
  955. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  956. // Add it, in reverse, to the buffer
  957. for i := len(ip) - 1; i >= 0; i-- {
  958. v := ip[i]
  959. buf = append(buf, hexit[v&0xF],
  960. '.',
  961. hexit[v>>4],
  962. '.')
  963. }
  964. // Append "ip6.arpa." and return (buf already has the final .)
  965. buf = append(buf, "ip6.arpa."...)
  966. return string(buf)
  967. }
  968. // Convert unsigned integer to decimal string.
  969. // Implementation taken from https://golang.org/src/net/parse.go
  970. func uitoa(val uint) string {
  971. if val == 0 { // avoid string allocation
  972. return "0"
  973. }
  974. var buf [20]byte // big enough for 64bit value base 10
  975. i := len(buf) - 1
  976. for val >= 10 {
  977. v := val / 10
  978. buf[i] = byte('0' + val - v*10)
  979. i--
  980. val = v
  981. }
  982. // val < 10
  983. buf[i] = byte('0' + val)
  984. return string(buf[i:])
  985. }
  986. const hexit = "0123456789abcdef"
  987. // KeyAuthorization creates the ACME key authorization value from a token
  988. // and a jwk.
  989. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  990. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  991. if err != nil {
  992. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  993. }
  994. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  995. return fmt.Sprintf("%s.%s", token, encPrint), nil
  996. }
  997. // storeError the given error to an ACME error and saves using the DB interface.
  998. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  999. ch.Error = err
  1000. if markInvalid {
  1001. ch.Status = StatusInvalid
  1002. }
  1003. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1004. return WrapErrorISE(err, "failure saving error to acme challenge")
  1005. }
  1006. return nil
  1007. }