challenge.go 24 KB

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