challenge.go 25 KB

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