challenge.go 39 KB

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