challenge.go 13 KB

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