challenge.go 25 KB

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