challenge.go 54 KB

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