challenge.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. "go.step.sm/crypto/jose"
  28. "go.step.sm/crypto/pemutil"
  29. "github.com/smallstep/certificates/authority/provisioner"
  30. )
  31. type ChallengeType string
  32. const (
  33. // HTTP01 is the http-01 ACME challenge type
  34. HTTP01 ChallengeType = "http-01"
  35. // DNS01 is the dns-01 ACME challenge type
  36. DNS01 ChallengeType = "dns-01"
  37. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  38. TLSALPN01 ChallengeType = "tls-alpn-01"
  39. // DEVICEATTEST01 is the device-attest-01 ACME challenge type
  40. DEVICEATTEST01 ChallengeType = "device-attest-01"
  41. )
  42. var (
  43. // InsecurePortHTTP01 is the port used to verify http-01 challenges. If not set it
  44. // defaults to 80.
  45. InsecurePortHTTP01 int
  46. // InsecurePortTLSALPN01 is the port used to verify tls-alpn-01 challenges. If not
  47. // set it defaults to 443.
  48. //
  49. // This variable can be used for testing purposes.
  50. InsecurePortTLSALPN01 int
  51. )
  52. // Challenge represents an ACME response Challenge type.
  53. type Challenge struct {
  54. ID string `json:"-"`
  55. AccountID string `json:"-"`
  56. AuthorizationID string `json:"-"`
  57. Value string `json:"-"`
  58. Type ChallengeType `json:"type"`
  59. Status Status `json:"status"`
  60. Token string `json:"token"`
  61. ValidatedAt string `json:"validated,omitempty"`
  62. URL string `json:"url"`
  63. Error *Error `json:"error,omitempty"`
  64. }
  65. // ToLog enables response logging.
  66. func (ch *Challenge) ToLog() (interface{}, error) {
  67. b, err := json.Marshal(ch)
  68. if err != nil {
  69. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  70. }
  71. return string(b), nil
  72. }
  73. // Validate attempts to validate the Challenge. Stores changes to the Challenge
  74. // type using the DB interface. If the Challenge is validated, the 'status' and
  75. // 'validated' attributes are updated.
  76. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  77. // If already valid or invalid then return without performing validation.
  78. if ch.Status != StatusPending {
  79. return nil
  80. }
  81. switch ch.Type {
  82. case HTTP01:
  83. return http01Validate(ctx, ch, db, jwk)
  84. case DNS01:
  85. return dns01Validate(ctx, ch, db, jwk)
  86. case TLSALPN01:
  87. return tlsalpn01Validate(ctx, ch, db, jwk)
  88. case DEVICEATTEST01:
  89. return deviceAttest01Validate(ctx, ch, db, jwk, payload)
  90. default:
  91. return NewErrorISE("unexpected challenge type '%s'", ch.Type)
  92. }
  93. }
  94. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  95. u := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  96. // Append insecure port if set.
  97. // Only used for testing purposes.
  98. if InsecurePortHTTP01 != 0 {
  99. u.Host += ":" + strconv.Itoa(InsecurePortHTTP01)
  100. }
  101. vc := MustClientFromContext(ctx)
  102. resp, err := vc.Get(u.String())
  103. if err != nil {
  104. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  105. "error doing http GET for url %s", u))
  106. }
  107. defer resp.Body.Close()
  108. if resp.StatusCode >= 400 {
  109. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  110. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  111. }
  112. body, err := io.ReadAll(resp.Body)
  113. if err != nil {
  114. return WrapErrorISE(err, "error reading "+
  115. "response body for url %s", u)
  116. }
  117. keyAuth := strings.TrimSpace(string(body))
  118. expected, err := KeyAuthorization(ch.Token, jwk)
  119. if err != nil {
  120. return err
  121. }
  122. if keyAuth != expected {
  123. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  124. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  125. }
  126. // Update and store the challenge.
  127. ch.Status = StatusValid
  128. ch.Error = nil
  129. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  130. if err = db.UpdateChallenge(ctx, ch); err != nil {
  131. return WrapErrorISE(err, "error updating challenge")
  132. }
  133. return nil
  134. }
  135. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  136. // and adds square brackets if that's the case, so that it can be used
  137. // as a hostname. Returns the original Challenge value as the host to
  138. // use in other cases.
  139. func http01ChallengeHost(value string) string {
  140. if ip := net.ParseIP(value); ip != nil && ip.To4() == nil {
  141. value = "[" + value + "]"
  142. }
  143. return value
  144. }
  145. func tlsAlert(err error) uint8 {
  146. var opErr *net.OpError
  147. if errors.As(err, &opErr) {
  148. v := reflect.ValueOf(opErr.Err)
  149. if v.Kind() == reflect.Uint8 {
  150. return uint8(v.Uint())
  151. }
  152. }
  153. return 0
  154. }
  155. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  156. config := &tls.Config{
  157. NextProtos: []string{"acme-tls/1"},
  158. // https://tools.ietf.org/html/rfc8737#section-4
  159. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  160. // [RFC5246] or higher when connecting to clients for validation.
  161. MinVersion: tls.VersionTLS12,
  162. ServerName: serverName(ch),
  163. InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate
  164. }
  165. var hostPort string
  166. // Allow to change TLS port for testing purposes.
  167. if port := InsecurePortTLSALPN01; port == 0 {
  168. hostPort = net.JoinHostPort(ch.Value, "443")
  169. } else {
  170. hostPort = net.JoinHostPort(ch.Value, strconv.Itoa(port))
  171. }
  172. vc := MustClientFromContext(ctx)
  173. conn, err := vc.TLSDial("tcp", hostPort, config)
  174. if err != nil {
  175. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  176. // client and server protocols. When this happens the connection is
  177. // closed with the error no_application_protocol(120) as required by
  178. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  179. if tlsAlert(err) == 120 {
  180. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  181. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  182. }
  183. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  184. "error doing TLS dial for %s", hostPort))
  185. }
  186. defer conn.Close()
  187. cs := conn.ConnectionState()
  188. certs := cs.PeerCertificates
  189. if len(certs) == 0 {
  190. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  191. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  192. }
  193. if cs.NegotiatedProtocol != "acme-tls/1" {
  194. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  195. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  196. }
  197. leafCert := certs[0]
  198. // if no DNS names present, look for IP address and verify that exactly one exists
  199. if len(leafCert.DNSNames) == 0 {
  200. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  201. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  202. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  203. }
  204. } else {
  205. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], 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. }
  210. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  211. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  212. foundIDPeAcmeIdentifierV1Obsolete := false
  213. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  214. if err != nil {
  215. return err
  216. }
  217. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  218. for _, ext := range leafCert.Extensions {
  219. if idPeAcmeIdentifier.Equal(ext.Id) {
  220. if !ext.Critical {
  221. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  222. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  223. }
  224. var extValue []byte
  225. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  226. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  227. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  228. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  229. }
  230. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  231. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  232. "incorrect certificate for tls-alpn-01 challenge: "+
  233. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  234. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  235. }
  236. ch.Status = StatusValid
  237. ch.Error = nil
  238. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  239. if err = db.UpdateChallenge(ctx, ch); err != nil {
  240. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  241. }
  242. return nil
  243. }
  244. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  245. foundIDPeAcmeIdentifierV1Obsolete = true
  246. }
  247. }
  248. if foundIDPeAcmeIdentifierV1Obsolete {
  249. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  250. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  251. }
  252. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  253. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  254. }
  255. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  256. // Normalize domain for wildcard DNS names
  257. // This is done to avoid making TXT lookups for domains like
  258. // _acme-challenge.*.example.com
  259. // Instead perform txt lookup for _acme-challenge.example.com
  260. domain := strings.TrimPrefix(ch.Value, "*.")
  261. vc := MustClientFromContext(ctx)
  262. txtRecords, err := vc.LookupTxt("_acme-challenge." + domain)
  263. if err != nil {
  264. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  265. "error looking up TXT records for domain %s", domain))
  266. }
  267. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  268. if err != nil {
  269. return err
  270. }
  271. h := sha256.Sum256([]byte(expectedKeyAuth))
  272. expected := base64.RawURLEncoding.EncodeToString(h[:])
  273. var found bool
  274. for _, r := range txtRecords {
  275. if r == expected {
  276. found = true
  277. break
  278. }
  279. }
  280. if !found {
  281. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  282. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  283. }
  284. // Update and store the challenge.
  285. ch.Status = StatusValid
  286. ch.Error = nil
  287. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  288. if err = db.UpdateChallenge(ctx, ch); err != nil {
  289. return WrapErrorISE(err, "error updating challenge")
  290. }
  291. return nil
  292. }
  293. type payloadType struct {
  294. AttObj string `json:"attObj"`
  295. Error string `json:"error"`
  296. }
  297. type attestationObject struct {
  298. Format string `json:"fmt"`
  299. AttStatement map[string]interface{} `json:"attStmt,omitempty"`
  300. }
  301. // TODO(bweeks): move attestation verification to a shared package.
  302. func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  303. var p payloadType
  304. if err := json.Unmarshal(payload, &p); err != nil {
  305. return WrapErrorISE(err, "error unmarshalling JSON")
  306. }
  307. if p.Error != "" {
  308. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  309. "payload contained error: %v", p.Error))
  310. }
  311. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  312. if err != nil {
  313. return WrapErrorISE(err, "error base64 decoding attObj")
  314. }
  315. att := attestationObject{}
  316. if err := cbor.Unmarshal(attObj, &att); err != nil {
  317. return WrapErrorISE(err, "error unmarshalling CBOR")
  318. }
  319. prov := MustProvisionerFromContext(ctx)
  320. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(att.Format)) {
  321. return storeError(ctx, db, ch, true,
  322. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", att.Format))
  323. }
  324. switch att.Format {
  325. case "apple":
  326. data, err := doAppleAttestationFormat(ctx, prov, ch, &att)
  327. if err != nil {
  328. var acmeError *Error
  329. if errors.As(err, &acmeError) {
  330. if acmeError.Status == 500 {
  331. return acmeError
  332. }
  333. return storeError(ctx, db, ch, true, acmeError)
  334. }
  335. return WrapErrorISE(err, "error validating attestation")
  336. }
  337. // Validate nonce with SHA-256 of the token.
  338. if len(data.Nonce) != 0 {
  339. sum := sha256.Sum256([]byte(ch.Token))
  340. if subtle.ConstantTimeCompare(data.Nonce, sum[:]) != 1 {
  341. return storeError(ctx, db, ch, true, NewError(ErrorBadAttestationStatementType, "challenge token does not match"))
  342. }
  343. }
  344. // Validate Apple's ClientIdentifier (Identifier.Value) with device
  345. // identifiers.
  346. //
  347. // Note: We might want to use an external service for this.
  348. if data.UDID != ch.Value && data.SerialNumber != ch.Value {
  349. return storeError(ctx, db, ch, true, NewError(ErrorBadAttestationStatementType, "permanent identifier does not match"))
  350. }
  351. case "step":
  352. data, err := doStepAttestationFormat(ctx, prov, ch, jwk, &att)
  353. if err != nil {
  354. var acmeError *Error
  355. if errors.As(err, &acmeError) {
  356. if acmeError.Status == 500 {
  357. return acmeError
  358. }
  359. return storeError(ctx, db, ch, true, acmeError)
  360. }
  361. return WrapErrorISE(err, "error validating attestation")
  362. }
  363. // Validate the YubiKey serial number from the attestation
  364. // certificate with the challenged Order value.
  365. //
  366. // Note: We might want to use an external service for this.
  367. if data.SerialNumber != ch.Value {
  368. subproblem := NewSubproblemWithIdentifier(
  369. ErrorMalformedType,
  370. Identifier{Type: "permanent-identifier", Value: ch.Value},
  371. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  372. )
  373. return storeError(ctx, db, ch, true, NewError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  374. }
  375. default:
  376. return storeError(ctx, db, ch, true, NewError(ErrorBadAttestationStatementType, "unexpected attestation object format"))
  377. }
  378. // Update and store the challenge.
  379. ch.Status = StatusValid
  380. ch.Error = nil
  381. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  382. if err := db.UpdateChallenge(ctx, ch); err != nil {
  383. return WrapErrorISE(err, "error updating challenge")
  384. }
  385. return nil
  386. }
  387. // Apple Enterprise Attestation Root CA from
  388. // https://www.apple.com/certificateauthority/private/
  389. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  390. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  391. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  392. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  393. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  394. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  395. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  396. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  397. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  398. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  399. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  400. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  401. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  402. -----END CERTIFICATE-----`
  403. var (
  404. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  405. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  406. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  407. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  408. )
  409. type appleAttestationData struct {
  410. Nonce []byte
  411. SerialNumber string
  412. UDID string
  413. SEPVersion string
  414. Certificate *x509.Certificate
  415. }
  416. func doAppleAttestationFormat(ctx context.Context, prov Provisioner, ch *Challenge, att *attestationObject) (*appleAttestationData, error) {
  417. // Use configured or default attestation roots if none is configured.
  418. roots, ok := prov.GetAttestationRoots()
  419. if !ok {
  420. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  421. if err != nil {
  422. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  423. }
  424. roots = x509.NewCertPool()
  425. roots.AddCert(root)
  426. }
  427. x5c, ok := att.AttStatement["x5c"].([]interface{})
  428. if !ok {
  429. return nil, NewError(ErrorBadAttestationStatementType, "x5c not present")
  430. }
  431. if len(x5c) == 0 {
  432. return nil, NewError(ErrorRejectedIdentifierType, "x5c is empty")
  433. }
  434. der, ok := x5c[0].([]byte)
  435. if !ok {
  436. return nil, NewError(ErrorBadAttestationStatementType, "x5c is malformed")
  437. }
  438. leaf, err := x509.ParseCertificate(der)
  439. if err != nil {
  440. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  441. }
  442. intermediates := x509.NewCertPool()
  443. for _, v := range x5c[1:] {
  444. der, ok = v.([]byte)
  445. if !ok {
  446. return nil, NewError(ErrorBadAttestationStatementType, "x5c is malformed")
  447. }
  448. cert, err := x509.ParseCertificate(der)
  449. if err != nil {
  450. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  451. }
  452. intermediates.AddCert(cert)
  453. }
  454. if _, err := leaf.Verify(x509.VerifyOptions{
  455. Intermediates: intermediates,
  456. Roots: roots,
  457. CurrentTime: time.Now().Truncate(time.Second),
  458. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  459. }); err != nil {
  460. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  461. }
  462. data := &appleAttestationData{
  463. Certificate: leaf,
  464. }
  465. for _, ext := range leaf.Extensions {
  466. switch {
  467. case ext.Id.Equal(oidAppleSerialNumber):
  468. data.SerialNumber = string(ext.Value)
  469. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  470. data.UDID = string(ext.Value)
  471. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  472. data.SEPVersion = string(ext.Value)
  473. case ext.Id.Equal(oidAppleNonce):
  474. data.Nonce = ext.Value
  475. }
  476. }
  477. return data, nil
  478. }
  479. // Yubico PIV Root CA Serial 263751
  480. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  481. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  482. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  483. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  484. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  485. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  486. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  487. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  488. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  489. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  490. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  491. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  492. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  493. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  494. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  495. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  496. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  497. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  498. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  499. -----END CERTIFICATE-----`
  500. // Serial number of the YubiKey, encoded as an integer.
  501. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  502. var oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  503. type stepAttestationData struct {
  504. Certificate *x509.Certificate
  505. SerialNumber string
  506. }
  507. func doStepAttestationFormat(ctx context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  508. // Use configured or default attestation roots if none is configured.
  509. roots, ok := prov.GetAttestationRoots()
  510. if !ok {
  511. root, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  512. if err != nil {
  513. return nil, WrapErrorISE(err, "error parsing root ca")
  514. }
  515. roots = x509.NewCertPool()
  516. roots.AddCert(root)
  517. }
  518. // Extract x5c and verify certificate
  519. x5c, ok := att.AttStatement["x5c"].([]interface{})
  520. if !ok {
  521. return nil, NewError(ErrorBadAttestationStatementType, "x5c not present")
  522. }
  523. if len(x5c) == 0 {
  524. return nil, NewError(ErrorRejectedIdentifierType, "x5c is empty")
  525. }
  526. der, ok := x5c[0].([]byte)
  527. if !ok {
  528. return nil, NewError(ErrorBadAttestationStatementType, "x5c is malformed")
  529. }
  530. leaf, err := x509.ParseCertificate(der)
  531. if err != nil {
  532. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  533. }
  534. intermediates := x509.NewCertPool()
  535. for _, v := range x5c[1:] {
  536. der, ok = v.([]byte)
  537. if !ok {
  538. return nil, NewError(ErrorBadAttestationStatementType, "x5c is malformed")
  539. }
  540. cert, err := x509.ParseCertificate(der)
  541. if err != nil {
  542. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  543. }
  544. intermediates.AddCert(cert)
  545. }
  546. if _, err := leaf.Verify(x509.VerifyOptions{
  547. Intermediates: intermediates,
  548. Roots: roots,
  549. CurrentTime: time.Now().Truncate(time.Second),
  550. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  551. }); err != nil {
  552. return nil, WrapError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  553. }
  554. // Verify proof of possession of private key validating the key
  555. // authorization. Per recommendation at
  556. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  557. // signature is CBOR-encoded.
  558. var sig []byte
  559. csig, ok := att.AttStatement["sig"].([]byte)
  560. if !ok {
  561. return nil, NewError(ErrorBadAttestationStatementType, "sig not present")
  562. }
  563. if err := cbor.Unmarshal(csig, &sig); err != nil {
  564. return nil, NewError(ErrorBadAttestationStatementType, "sig is malformed")
  565. }
  566. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  567. if err != nil {
  568. return nil, err
  569. }
  570. switch pub := leaf.PublicKey.(type) {
  571. case *ecdsa.PublicKey:
  572. if pub.Curve != elliptic.P256() {
  573. return nil, WrapError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  574. }
  575. sum := sha256.Sum256([]byte(keyAuth))
  576. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  577. return nil, NewError(ErrorBadAttestationStatementType, "failed to validate signature")
  578. }
  579. case *rsa.PublicKey:
  580. sum := sha256.Sum256([]byte(keyAuth))
  581. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  582. return nil, NewError(ErrorBadAttestationStatementType, "failed to validate signature")
  583. }
  584. case ed25519.PublicKey:
  585. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  586. return nil, NewError(ErrorBadAttestationStatementType, "failed to validate signature")
  587. }
  588. default:
  589. return nil, NewError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  590. }
  591. // Parse attestation data:
  592. // TODO(mariano): add support for other extensions.
  593. data := &stepAttestationData{
  594. Certificate: leaf,
  595. }
  596. for _, ext := range leaf.Extensions {
  597. if !ext.Id.Equal(oidYubicoSerialNumber) {
  598. continue
  599. }
  600. var serialNumber int
  601. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  602. if err != nil || len(rest) > 0 {
  603. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  604. }
  605. data.SerialNumber = strconv.Itoa(serialNumber)
  606. break
  607. }
  608. return data, nil
  609. }
  610. // serverName determines the SNI HostName to set based on an acme.Challenge
  611. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  612. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  613. // It also references TLS Extensions [RFC6066].
  614. func serverName(ch *Challenge) string {
  615. var serverName string
  616. ip := net.ParseIP(ch.Value)
  617. if ip != nil {
  618. serverName = reverseAddr(ip)
  619. } else {
  620. serverName = ch.Value
  621. }
  622. return serverName
  623. }
  624. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  625. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  626. // to parse the IP address.
  627. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  628. func reverseAddr(ip net.IP) (arpa string) {
  629. if ip.To4() != nil {
  630. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  631. }
  632. // Must be IPv6
  633. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  634. // Add it, in reverse, to the buffer
  635. for i := len(ip) - 1; i >= 0; i-- {
  636. v := ip[i]
  637. buf = append(buf, hexit[v&0xF],
  638. '.',
  639. hexit[v>>4],
  640. '.')
  641. }
  642. // Append "ip6.arpa." and return (buf already has the final .)
  643. buf = append(buf, "ip6.arpa."...)
  644. return string(buf)
  645. }
  646. // Convert unsigned integer to decimal string.
  647. // Implementation taken from https://golang.org/src/net/parse.go
  648. func uitoa(val uint) string {
  649. if val == 0 { // avoid string allocation
  650. return "0"
  651. }
  652. var buf [20]byte // big enough for 64bit value base 10
  653. i := len(buf) - 1
  654. for val >= 10 {
  655. q := val / 10
  656. buf[i] = byte('0' + val - q*10)
  657. i--
  658. val = q
  659. }
  660. // val < 10
  661. buf[i] = byte('0' + val)
  662. return string(buf[i:])
  663. }
  664. const hexit = "0123456789abcdef"
  665. // KeyAuthorization creates the ACME key authorization value from a token
  666. // and a jwk.
  667. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  668. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  669. if err != nil {
  670. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  671. }
  672. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  673. return fmt.Sprintf("%s.%s", token, encPrint), nil
  674. }
  675. // storeError the given error to an ACME error and saves using the DB interface.
  676. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  677. ch.Error = err
  678. if markInvalid {
  679. ch.Status = StatusInvalid
  680. }
  681. if err := db.UpdateChallenge(ctx, ch); err != nil {
  682. return WrapErrorISE(err, "failure saving error to acme challenge")
  683. }
  684. return nil
  685. }