challenge.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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/google/go-tpm/legacy/tpm2"
  28. "github.com/smallstep/go-attestation/attest"
  29. "go.step.sm/crypto/jose"
  30. "go.step.sm/crypto/keyutil"
  31. "go.step.sm/crypto/pemutil"
  32. "go.step.sm/crypto/x509util"
  33. "golang.org/x/exp/slices"
  34. "github.com/smallstep/certificates/acme/wire"
  35. "github.com/smallstep/certificates/authority/provisioner"
  36. )
  37. type ChallengeType string
  38. const (
  39. // HTTP01 is the http-01 ACME challenge type
  40. HTTP01 ChallengeType = "http-01"
  41. // DNS01 is the dns-01 ACME challenge type
  42. DNS01 ChallengeType = "dns-01"
  43. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  44. TLSALPN01 ChallengeType = "tls-alpn-01"
  45. // DEVICEATTEST01 is the device-attest-01 ACME challenge type
  46. DEVICEATTEST01 ChallengeType = "device-attest-01"
  47. // WIREOIDC01 is the Wire OIDC challenge type
  48. WIREOIDC01 ChallengeType = "wire-oidc-01"
  49. // WIREDPOP01 is the Wire DPoP challenge type
  50. WIREDPOP01 ChallengeType = "wire-dpop-01"
  51. )
  52. var (
  53. // InsecurePortHTTP01 is the port used to verify http-01 challenges. If not set it
  54. // defaults to 80.
  55. InsecurePortHTTP01 int
  56. // InsecurePortTLSALPN01 is the port used to verify tls-alpn-01 challenges. If not
  57. // set it defaults to 443.
  58. //
  59. // This variable can be used for testing purposes.
  60. InsecurePortTLSALPN01 int
  61. )
  62. // Challenge represents an ACME response Challenge type.
  63. type Challenge struct {
  64. ID string `json:"-"`
  65. AccountID string `json:"-"`
  66. AuthorizationID string `json:"-"`
  67. Value string `json:"-"`
  68. Type ChallengeType `json:"type"`
  69. Status Status `json:"status"`
  70. Token string `json:"token"`
  71. ValidatedAt string `json:"validated,omitempty"`
  72. URL string `json:"url"`
  73. Target string `json:"target,omitempty"`
  74. Error *Error `json:"error,omitempty"`
  75. }
  76. // ToLog enables response logging.
  77. func (ch *Challenge) ToLog() (interface{}, error) {
  78. b, err := json.Marshal(ch)
  79. if err != nil {
  80. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  81. }
  82. return string(b), nil
  83. }
  84. // Validate attempts to validate the Challenge. Stores changes to the Challenge
  85. // type using the DB interface. If the Challenge is validated, the 'status' and
  86. // 'validated' attributes are updated.
  87. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  88. // If already valid or invalid then return without performing validation.
  89. if ch.Status != StatusPending {
  90. return nil
  91. }
  92. switch ch.Type {
  93. case HTTP01:
  94. return http01Validate(ctx, ch, db, jwk)
  95. case DNS01:
  96. return dns01Validate(ctx, ch, db, jwk)
  97. case TLSALPN01:
  98. return tlsalpn01Validate(ctx, ch, db, jwk)
  99. case DEVICEATTEST01:
  100. return deviceAttest01Validate(ctx, ch, db, jwk, payload)
  101. case WIREOIDC01:
  102. return wireOIDC01Validate(ctx, ch, db, jwk, payload)
  103. case WIREDPOP01:
  104. return wireDPOP01Validate(ctx, ch, db, jwk, payload)
  105. default:
  106. return NewErrorISE("unexpected challenge type '%s'", ch.Type)
  107. }
  108. }
  109. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  110. u := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  111. // Append insecure port if set.
  112. // Only used for testing purposes.
  113. if InsecurePortHTTP01 != 0 {
  114. u.Host += ":" + strconv.Itoa(InsecurePortHTTP01)
  115. }
  116. vc := MustClientFromContext(ctx)
  117. resp, err := vc.Get(u.String())
  118. if err != nil {
  119. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  120. "error doing http GET for url %s", u))
  121. }
  122. defer resp.Body.Close()
  123. if resp.StatusCode >= 400 {
  124. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  125. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  126. }
  127. body, err := io.ReadAll(resp.Body)
  128. if err != nil {
  129. return WrapErrorISE(err, "error reading "+
  130. "response body for url %s", u)
  131. }
  132. keyAuth := strings.TrimSpace(string(body))
  133. expected, err := KeyAuthorization(ch.Token, jwk)
  134. if err != nil {
  135. return err
  136. }
  137. if keyAuth != expected {
  138. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  139. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  140. }
  141. // Update and store the challenge.
  142. ch.Status = StatusValid
  143. ch.Error = nil
  144. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  145. if err = db.UpdateChallenge(ctx, ch); err != nil {
  146. return WrapErrorISE(err, "error updating challenge")
  147. }
  148. return nil
  149. }
  150. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  151. // and adds square brackets if that's the case, so that it can be used
  152. // as a hostname. Returns the original Challenge value as the host to
  153. // use in other cases.
  154. func http01ChallengeHost(value string) string {
  155. if ip := net.ParseIP(value); ip != nil && ip.To4() == nil {
  156. value = "[" + value + "]"
  157. }
  158. return value
  159. }
  160. func tlsAlert(err error) uint8 {
  161. var opErr *net.OpError
  162. if errors.As(err, &opErr) {
  163. v := reflect.ValueOf(opErr.Err)
  164. if v.Kind() == reflect.Uint8 {
  165. return uint8(v.Uint())
  166. }
  167. }
  168. return 0
  169. }
  170. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  171. config := &tls.Config{
  172. NextProtos: []string{"acme-tls/1"},
  173. // https://tools.ietf.org/html/rfc8737#section-4
  174. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  175. // [RFC5246] or higher when connecting to clients for validation.
  176. MinVersion: tls.VersionTLS12,
  177. ServerName: serverName(ch),
  178. InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate
  179. }
  180. var hostPort string
  181. // Allow to change TLS port for testing purposes.
  182. if port := InsecurePortTLSALPN01; port == 0 {
  183. hostPort = net.JoinHostPort(ch.Value, "443")
  184. } else {
  185. hostPort = net.JoinHostPort(ch.Value, strconv.Itoa(port))
  186. }
  187. vc := MustClientFromContext(ctx)
  188. conn, err := vc.TLSDial("tcp", hostPort, config)
  189. if err != nil {
  190. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  191. // client and server protocols. When this happens the connection is
  192. // closed with the error no_application_protocol(120) as required by
  193. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  194. if tlsAlert(err) == 120 {
  195. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  196. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  197. }
  198. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  199. "error doing TLS dial for %s", hostPort))
  200. }
  201. defer conn.Close()
  202. cs := conn.ConnectionState()
  203. certs := cs.PeerCertificates
  204. if len(certs) == 0 {
  205. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  206. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  207. }
  208. if cs.NegotiatedProtocol != "acme-tls/1" {
  209. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  210. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  211. }
  212. leafCert := certs[0]
  213. // if no DNS names present, look for IP address and verify that exactly one exists
  214. if len(leafCert.DNSNames) == 0 {
  215. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  216. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  217. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  218. }
  219. } else {
  220. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], ch.Value) {
  221. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  222. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  223. }
  224. }
  225. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  226. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  227. foundIDPeAcmeIdentifierV1Obsolete := false
  228. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  229. if err != nil {
  230. return err
  231. }
  232. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  233. for _, ext := range leafCert.Extensions {
  234. if idPeAcmeIdentifier.Equal(ext.Id) {
  235. if !ext.Critical {
  236. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  237. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  238. }
  239. var extValue []byte
  240. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  241. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  242. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  243. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  244. }
  245. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  246. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  247. "incorrect certificate for tls-alpn-01 challenge: "+
  248. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  249. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  250. }
  251. ch.Status = StatusValid
  252. ch.Error = nil
  253. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  254. if err = db.UpdateChallenge(ctx, ch); err != nil {
  255. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  256. }
  257. return nil
  258. }
  259. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  260. foundIDPeAcmeIdentifierV1Obsolete = true
  261. }
  262. }
  263. if foundIDPeAcmeIdentifierV1Obsolete {
  264. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  265. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  266. }
  267. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  268. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  269. }
  270. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  271. // Normalize domain for wildcard DNS names
  272. // This is done to avoid making TXT lookups for domains like
  273. // _acme-challenge.*.example.com
  274. // Instead perform txt lookup for _acme-challenge.example.com
  275. domain := strings.TrimPrefix(ch.Value, "*.")
  276. vc := MustClientFromContext(ctx)
  277. txtRecords, err := vc.LookupTxt("_acme-challenge." + domain)
  278. if err != nil {
  279. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  280. "error looking up TXT records for domain %s", domain))
  281. }
  282. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  283. if err != nil {
  284. return err
  285. }
  286. h := sha256.Sum256([]byte(expectedKeyAuth))
  287. expected := base64.RawURLEncoding.EncodeToString(h[:])
  288. var found bool
  289. for _, r := range txtRecords {
  290. if r == expected {
  291. found = true
  292. break
  293. }
  294. }
  295. if !found {
  296. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  297. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  298. }
  299. // Update and store the challenge.
  300. ch.Status = StatusValid
  301. ch.Error = nil
  302. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  303. if err = db.UpdateChallenge(ctx, ch); err != nil {
  304. return WrapErrorISE(err, "error updating challenge")
  305. }
  306. return nil
  307. }
  308. type wireOidcPayload struct {
  309. // IDToken contains the OIDC identity token
  310. IDToken string `json:"id_token"`
  311. // KeyAuth ({challenge-token}.{jwk-thumbprint})
  312. KeyAuth string `json:"keyauth"`
  313. }
  314. func wireOIDC01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  315. prov, ok := ProvisionerFromContext(ctx)
  316. if !ok {
  317. return NewErrorISE("no provisioner provided")
  318. }
  319. var oidcPayload wireOidcPayload
  320. err := json.Unmarshal(payload, &oidcPayload)
  321. if err != nil {
  322. return storeError(ctx, db, ch, false, WrapError(ErrorRejectedIdentifierType, err,
  323. "error unmarshalling Wire challenge payload"))
  324. }
  325. wireOptions, err := prov.GetOptions().GetWireOptions()
  326. if err != nil {
  327. return WrapErrorISE(err, "failed getting Wire options")
  328. }
  329. oidcOptions := wireOptions.GetOIDCOptions()
  330. idToken, err := oidcOptions.GetProvider(ctx).Verifier(oidcOptions.GetConfig()).Verify(ctx, oidcPayload.IDToken)
  331. if err != nil {
  332. return storeError(ctx, db, ch, false, WrapError(ErrorRejectedIdentifierType, err,
  333. "error verifying ID token signature"))
  334. }
  335. var claims struct {
  336. Name string `json:"preferred_username,omitempty"`
  337. Handle string `json:"name"`
  338. Issuer string `json:"iss,omitempty"`
  339. GivenName string `json:"given_name,omitempty"`
  340. KeyAuth string `json:"keyauth"` // TODO(hs): use this property instead of the one in the payload after https://github.com/wireapp/rusty-jwt-tools/tree/fix/keyauth is done
  341. }
  342. if err := idToken.Claims(&claims); err != nil {
  343. return storeError(ctx, db, ch, false, WrapError(ErrorRejectedIdentifierType, err,
  344. "error retrieving claims from ID token"))
  345. }
  346. wireID, err := wire.ParseID([]byte(ch.Value))
  347. if err != nil {
  348. return WrapErrorISE(err, "error unmarshalling challenge data")
  349. }
  350. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  351. if err != nil {
  352. return err
  353. }
  354. if expectedKeyAuth != oidcPayload.KeyAuth {
  355. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  356. "keyAuthorization does not match; expected %q, but got %q", expectedKeyAuth, oidcPayload.KeyAuth))
  357. }
  358. if wireID.Name != claims.Name || wireID.Handle != claims.Handle {
  359. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType, "claims in OIDC ID token don't match"))
  360. }
  361. // Update and store the challenge.
  362. ch.Status = StatusValid
  363. ch.Error = nil
  364. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  365. if err = db.UpdateChallenge(ctx, ch); err != nil {
  366. return WrapErrorISE(err, "error updating challenge")
  367. }
  368. parsedIDToken, err := jose.ParseSigned(oidcPayload.IDToken)
  369. if err != nil {
  370. return WrapErrorISE(err, "invalid OIDC ID token")
  371. }
  372. oidcToken := make(map[string]interface{})
  373. if err := parsedIDToken.UnsafeClaimsWithoutVerification(&oidcToken); err != nil {
  374. return WrapErrorISE(err, "failed parsing OIDC id token")
  375. }
  376. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  377. if err != nil {
  378. return WrapErrorISE(err, "could not find current order by account id")
  379. }
  380. if len(orders) == 0 {
  381. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  382. }
  383. order := orders[len(orders)-1]
  384. if err := db.CreateOidcToken(ctx, order, oidcToken); err != nil {
  385. return WrapErrorISE(err, "failed storing OIDC id token")
  386. }
  387. return nil
  388. }
  389. type wireDpopPayload struct {
  390. // AccessToken is the token generated by wire-server
  391. AccessToken string `json:"access_token"`
  392. }
  393. func wireDPOP01Validate(ctx context.Context, ch *Challenge, db DB, accountJWK *jose.JSONWebKey, payload []byte) error {
  394. prov, ok := ProvisionerFromContext(ctx)
  395. if !ok {
  396. return NewErrorISE("missing provisioner")
  397. }
  398. var dpopPayload wireDpopPayload
  399. if err := json.Unmarshal(payload, &dpopPayload); err != nil {
  400. return storeError(ctx, db, ch, false, WrapError(ErrorRejectedIdentifierType, err,
  401. "error unmarshalling Wire challenge payload"))
  402. }
  403. wireID, err := wire.ParseID([]byte(ch.Value))
  404. if err != nil {
  405. return WrapErrorISE(err, "error unmarshalling challenge data")
  406. }
  407. clientID, err := wire.ParseClientID(wireID.ClientID)
  408. if err != nil {
  409. return WrapErrorISE(err, "error parsing device id")
  410. }
  411. wireOptions, err := prov.GetOptions().GetWireOptions()
  412. if err != nil {
  413. return WrapErrorISE(err, "failed getting Wire options")
  414. }
  415. dpopOptions := wireOptions.GetDPOPOptions()
  416. issuer, err := dpopOptions.EvaluateTarget(clientID.DeviceID)
  417. if err != nil {
  418. return WrapErrorISE(err, "invalid Go template registered for 'target'")
  419. }
  420. params := wireVerifyParams{
  421. token: dpopPayload.AccessToken,
  422. tokenKey: dpopOptions.GetSigningKey(),
  423. dpopKey: accountJWK.Public(),
  424. dpopKeyID: accountJWK.KeyID,
  425. issuer: issuer,
  426. wireID: wireID,
  427. chToken: ch.Token,
  428. t: clock.Now().UTC(),
  429. }
  430. _, dpop, err := parseAndVerifyWireAccessToken(params)
  431. if err != nil {
  432. return WrapErrorISE(err, "failed validating token")
  433. }
  434. // Update and store the challenge.
  435. ch.Status = StatusValid
  436. ch.Error = nil
  437. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  438. if err = db.UpdateChallenge(ctx, ch); err != nil {
  439. return WrapErrorISE(err, "error updating challenge")
  440. }
  441. orders, err := db.GetAllOrdersByAccountID(ctx, ch.AccountID)
  442. if err != nil {
  443. return WrapErrorISE(err, "could not find current order by account id")
  444. }
  445. if len(orders) == 0 {
  446. return NewErrorISE("there are not enough orders for this account for this custom OIDC challenge")
  447. }
  448. order := orders[len(orders)-1]
  449. if err := db.CreateDpopToken(ctx, order, dpop); err != nil {
  450. return WrapErrorISE(err, "failed storing DPoP token")
  451. }
  452. return nil
  453. }
  454. type wireCnf struct {
  455. Kid string `json:"kid,omitempty"`
  456. }
  457. type wireAccessToken struct {
  458. jose.Claims
  459. Challenge string `json:"chal,omitempty"`
  460. Cnf wireCnf `json:"cnf,omitempty"`
  461. Proof string `json:"proof,omitempty"`
  462. ClientID string `json:"client_id,omitempty"`
  463. APIVersion int `json:"api_version,omitempty"`
  464. Scope string `json:"scope,omitempty"`
  465. }
  466. type WireDpopToken struct {
  467. jose.Claims
  468. Nonce string `json:"nonce,omitempty"`
  469. Method string `json:"htm,omitempty"`
  470. URL string `json:"htu,omitempty"`
  471. Challenge string `json:"chal,omitempty"`
  472. Handle string `json:"handle,omitempty"`
  473. Team string `json:"team,omitempty"`
  474. }
  475. type wireVerifyParams struct {
  476. token string
  477. tokenKey crypto.PublicKey
  478. dpopKey crypto.PublicKey
  479. dpopKeyID string
  480. issuer string
  481. wireID wire.ID
  482. chToken string
  483. t time.Time
  484. }
  485. func parseAndVerifyWireAccessToken(v wireVerifyParams) (*wireAccessToken, *WireDpopToken, error) {
  486. jwt, err := jose.ParseSigned(v.token)
  487. if err != nil {
  488. return nil, nil, fmt.Errorf("failed parsing token: %w", err)
  489. }
  490. var accessToken wireAccessToken
  491. if err = jwt.Claims(v.tokenKey, &accessToken); err != nil {
  492. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  493. }
  494. if err := accessToken.ValidateWithLeeway(jose.Expected{
  495. Time: v.t,
  496. Issuer: v.issuer,
  497. }, 360*time.Second); err != nil {
  498. return nil, nil, fmt.Errorf("failed validation: %w", err)
  499. }
  500. if accessToken.Cnf.Kid != v.dpopKeyID {
  501. return nil, nil, fmt.Errorf("expected kid %q; got %q", v.dpopKeyID, accessToken.Cnf.Kid)
  502. }
  503. if accessToken.ClientID != v.wireID.ClientID {
  504. return nil, nil, fmt.Errorf("invalid Wire client ID %q", accessToken.ClientID)
  505. }
  506. if accessToken.Expiry.Time().After(v.t.Add(time.Hour * 24 * 365)) {
  507. return nil, nil, fmt.Errorf("'exp' %s is too far into the future", accessToken.Expiry.Time().String())
  508. }
  509. dpopJWT, err := jose.ParseSigned(accessToken.Proof)
  510. if err != nil {
  511. return nil, nil, fmt.Errorf("invalid Wire DPoP token: %w", err)
  512. }
  513. var dpopToken WireDpopToken
  514. if err := dpopJWT.Claims(v.dpopKey, &dpopToken); err != nil {
  515. return nil, nil, fmt.Errorf("failed validating Wire DPoP token claims: %w", err)
  516. }
  517. if dpopToken.Challenge != v.chToken {
  518. return nil, nil, fmt.Errorf("invalid Wire DPoP challenge %q", dpopToken.Challenge)
  519. }
  520. if dpopToken.Handle != v.wireID.Handle {
  521. return nil, nil, fmt.Errorf("invalid Wire client handle %q", dpopToken.Handle)
  522. }
  523. return &accessToken, &dpopToken, nil
  524. }
  525. type payloadType struct {
  526. AttObj string `json:"attObj"`
  527. Error string `json:"error"`
  528. }
  529. type attestationObject struct {
  530. Format string `json:"fmt"`
  531. AttStatement map[string]interface{} `json:"attStmt,omitempty"`
  532. }
  533. // TODO(bweeks): move attestation verification to a shared package.
  534. func deviceAttest01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey, payload []byte) error {
  535. // Load authorization to store the key fingerprint.
  536. az, err := db.GetAuthorization(ctx, ch.AuthorizationID)
  537. if err != nil {
  538. return WrapErrorISE(err, "error loading authorization")
  539. }
  540. // Parse payload.
  541. var p payloadType
  542. if err := json.Unmarshal(payload, &p); err != nil {
  543. return WrapErrorISE(err, "error unmarshalling JSON")
  544. }
  545. if p.Error != "" {
  546. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  547. "payload contained error: %v", p.Error))
  548. }
  549. attObj, err := base64.RawURLEncoding.DecodeString(p.AttObj)
  550. if err != nil {
  551. return WrapErrorISE(err, "error base64 decoding attObj")
  552. }
  553. att := attestationObject{}
  554. if err := cbor.Unmarshal(attObj, &att); err != nil {
  555. return WrapErrorISE(err, "error unmarshalling CBOR")
  556. }
  557. format := att.Format
  558. prov := MustProvisionerFromContext(ctx)
  559. if !prov.IsAttestationFormatEnabled(ctx, provisioner.ACMEAttestationFormat(format)) {
  560. if format != "apple" && format != "step" && format != "tpm" {
  561. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  562. }
  563. return storeError(ctx, db, ch, true,
  564. NewError(ErrorBadAttestationStatementType, "attestation format %q is not enabled", format))
  565. }
  566. switch format {
  567. case "apple":
  568. data, err := doAppleAttestationFormat(ctx, prov, ch, &att)
  569. if err != nil {
  570. var acmeError *Error
  571. if errors.As(err, &acmeError) {
  572. if acmeError.Status == 500 {
  573. return acmeError
  574. }
  575. return storeError(ctx, db, ch, true, acmeError)
  576. }
  577. return WrapErrorISE(err, "error validating attestation")
  578. }
  579. // Validate nonce with SHA-256 of the token.
  580. if len(data.Nonce) != 0 {
  581. sum := sha256.Sum256([]byte(ch.Token))
  582. if subtle.ConstantTimeCompare(data.Nonce, sum[:]) != 1 {
  583. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "challenge token does not match"))
  584. }
  585. }
  586. // Validate Apple's ClientIdentifier (Identifier.Value) with device
  587. // identifiers.
  588. //
  589. // Note: We might want to use an external service for this.
  590. if data.UDID != ch.Value && data.SerialNumber != ch.Value {
  591. subproblem := NewSubproblemWithIdentifier(
  592. ErrorRejectedIdentifierType,
  593. Identifier{Type: "permanent-identifier", Value: ch.Value},
  594. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, []string{data.UDID, data.SerialNumber},
  595. )
  596. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  597. }
  598. // Update attestation key fingerprint to compare against the CSR
  599. az.Fingerprint = data.Fingerprint
  600. case "step":
  601. data, err := doStepAttestationFormat(ctx, prov, ch, jwk, &att)
  602. if err != nil {
  603. var acmeError *Error
  604. if errors.As(err, &acmeError) {
  605. if acmeError.Status == 500 {
  606. return acmeError
  607. }
  608. return storeError(ctx, db, ch, true, acmeError)
  609. }
  610. return WrapErrorISE(err, "error validating attestation")
  611. }
  612. // Validate the YubiKey serial number from the attestation
  613. // certificate with the challenged Order value.
  614. //
  615. // Note: We might want to use an external service for this.
  616. if data.SerialNumber != ch.Value {
  617. subproblem := NewSubproblemWithIdentifier(
  618. ErrorRejectedIdentifierType,
  619. Identifier{Type: "permanent-identifier", Value: ch.Value},
  620. "challenge identifier %q doesn't match the attested hardware identifier %q", ch.Value, data.SerialNumber,
  621. )
  622. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  623. }
  624. // Update attestation key fingerprint to compare against the CSR
  625. az.Fingerprint = data.Fingerprint
  626. case "tpm":
  627. data, err := doTPMAttestationFormat(ctx, prov, ch, jwk, &att)
  628. if err != nil {
  629. var acmeError *Error
  630. if errors.As(err, &acmeError) {
  631. if acmeError.Status == 500 {
  632. return acmeError
  633. }
  634. return storeError(ctx, db, ch, true, acmeError)
  635. }
  636. return WrapErrorISE(err, "error validating attestation")
  637. }
  638. // TODO(hs): currently this will allow a request for which no PermanentIdentifiers have been
  639. // extracted from the AK certificate. This is currently the case for AK certs from the CLI, as we
  640. // haven't implemented a way for AK certs requested by the CLI to always contain the requested
  641. // PermanentIdentifier. Omitting the check below doesn't allow just any request, as the Order can
  642. // still fail if the challenge value isn't equal to the CSR subject.
  643. if len(data.PermanentIdentifiers) > 0 && !slices.Contains(data.PermanentIdentifiers, ch.Value) { // TODO(hs): add support for HardwareModuleName
  644. subproblem := NewSubproblemWithIdentifier(
  645. ErrorRejectedIdentifierType,
  646. Identifier{Type: "permanent-identifier", Value: ch.Value},
  647. "challenge identifier %q doesn't match any of the attested hardware identifiers %q", ch.Value, data.PermanentIdentifiers,
  648. )
  649. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "permanent identifier does not match").AddSubproblems(subproblem))
  650. }
  651. // Update attestation key fingerprint to compare against the CSR
  652. az.Fingerprint = data.Fingerprint
  653. default:
  654. return storeError(ctx, db, ch, true, NewDetailedError(ErrorBadAttestationStatementType, "unsupported attestation object format %q", format))
  655. }
  656. // Update and store the challenge.
  657. ch.Status = StatusValid
  658. ch.Error = nil
  659. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  660. // Store the fingerprint in the authorization.
  661. //
  662. // TODO: add method to update authorization and challenge atomically.
  663. if az.Fingerprint != "" {
  664. if err := db.UpdateAuthorization(ctx, az); err != nil {
  665. return WrapErrorISE(err, "error updating authorization")
  666. }
  667. }
  668. if err := db.UpdateChallenge(ctx, ch); err != nil {
  669. return WrapErrorISE(err, "error updating challenge")
  670. }
  671. return nil
  672. }
  673. var (
  674. oidSubjectAlternativeName = asn1.ObjectIdentifier{2, 5, 29, 17}
  675. )
  676. type tpmAttestationData struct {
  677. Certificate *x509.Certificate
  678. VerifiedChains [][]*x509.Certificate
  679. PermanentIdentifiers []string
  680. Fingerprint string
  681. }
  682. // coseAlgorithmIdentifier models a COSEAlgorithmIdentifier.
  683. // Also see https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier.
  684. type coseAlgorithmIdentifier int32
  685. const (
  686. coseAlgES256 coseAlgorithmIdentifier = -7
  687. coseAlgRS256 coseAlgorithmIdentifier = -257
  688. coseAlgRS1 coseAlgorithmIdentifier = -65535 // deprecated, but (still) often used in TPMs
  689. )
  690. func doTPMAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*tpmAttestationData, error) {
  691. ver, ok := att.AttStatement["ver"].(string)
  692. if !ok {
  693. return nil, NewDetailedError(ErrorBadAttestationStatementType, "ver not present")
  694. }
  695. if ver != "2.0" {
  696. return nil, NewDetailedError(ErrorBadAttestationStatementType, "version %q is not supported", ver)
  697. }
  698. x5c, ok := att.AttStatement["x5c"].([]interface{})
  699. if !ok {
  700. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  701. }
  702. if len(x5c) == 0 {
  703. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  704. }
  705. akCertBytes, ok := x5c[0].([]byte)
  706. if !ok {
  707. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  708. }
  709. akCert, err := x509.ParseCertificate(akCertBytes)
  710. if err != nil {
  711. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  712. }
  713. intermediates := x509.NewCertPool()
  714. for _, v := range x5c[1:] {
  715. intCertBytes, vok := v.([]byte)
  716. if !vok {
  717. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  718. }
  719. intCert, err := x509.ParseCertificate(intCertBytes)
  720. if err != nil {
  721. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  722. }
  723. intermediates.AddCert(intCert)
  724. }
  725. // TODO(hs): this can be removed when permanent-identifier/hardware-module-name are handled correctly in
  726. // the stdlib in https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/crypto/x509/parser.go;drc=b5b2cf519fe332891c165077f3723ee74932a647;l=362,
  727. // but I doubt that will happen.
  728. if len(akCert.UnhandledCriticalExtensions) > 0 {
  729. unhandledCriticalExtensions := akCert.UnhandledCriticalExtensions[:0]
  730. for _, extOID := range akCert.UnhandledCriticalExtensions {
  731. if !extOID.Equal(oidSubjectAlternativeName) {
  732. // critical extensions other than the Subject Alternative Name remain unhandled
  733. unhandledCriticalExtensions = append(unhandledCriticalExtensions, extOID)
  734. }
  735. }
  736. akCert.UnhandledCriticalExtensions = unhandledCriticalExtensions
  737. }
  738. roots, ok := prov.GetAttestationRoots()
  739. if !ok {
  740. return nil, NewErrorISE("no root CA bundle available to verify the attestation certificate")
  741. }
  742. // verify that the AK certificate was signed by a trusted root,
  743. // chained to by the intermediates provided by the client. As part
  744. // of building the verified certificate chain, the signature over the
  745. // AK certificate is checked to be a valid signature of one of the
  746. // provided intermediates. Signatures over the intermediates are in
  747. // turn also verified to be valid signatures from one of the trusted
  748. // roots.
  749. verifiedChains, err := akCert.Verify(x509.VerifyOptions{
  750. Roots: roots,
  751. Intermediates: intermediates,
  752. CurrentTime: time.Now().Truncate(time.Second),
  753. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  754. })
  755. if err != nil {
  756. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  757. }
  758. // validate additional AK certificate requirements
  759. if err := validateAKCertificate(akCert); err != nil {
  760. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "AK certificate is not valid")
  761. }
  762. // TODO(hs): implement revocation check; Verify() doesn't perform CRL check nor OCSP lookup.
  763. sans, err := x509util.ParseSubjectAlternativeNames(akCert)
  764. if err != nil {
  765. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed parsing AK certificate Subject Alternative Names")
  766. }
  767. permanentIdentifiers := make([]string, len(sans.PermanentIdentifiers))
  768. for i, pi := range sans.PermanentIdentifiers {
  769. permanentIdentifiers[i] = pi.Identifier
  770. }
  771. // extract and validate pubArea, sig, certInfo and alg properties from the request body
  772. pubArea, ok := att.AttStatement["pubArea"].([]byte)
  773. if !ok {
  774. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid pubArea in attestation statement")
  775. }
  776. if len(pubArea) == 0 {
  777. return nil, NewDetailedError(ErrorBadAttestationStatementType, "pubArea is empty")
  778. }
  779. sig, ok := att.AttStatement["sig"].([]byte)
  780. if !ok {
  781. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid sig in attestation statement")
  782. }
  783. if len(sig) == 0 {
  784. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is empty")
  785. }
  786. certInfo, ok := att.AttStatement["certInfo"].([]byte)
  787. if !ok {
  788. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid certInfo in attestation statement")
  789. }
  790. if len(certInfo) == 0 {
  791. return nil, NewDetailedError(ErrorBadAttestationStatementType, "certInfo is empty")
  792. }
  793. alg, ok := att.AttStatement["alg"].(int64)
  794. if !ok {
  795. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg in attestation statement")
  796. }
  797. var hash crypto.Hash
  798. switch coseAlgorithmIdentifier(alg) {
  799. case coseAlgRS256, coseAlgES256:
  800. hash = crypto.SHA256
  801. case coseAlgRS1:
  802. hash = crypto.SHA1
  803. default:
  804. return nil, NewDetailedError(ErrorBadAttestationStatementType, "invalid alg %d in attestation statement", alg)
  805. }
  806. // recreate the generated key certification parameter values and verify
  807. // the attested key using the public key of the AK.
  808. certificationParameters := &attest.CertificationParameters{
  809. Public: pubArea, // the public key that was attested
  810. CreateAttestation: certInfo, // the attested properties of the key
  811. CreateSignature: sig, // signature over the attested properties
  812. }
  813. verifyOpts := attest.VerifyOpts{
  814. Public: akCert.PublicKey, // public key of the AK that attested the key
  815. Hash: hash,
  816. }
  817. if err = certificationParameters.Verify(verifyOpts); err != nil {
  818. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "invalid certification parameters")
  819. }
  820. // decode the "certInfo" data. This won't fail, as it's also done as part of Verify().
  821. tpmCertInfo, err := tpm2.DecodeAttestationData(certInfo)
  822. if err != nil {
  823. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding attestation data")
  824. }
  825. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  826. if err != nil {
  827. return nil, WrapErrorISE(err, "failed creating key auth digest")
  828. }
  829. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  830. // verify the WebAuthn object contains the expect key authorization digest, which is carried
  831. // within the encoded `certInfo` property of the attestation statement.
  832. if subtle.ConstantTimeCompare(hashedKeyAuth[:], []byte(tpmCertInfo.ExtraData)) == 0 {
  833. return nil, NewDetailedError(ErrorBadAttestationStatementType, "key authorization invalid")
  834. }
  835. // decode the (attested) public key and determine its fingerprint. This won't fail, as it's also done as part of Verify().
  836. pub, err := tpm2.DecodePublic(pubArea)
  837. if err != nil {
  838. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed decoding pubArea")
  839. }
  840. publicKey, err := pub.Key()
  841. if err != nil {
  842. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "failed getting public key")
  843. }
  844. data := &tpmAttestationData{
  845. Certificate: akCert,
  846. VerifiedChains: verifiedChains,
  847. PermanentIdentifiers: permanentIdentifiers,
  848. }
  849. if data.Fingerprint, err = keyutil.Fingerprint(publicKey); err != nil {
  850. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  851. }
  852. // TODO(hs): pass more attestation data, so that that can be used/recorded too?
  853. return data, nil
  854. }
  855. var (
  856. oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
  857. oidTCGKpAIKCertificate = asn1.ObjectIdentifier{2, 23, 133, 8, 3}
  858. )
  859. // validateAKCertifiate validates the X.509 AK certificate to be
  860. // in accordance with the required properties. The requirements come from:
  861. // https://www.w3.org/TR/webauthn-2/#sctn-tpm-cert-requirements.
  862. //
  863. // - Version MUST be set to 3.
  864. // - Subject field MUST be set to empty.
  865. // - The Subject Alternative Name extension MUST be set as defined
  866. // in [TPMv2-EK-Profile] section 3.2.9.
  867. // - The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
  868. // ("joint-iso-itu-t(2) internationalorganizations(23) 133 tcg-kp(8) tcg-kp-AIKCertificate(3)").
  869. // - The Basic Constraints extension MUST have the CA component set to false.
  870. // - An Authority Information Access (AIA) extension with entry id-ad-ocsp
  871. // and a CRL Distribution Point extension [RFC5280] are both OPTIONAL as
  872. // the status of many attestation certificates is available through metadata
  873. // services. See, for example, the FIDO Metadata Service.
  874. func validateAKCertificate(c *x509.Certificate) error {
  875. if c.Version != 3 {
  876. return fmt.Errorf("AK certificate has invalid version %d; only version 3 is allowed", c.Version)
  877. }
  878. if c.Subject.String() != "" {
  879. return fmt.Errorf("AK certificate subject must be empty; got %q", c.Subject)
  880. }
  881. if c.IsCA {
  882. return errors.New("AK certificate must not be a CA")
  883. }
  884. if err := validateAKCertificateExtendedKeyUsage(c); err != nil {
  885. return err
  886. }
  887. return validateAKCertificateSubjectAlternativeNames(c)
  888. }
  889. // validateAKCertificateSubjectAlternativeNames checks if the AK certificate
  890. // has TPM hardware details set.
  891. func validateAKCertificateSubjectAlternativeNames(c *x509.Certificate) error {
  892. sans, err := x509util.ParseSubjectAlternativeNames(c)
  893. if err != nil {
  894. return fmt.Errorf("failed parsing AK certificate Subject Alternative Names: %w", err)
  895. }
  896. details := sans.TPMHardwareDetails
  897. manufacturer, model, version := details.Manufacturer, details.Model, details.Version
  898. switch {
  899. case manufacturer == "":
  900. return errors.New("missing TPM manufacturer")
  901. case model == "":
  902. return errors.New("missing TPM model")
  903. case version == "":
  904. return errors.New("missing TPM version")
  905. }
  906. return nil
  907. }
  908. // validateAKCertificateExtendedKeyUsage checks if the AK certificate
  909. // has the "tcg-kp-AIKCertificate" Extended Key Usage set.
  910. func validateAKCertificateExtendedKeyUsage(c *x509.Certificate) error {
  911. var (
  912. valid = false
  913. ekus []asn1.ObjectIdentifier
  914. )
  915. for _, ext := range c.Extensions {
  916. if ext.Id.Equal(oidExtensionExtendedKeyUsage) {
  917. if _, err := asn1.Unmarshal(ext.Value, &ekus); err != nil || !ekus[0].Equal(oidTCGKpAIKCertificate) {
  918. return errors.New("AK certificate is missing Extended Key Usage value tcg-kp-AIKCertificate (2.23.133.8.3)")
  919. }
  920. valid = true
  921. }
  922. }
  923. if !valid {
  924. return errors.New("AK certificate is missing Extended Key Usage extension")
  925. }
  926. return nil
  927. }
  928. // Apple Enterprise Attestation Root CA from
  929. // https://www.apple.com/certificateauthority/private/
  930. const appleEnterpriseAttestationRootCA = `-----BEGIN CERTIFICATE-----
  931. MIICJDCCAamgAwIBAgIUQsDCuyxyfFxeq/bxpm8frF15hzcwCgYIKoZIzj0EAwMw
  932. UTEtMCsGA1UEAwwkQXBwbGUgRW50ZXJwcmlzZSBBdHRlc3RhdGlvbiBSb290IENB
  933. MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzAeFw0yMjAyMTYxOTAx
  934. MjRaFw00NzAyMjAwMDAwMDBaMFExLTArBgNVBAMMJEFwcGxlIEVudGVycHJpc2Ug
  935. QXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UE
  936. BhMCVVMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT6Jigq+Ps9Q4CoT8t8q+UnOe2p
  937. oT9nRaUfGhBTbgvqSGXPjVkbYlIWYO+1zPk2Sz9hQ5ozzmLrPmTBgEWRcHjA2/y7
  938. 7GEicps9wn2tj+G89l3INNDKETdxSPPIZpPj8VmjQjBAMA8GA1UdEwEB/wQFMAMB
  939. Af8wHQYDVR0OBBYEFPNqTQGd8muBpV5du+UIbVbi+d66MA4GA1UdDwEB/wQEAwIB
  940. BjAKBggqhkjOPQQDAwNpADBmAjEA1xpWmTLSpr1VH4f8Ypk8f3jMUKYz4QPG8mL5
  941. 8m9sX/b2+eXpTv2pH4RZgJjucnbcAjEA4ZSB6S45FlPuS/u4pTnzoz632rA+xW/T
  942. ZwFEh9bhKjJ+5VQ9/Do1os0u3LEkgN/r
  943. -----END CERTIFICATE-----`
  944. var (
  945. oidAppleSerialNumber = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 1}
  946. oidAppleUniqueDeviceIdentifier = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 9, 2}
  947. oidAppleSecureEnclaveProcessorOSVersion = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 10, 2}
  948. oidAppleNonce = asn1.ObjectIdentifier{1, 2, 840, 113635, 100, 8, 11, 1}
  949. )
  950. type appleAttestationData struct {
  951. Nonce []byte
  952. SerialNumber string
  953. UDID string
  954. SEPVersion string
  955. Certificate *x509.Certificate
  956. Fingerprint string
  957. }
  958. func doAppleAttestationFormat(_ context.Context, prov Provisioner, _ *Challenge, att *attestationObject) (*appleAttestationData, error) {
  959. // Use configured or default attestation roots if none is configured.
  960. roots, ok := prov.GetAttestationRoots()
  961. if !ok {
  962. root, err := pemutil.ParseCertificate([]byte(appleEnterpriseAttestationRootCA))
  963. if err != nil {
  964. return nil, WrapErrorISE(err, "error parsing apple enterprise ca")
  965. }
  966. roots = x509.NewCertPool()
  967. roots.AddCert(root)
  968. }
  969. x5c, ok := att.AttStatement["x5c"].([]interface{})
  970. if !ok {
  971. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  972. }
  973. if len(x5c) == 0 {
  974. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is empty")
  975. }
  976. der, ok := x5c[0].([]byte)
  977. if !ok {
  978. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  979. }
  980. leaf, err := x509.ParseCertificate(der)
  981. if err != nil {
  982. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  983. }
  984. intermediates := x509.NewCertPool()
  985. for _, v := range x5c[1:] {
  986. der, ok = v.([]byte)
  987. if !ok {
  988. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  989. }
  990. cert, err := x509.ParseCertificate(der)
  991. if err != nil {
  992. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  993. }
  994. intermediates.AddCert(cert)
  995. }
  996. if _, err := leaf.Verify(x509.VerifyOptions{
  997. Intermediates: intermediates,
  998. Roots: roots,
  999. CurrentTime: time.Now().Truncate(time.Second),
  1000. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1001. }); err != nil {
  1002. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1003. }
  1004. data := &appleAttestationData{
  1005. Certificate: leaf,
  1006. }
  1007. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1008. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1009. }
  1010. for _, ext := range leaf.Extensions {
  1011. switch {
  1012. case ext.Id.Equal(oidAppleSerialNumber):
  1013. data.SerialNumber = string(ext.Value)
  1014. case ext.Id.Equal(oidAppleUniqueDeviceIdentifier):
  1015. data.UDID = string(ext.Value)
  1016. case ext.Id.Equal(oidAppleSecureEnclaveProcessorOSVersion):
  1017. data.SEPVersion = string(ext.Value)
  1018. case ext.Id.Equal(oidAppleNonce):
  1019. data.Nonce = ext.Value
  1020. }
  1021. }
  1022. return data, nil
  1023. }
  1024. // Yubico PIV Root CA Serial 263751
  1025. // https://developers.yubico.com/PIV/Introduction/piv-attestation-ca.pem
  1026. const yubicoPIVRootCA = `-----BEGIN CERTIFICATE-----
  1027. MIIDFzCCAf+gAwIBAgIDBAZHMA0GCSqGSIb3DQEBCwUAMCsxKTAnBgNVBAMMIFl1
  1028. YmljbyBQSVYgUm9vdCBDQSBTZXJpYWwgMjYzNzUxMCAXDTE2MDMxNDAwMDAwMFoY
  1029. DzIwNTIwNDE3MDAwMDAwWjArMSkwJwYDVQQDDCBZdWJpY28gUElWIFJvb3QgQ0Eg
  1030. U2VyaWFsIDI2Mzc1MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMN2
  1031. cMTNR6YCdcTFRxuPy31PabRn5m6pJ+nSE0HRWpoaM8fc8wHC+Tmb98jmNvhWNE2E
  1032. ilU85uYKfEFP9d6Q2GmytqBnxZsAa3KqZiCCx2LwQ4iYEOb1llgotVr/whEpdVOq
  1033. joU0P5e1j1y7OfwOvky/+AXIN/9Xp0VFlYRk2tQ9GcdYKDmqU+db9iKwpAzid4oH
  1034. BVLIhmD3pvkWaRA2H3DA9t7H/HNq5v3OiO1jyLZeKqZoMbPObrxqDg+9fOdShzgf
  1035. wCqgT3XVmTeiwvBSTctyi9mHQfYd2DwkaqxRnLbNVyK9zl+DzjSGp9IhVPiVtGet
  1036. X02dxhQnGS7K6BO0Qe8CAwEAAaNCMEAwHQYDVR0OBBYEFMpfyvLEojGc6SJf8ez0
  1037. 1d8Cv4O/MA8GA1UdEwQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
  1038. DQEBCwUAA4IBAQBc7Ih8Bc1fkC+FyN1fhjWioBCMr3vjneh7MLbA6kSoyWF70N3s
  1039. XhbXvT4eRh0hvxqvMZNjPU/VlRn6gLVtoEikDLrYFXN6Hh6Wmyy1GTnspnOvMvz2
  1040. lLKuym9KYdYLDgnj3BeAvzIhVzzYSeU77/Cupofj093OuAswW0jYvXsGTyix6B3d
  1041. bW5yWvyS9zNXaqGaUmP3U9/b6DlHdDogMLu3VLpBB9bm5bjaKWWJYgWltCVgUbFq
  1042. Fqyi4+JE014cSgR57Jcu3dZiehB6UtAPgad9L5cNvua/IWRmm+ANy3O2LH++Pyl8
  1043. SREzU8onbBsjMg9QDiSf5oJLKvd/Ren+zGY7
  1044. -----END CERTIFICATE-----`
  1045. // Serial number of the YubiKey, encoded as an integer.
  1046. // https://developers.yubico.com/PIV/Introduction/PIV_attestation.html
  1047. var oidYubicoSerialNumber = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 7}
  1048. type stepAttestationData struct {
  1049. Certificate *x509.Certificate
  1050. SerialNumber string
  1051. Fingerprint string
  1052. }
  1053. func doStepAttestationFormat(_ context.Context, prov Provisioner, ch *Challenge, jwk *jose.JSONWebKey, att *attestationObject) (*stepAttestationData, error) {
  1054. // Use configured or default attestation roots if none is configured.
  1055. roots, ok := prov.GetAttestationRoots()
  1056. if !ok {
  1057. root, err := pemutil.ParseCertificate([]byte(yubicoPIVRootCA))
  1058. if err != nil {
  1059. return nil, WrapErrorISE(err, "error parsing root ca")
  1060. }
  1061. roots = x509.NewCertPool()
  1062. roots.AddCert(root)
  1063. }
  1064. // Extract x5c and verify certificate
  1065. x5c, ok := att.AttStatement["x5c"].([]interface{})
  1066. if !ok {
  1067. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c not present")
  1068. }
  1069. if len(x5c) == 0 {
  1070. return nil, NewDetailedError(ErrorRejectedIdentifierType, "x5c is empty")
  1071. }
  1072. der, ok := x5c[0].([]byte)
  1073. if !ok {
  1074. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1075. }
  1076. leaf, err := x509.ParseCertificate(der)
  1077. if err != nil {
  1078. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1079. }
  1080. intermediates := x509.NewCertPool()
  1081. for _, v := range x5c[1:] {
  1082. der, ok = v.([]byte)
  1083. if !ok {
  1084. return nil, NewDetailedError(ErrorBadAttestationStatementType, "x5c is malformed")
  1085. }
  1086. cert, err := x509.ParseCertificate(der)
  1087. if err != nil {
  1088. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is malformed")
  1089. }
  1090. intermediates.AddCert(cert)
  1091. }
  1092. if _, err := leaf.Verify(x509.VerifyOptions{
  1093. Intermediates: intermediates,
  1094. Roots: roots,
  1095. CurrentTime: time.Now().Truncate(time.Second),
  1096. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  1097. }); err != nil {
  1098. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "x5c is not valid")
  1099. }
  1100. // Verify proof of possession of private key validating the key
  1101. // authorization. Per recommendation at
  1102. // https://w3c.github.io/webauthn/#sctn-signature-attestation-types the
  1103. // signature is CBOR-encoded.
  1104. var sig []byte
  1105. csig, ok := att.AttStatement["sig"].([]byte)
  1106. if !ok {
  1107. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig not present")
  1108. }
  1109. if err := cbor.Unmarshal(csig, &sig); err != nil {
  1110. return nil, NewDetailedError(ErrorBadAttestationStatementType, "sig is malformed")
  1111. }
  1112. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. switch pub := leaf.PublicKey.(type) {
  1117. case *ecdsa.PublicKey:
  1118. if pub.Curve != elliptic.P256() {
  1119. return nil, WrapDetailedError(ErrorBadAttestationStatementType, err, "unsupported elliptic curve %s", pub.Curve)
  1120. }
  1121. sum := sha256.Sum256([]byte(keyAuth))
  1122. if !ecdsa.VerifyASN1(pub, sum[:], sig) {
  1123. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1124. }
  1125. case *rsa.PublicKey:
  1126. sum := sha256.Sum256([]byte(keyAuth))
  1127. if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil {
  1128. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1129. }
  1130. case ed25519.PublicKey:
  1131. if !ed25519.Verify(pub, []byte(keyAuth), sig) {
  1132. return nil, NewDetailedError(ErrorBadAttestationStatementType, "failed to validate signature")
  1133. }
  1134. default:
  1135. return nil, NewDetailedError(ErrorBadAttestationStatementType, "unsupported public key type %T", pub)
  1136. }
  1137. // Parse attestation data:
  1138. // TODO(mariano): add support for other extensions.
  1139. data := &stepAttestationData{
  1140. Certificate: leaf,
  1141. }
  1142. if data.Fingerprint, err = keyutil.Fingerprint(leaf.PublicKey); err != nil {
  1143. return nil, WrapErrorISE(err, "error calculating key fingerprint")
  1144. }
  1145. for _, ext := range leaf.Extensions {
  1146. if !ext.Id.Equal(oidYubicoSerialNumber) {
  1147. continue
  1148. }
  1149. var serialNumber int
  1150. rest, err := asn1.Unmarshal(ext.Value, &serialNumber)
  1151. if err != nil || len(rest) > 0 {
  1152. return nil, WrapError(ErrorBadAttestationStatementType, err, "error parsing serial number")
  1153. }
  1154. data.SerialNumber = strconv.Itoa(serialNumber)
  1155. break
  1156. }
  1157. return data, nil
  1158. }
  1159. // serverName determines the SNI HostName to set based on an acme.Challenge
  1160. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  1161. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  1162. // It also references TLS Extensions [RFC6066].
  1163. func serverName(ch *Challenge) string {
  1164. var serverName string
  1165. ip := net.ParseIP(ch.Value)
  1166. if ip != nil {
  1167. serverName = reverseAddr(ip)
  1168. } else {
  1169. serverName = ch.Value
  1170. }
  1171. return serverName
  1172. }
  1173. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  1174. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  1175. // to parse the IP address.
  1176. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  1177. func reverseAddr(ip net.IP) (arpa string) {
  1178. if ip.To4() != nil {
  1179. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  1180. }
  1181. // Must be IPv6
  1182. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  1183. // Add it, in reverse, to the buffer
  1184. for i := len(ip) - 1; i >= 0; i-- {
  1185. v := ip[i]
  1186. buf = append(buf, hexit[v&0xF],
  1187. '.',
  1188. hexit[v>>4],
  1189. '.')
  1190. }
  1191. // Append "ip6.arpa." and return (buf already has the final .)
  1192. buf = append(buf, "ip6.arpa."...)
  1193. return string(buf)
  1194. }
  1195. // Convert unsigned integer to decimal string.
  1196. // Implementation taken from https://golang.org/src/net/parse.go
  1197. func uitoa(val uint) string {
  1198. if val == 0 { // avoid string allocation
  1199. return "0"
  1200. }
  1201. var buf [20]byte // big enough for 64bit value base 10
  1202. i := len(buf) - 1
  1203. for val >= 10 {
  1204. v := val / 10
  1205. buf[i] = byte('0' + val - v*10)
  1206. i--
  1207. val = v
  1208. }
  1209. // val < 10
  1210. buf[i] = byte('0' + val)
  1211. return string(buf[i:])
  1212. }
  1213. const hexit = "0123456789abcdef"
  1214. // KeyAuthorization creates the ACME key authorization value from a token
  1215. // and a jwk.
  1216. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  1217. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  1218. if err != nil {
  1219. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  1220. }
  1221. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  1222. return fmt.Sprintf("%s.%s", token, encPrint), nil
  1223. }
  1224. // storeError the given error to an ACME error and saves using the DB interface.
  1225. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  1226. ch.Error = err
  1227. if markInvalid {
  1228. ch.Status = StatusInvalid
  1229. }
  1230. if err := db.UpdateChallenge(ctx, ch); err != nil {
  1231. return WrapErrorISE(err, "failure saving error to acme challenge")
  1232. }
  1233. return nil
  1234. }