challenge.go 11 KB

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