challenge.go 12 KB

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