challenge.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package acme
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "crypto/tls"
  8. "encoding/asn1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "net/url"
  17. "reflect"
  18. "strings"
  19. "time"
  20. "go.step.sm/crypto/jose"
  21. )
  22. type ChallengeType string
  23. const (
  24. // HTTP01 is the http-01 ACME challenge type
  25. HTTP01 ChallengeType = "http-01"
  26. // DNS01 is the dns-01 ACME challenge type
  27. DNS01 ChallengeType = "dns-01"
  28. // TLSALPN01 is the tls-alpn-01 ACME challenge type
  29. TLSALPN01 ChallengeType = "tls-alpn-01"
  30. )
  31. // Challenge represents an ACME response Challenge type.
  32. type Challenge struct {
  33. ID string `json:"-"`
  34. AccountID string `json:"-"`
  35. AuthorizationID string `json:"-"`
  36. Value string `json:"-"`
  37. Type ChallengeType `json:"type"`
  38. Status Status `json:"status"`
  39. Token string `json:"token"`
  40. ValidatedAt string `json:"validated,omitempty"`
  41. URL string `json:"url"`
  42. Error *Error `json:"error,omitempty"`
  43. }
  44. // ToLog enables response logging.
  45. func (ch *Challenge) ToLog() (interface{}, error) {
  46. b, err := json.Marshal(ch)
  47. if err != nil {
  48. return nil, WrapErrorISE(err, "error marshaling challenge for logging")
  49. }
  50. return string(b), nil
  51. }
  52. // Validate attempts to validate the challenge. Stores changes to the Challenge
  53. // type using the DB interface.
  54. // satisfactorily validated, the 'status' and 'validated' attributes are
  55. // updated.
  56. func (ch *Challenge) Validate(ctx context.Context, db DB, jwk *jose.JSONWebKey) error {
  57. // If already valid or invalid then return without performing validation.
  58. if ch.Status != StatusPending {
  59. return nil
  60. }
  61. switch ch.Type {
  62. case HTTP01:
  63. return http01Validate(ctx, ch, db, jwk)
  64. case DNS01:
  65. return dns01Validate(ctx, ch, db, jwk)
  66. case TLSALPN01:
  67. return tlsalpn01Validate(ctx, ch, db, jwk)
  68. default:
  69. return NewErrorISE("unexpected challenge type '%s'", ch.Type)
  70. }
  71. }
  72. func http01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  73. u := &url.URL{Scheme: "http", Host: http01ChallengeHost(ch.Value), Path: fmt.Sprintf("/.well-known/acme-challenge/%s", ch.Token)}
  74. vc := MustClientFromContext(ctx)
  75. resp, err := vc.Get(u.String())
  76. if err != nil {
  77. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  78. "error doing http GET for url %s", u))
  79. }
  80. defer resp.Body.Close()
  81. if resp.StatusCode >= 400 {
  82. return storeError(ctx, db, ch, false, NewError(ErrorConnectionType,
  83. "error doing http GET for url %s with status code %d", u, resp.StatusCode))
  84. }
  85. body, err := io.ReadAll(resp.Body)
  86. if err != nil {
  87. return WrapErrorISE(err, "error reading "+
  88. "response body for url %s", u)
  89. }
  90. keyAuth := strings.TrimSpace(string(body))
  91. expected, err := KeyAuthorization(ch.Token, jwk)
  92. if err != nil {
  93. return err
  94. }
  95. if keyAuth != expected {
  96. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  97. "keyAuthorization does not match; expected %s, but got %s", expected, keyAuth))
  98. }
  99. // Update and store the challenge.
  100. ch.Status = StatusValid
  101. ch.Error = nil
  102. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  103. if err = db.UpdateChallenge(ctx, ch); err != nil {
  104. return WrapErrorISE(err, "error updating challenge")
  105. }
  106. return nil
  107. }
  108. // http01ChallengeHost checks if a Challenge value is an IPv6 address
  109. // and adds square brackets if that's the case, so that it can be used
  110. // as a hostname. Returns the original Challenge value as the host to
  111. // use in other cases.
  112. func http01ChallengeHost(value string) string {
  113. if ip := net.ParseIP(value); ip != nil && ip.To4() == nil {
  114. value = "[" + value + "]"
  115. }
  116. return value
  117. }
  118. func tlsAlert(err error) uint8 {
  119. var opErr *net.OpError
  120. if errors.As(err, &opErr) {
  121. v := reflect.ValueOf(opErr.Err)
  122. if v.Kind() == reflect.Uint8 {
  123. return uint8(v.Uint())
  124. }
  125. }
  126. return 0
  127. }
  128. func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  129. config := &tls.Config{
  130. NextProtos: []string{"acme-tls/1"},
  131. // https://tools.ietf.org/html/rfc8737#section-4
  132. // ACME servers that implement "acme-tls/1" MUST only negotiate TLS 1.2
  133. // [RFC5246] or higher when connecting to clients for validation.
  134. MinVersion: tls.VersionTLS12,
  135. ServerName: serverName(ch),
  136. InsecureSkipVerify: true, // we expect a self-signed challenge certificate
  137. }
  138. hostPort := net.JoinHostPort(ch.Value, "443")
  139. vc := MustClientFromContext(ctx)
  140. conn, err := vc.TLSDial("tcp", hostPort, config)
  141. if err != nil {
  142. // With Go 1.17+ tls.Dial fails if there's no overlap between configured
  143. // client and server protocols. When this happens the connection is
  144. // closed with the error no_application_protocol(120) as required by
  145. // RFC7301. See https://golang.org/doc/go1.17#ALPN
  146. if tlsAlert(err) == 120 {
  147. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  148. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  149. }
  150. return storeError(ctx, db, ch, false, WrapError(ErrorConnectionType, err,
  151. "error doing TLS dial for %s", hostPort))
  152. }
  153. defer conn.Close()
  154. cs := conn.ConnectionState()
  155. certs := cs.PeerCertificates
  156. if len(certs) == 0 {
  157. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  158. "%s challenge for %s resulted in no certificates", ch.Type, ch.Value))
  159. }
  160. if cs.NegotiatedProtocol != "acme-tls/1" {
  161. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  162. "cannot negotiate ALPN acme-tls/1 protocol for tls-alpn-01 challenge"))
  163. }
  164. leafCert := certs[0]
  165. // if no DNS names present, look for IP address and verify that exactly one exists
  166. if len(leafCert.DNSNames) == 0 {
  167. if len(leafCert.IPAddresses) != 1 || !leafCert.IPAddresses[0].Equal(net.ParseIP(ch.Value)) {
  168. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  169. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  170. }
  171. } else {
  172. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], ch.Value) {
  173. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  174. "incorrect certificate for tls-alpn-01 challenge: leaf certificate must contain a single IP address or DNS name, %v", ch.Value))
  175. }
  176. }
  177. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  178. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  179. foundIDPeAcmeIdentifierV1Obsolete := false
  180. keyAuth, err := KeyAuthorization(ch.Token, jwk)
  181. if err != nil {
  182. return err
  183. }
  184. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  185. for _, ext := range leafCert.Extensions {
  186. if idPeAcmeIdentifier.Equal(ext.Id) {
  187. if !ext.Critical {
  188. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  189. "incorrect certificate for tls-alpn-01 challenge: acmeValidationV1 extension not critical"))
  190. }
  191. var extValue []byte
  192. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  193. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  194. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  195. "incorrect certificate for tls-alpn-01 challenge: malformed acmeValidationV1 extension value"))
  196. }
  197. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  198. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  199. "incorrect certificate for tls-alpn-01 challenge: "+
  200. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  201. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))
  202. }
  203. ch.Status = StatusValid
  204. ch.Error = nil
  205. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  206. if err = db.UpdateChallenge(ctx, ch); err != nil {
  207. return WrapErrorISE(err, "tlsalpn01ValidateChallenge - error updating challenge")
  208. }
  209. return nil
  210. }
  211. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  212. foundIDPeAcmeIdentifierV1Obsolete = true
  213. }
  214. }
  215. if foundIDPeAcmeIdentifierV1Obsolete {
  216. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  217. "incorrect certificate for tls-alpn-01 challenge: obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))
  218. }
  219. return storeError(ctx, db, ch, true, NewError(ErrorRejectedIdentifierType,
  220. "incorrect certificate for tls-alpn-01 challenge: missing acmeValidationV1 extension"))
  221. }
  222. func dns01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSONWebKey) error {
  223. // Normalize domain for wildcard DNS names
  224. // This is done to avoid making TXT lookups for domains like
  225. // _acme-challenge.*.example.com
  226. // Instead perform txt lookup for _acme-challenge.example.com
  227. domain := strings.TrimPrefix(ch.Value, "*.")
  228. vc := MustClientFromContext(ctx)
  229. txtRecords, err := vc.LookupTxt("_acme-challenge." + domain)
  230. if err != nil {
  231. return storeError(ctx, db, ch, false, WrapError(ErrorDNSType, err,
  232. "error looking up TXT records for domain %s", domain))
  233. }
  234. expectedKeyAuth, err := KeyAuthorization(ch.Token, jwk)
  235. if err != nil {
  236. return err
  237. }
  238. h := sha256.Sum256([]byte(expectedKeyAuth))
  239. expected := base64.RawURLEncoding.EncodeToString(h[:])
  240. var found bool
  241. for _, r := range txtRecords {
  242. if r == expected {
  243. found = true
  244. break
  245. }
  246. }
  247. if !found {
  248. return storeError(ctx, db, ch, false, NewError(ErrorRejectedIdentifierType,
  249. "keyAuthorization does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))
  250. }
  251. // Update and store the challenge.
  252. ch.Status = StatusValid
  253. ch.Error = nil
  254. ch.ValidatedAt = clock.Now().Format(time.RFC3339)
  255. if err = db.UpdateChallenge(ctx, ch); err != nil {
  256. return WrapErrorISE(err, "error updating challenge")
  257. }
  258. return nil
  259. }
  260. // serverName determines the SNI HostName to set based on an acme.Challenge
  261. // for TLS-ALPN-01 challenges RFC8738 states that, if HostName is an IP, it
  262. // should be the ARPA address https://datatracker.ietf.org/doc/html/rfc8738#section-6.
  263. // It also references TLS Extensions [RFC6066].
  264. func serverName(ch *Challenge) string {
  265. var serverName string
  266. ip := net.ParseIP(ch.Value)
  267. if ip != nil {
  268. serverName = reverseAddr(ip)
  269. } else {
  270. serverName = ch.Value
  271. }
  272. return serverName
  273. }
  274. // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
  275. // address addr suitable for rDNS (PTR) record lookup or an error if it fails
  276. // to parse the IP address.
  277. // Implementation taken and adapted from https://golang.org/src/net/dnsclient.go?s=780:834#L20
  278. func reverseAddr(ip net.IP) (arpa string) {
  279. if ip.To4() != nil {
  280. return uitoa(uint(ip[15])) + "." + uitoa(uint(ip[14])) + "." + uitoa(uint(ip[13])) + "." + uitoa(uint(ip[12])) + ".in-addr.arpa."
  281. }
  282. // Must be IPv6
  283. buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
  284. // Add it, in reverse, to the buffer
  285. for i := len(ip) - 1; i >= 0; i-- {
  286. v := ip[i]
  287. buf = append(buf, hexit[v&0xF],
  288. '.',
  289. hexit[v>>4],
  290. '.')
  291. }
  292. // Append "ip6.arpa." and return (buf already has the final .)
  293. buf = append(buf, "ip6.arpa."...)
  294. return string(buf)
  295. }
  296. // Convert unsigned integer to decimal string.
  297. // Implementation taken from https://golang.org/src/net/parse.go
  298. func uitoa(val uint) string {
  299. if val == 0 { // avoid string allocation
  300. return "0"
  301. }
  302. var buf [20]byte // big enough for 64bit value base 10
  303. i := len(buf) - 1
  304. for val >= 10 {
  305. q := val / 10
  306. buf[i] = byte('0' + val - q*10)
  307. i--
  308. val = q
  309. }
  310. // val < 10
  311. buf[i] = byte('0' + val)
  312. return string(buf[i:])
  313. }
  314. const hexit = "0123456789abcdef"
  315. // KeyAuthorization creates the ACME key authorization value from a token
  316. // and a jwk.
  317. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  318. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  319. if err != nil {
  320. return "", WrapErrorISE(err, "error generating JWK thumbprint")
  321. }
  322. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  323. return fmt.Sprintf("%s.%s", token, encPrint), nil
  324. }
  325. // storeError the given error to an ACME error and saves using the DB interface.
  326. func storeError(ctx context.Context, db DB, ch *Challenge, markInvalid bool, err *Error) error {
  327. ch.Error = err
  328. if markInvalid {
  329. ch.Status = StatusInvalid
  330. }
  331. if err := db.UpdateChallenge(ctx, ch); err != nil {
  332. return WrapErrorISE(err, "failure saving error to acme challenge")
  333. }
  334. return nil
  335. }