challenge.go 69 KB

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