challenge.go 26 KB

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