challenge.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. "strings"
  17. "time"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/nosql"
  20. "go.step.sm/crypto/jose"
  21. )
  22. // Challenge is a subset of the challenge type containing only those attributes
  23. // required for responses in the ACME protocol.
  24. type Challenge struct {
  25. Type string `json:"type"`
  26. Status string `json:"status"`
  27. Token string `json:"token"`
  28. Validated string `json:"validated,omitempty"`
  29. URL string `json:"url"`
  30. Error *AError `json:"error,omitempty"`
  31. ID string `json:"-"`
  32. AuthzID string `json:"-"`
  33. }
  34. // ToLog enables response logging.
  35. func (c *Challenge) ToLog() (interface{}, error) {
  36. b, err := json.Marshal(c)
  37. if err != nil {
  38. return nil, ServerInternalErr(errors.Wrap(err, "error marshaling challenge for logging"))
  39. }
  40. return string(b), nil
  41. }
  42. // GetID returns the Challenge ID.
  43. func (c *Challenge) GetID() string {
  44. return c.ID
  45. }
  46. // GetAuthzID returns the parent Authz ID that owns the Challenge.
  47. func (c *Challenge) GetAuthzID() string {
  48. return c.AuthzID
  49. }
  50. type httpGetter func(string) (*http.Response, error)
  51. type lookupTxt func(string) ([]string, error)
  52. type tlsDialer func(network, addr string, config *tls.Config) (*tls.Conn, error)
  53. type validateOptions struct {
  54. httpGet httpGetter
  55. lookupTxt lookupTxt
  56. tlsDial tlsDialer
  57. }
  58. // challenge is the interface ACME challenege types must implement.
  59. type challenge interface {
  60. save(db nosql.DB, swap challenge) error
  61. validate(nosql.DB, *jose.JSONWebKey, validateOptions) (challenge, error)
  62. getType() string
  63. getError() *AError
  64. getValue() string
  65. getStatus() string
  66. getID() string
  67. getAuthzID() string
  68. getToken() string
  69. clone() *baseChallenge
  70. getAccountID() string
  71. getValidated() time.Time
  72. getCreated() time.Time
  73. toACME(context.Context, nosql.DB, *directory) (*Challenge, error)
  74. }
  75. // ChallengeOptions is the type used to created a new Challenge.
  76. type ChallengeOptions struct {
  77. AccountID string
  78. AuthzID string
  79. Identifier Identifier
  80. }
  81. // baseChallenge is the base Challenge type that others build from.
  82. type baseChallenge struct {
  83. ID string `json:"id"`
  84. AccountID string `json:"accountID"`
  85. AuthzID string `json:"authzID"`
  86. Type string `json:"type"`
  87. Status string `json:"status"`
  88. Token string `json:"token"`
  89. Value string `json:"value"`
  90. Validated time.Time `json:"validated"`
  91. Created time.Time `json:"created"`
  92. Error *AError `json:"error"`
  93. }
  94. func newBaseChallenge(accountID, authzID string) (*baseChallenge, error) {
  95. id, err := randID()
  96. if err != nil {
  97. return nil, Wrap(err, "error generating random id for ACME challenge")
  98. }
  99. token, err := randID()
  100. if err != nil {
  101. return nil, Wrap(err, "error generating token for ACME challenge")
  102. }
  103. return &baseChallenge{
  104. ID: id,
  105. AccountID: accountID,
  106. AuthzID: authzID,
  107. Status: StatusPending,
  108. Token: token,
  109. Created: clock.Now(),
  110. }, nil
  111. }
  112. // getID returns the id of the baseChallenge.
  113. func (bc *baseChallenge) getID() string {
  114. return bc.ID
  115. }
  116. // getAuthzID returns the authz ID of the baseChallenge.
  117. func (bc *baseChallenge) getAuthzID() string {
  118. return bc.AuthzID
  119. }
  120. // getAccountID returns the account id of the baseChallenge.
  121. func (bc *baseChallenge) getAccountID() string {
  122. return bc.AccountID
  123. }
  124. // getType returns the type of the baseChallenge.
  125. func (bc *baseChallenge) getType() string {
  126. return bc.Type
  127. }
  128. // getValue returns the type of the baseChallenge.
  129. func (bc *baseChallenge) getValue() string {
  130. return bc.Value
  131. }
  132. // getStatus returns the status of the baseChallenge.
  133. func (bc *baseChallenge) getStatus() string {
  134. return bc.Status
  135. }
  136. // getToken returns the token of the baseChallenge.
  137. func (bc *baseChallenge) getToken() string {
  138. return bc.Token
  139. }
  140. // getValidated returns the validated time of the baseChallenge.
  141. func (bc *baseChallenge) getValidated() time.Time {
  142. return bc.Validated
  143. }
  144. // getCreated returns the created time of the baseChallenge.
  145. func (bc *baseChallenge) getCreated() time.Time {
  146. return bc.Created
  147. }
  148. // getCreated returns the created time of the baseChallenge.
  149. func (bc *baseChallenge) getError() *AError {
  150. return bc.Error
  151. }
  152. // toACME converts the internal Challenge type into the public acmeChallenge
  153. // type for presentation in the ACME protocol.
  154. func (bc *baseChallenge) toACME(ctx context.Context, db nosql.DB, dir *directory) (*Challenge, error) {
  155. ac := &Challenge{
  156. Type: bc.getType(),
  157. Status: bc.getStatus(),
  158. Token: bc.getToken(),
  159. URL: dir.getLink(ctx, ChallengeLink, true, bc.getID()),
  160. ID: bc.getID(),
  161. AuthzID: bc.getAuthzID(),
  162. }
  163. if !bc.Validated.IsZero() {
  164. ac.Validated = bc.Validated.Format(time.RFC3339)
  165. }
  166. if bc.Error != nil {
  167. ac.Error = bc.Error
  168. }
  169. return ac, nil
  170. }
  171. // save writes the challenge to disk. For new challenges 'old' should be nil,
  172. // otherwise 'old' should be a pointer to the acme challenge as it was at the
  173. // start of the request. This method will fail if the value currently found
  174. // in the bucket/row does not match the value of 'old'.
  175. func (bc *baseChallenge) save(db nosql.DB, old challenge) error {
  176. newB, err := json.Marshal(bc)
  177. if err != nil {
  178. return ServerInternalErr(errors.Wrap(err,
  179. "error marshaling new acme challenge"))
  180. }
  181. var oldB []byte
  182. if old == nil {
  183. oldB = nil
  184. } else {
  185. oldB, err = json.Marshal(old)
  186. if err != nil {
  187. return ServerInternalErr(errors.Wrap(err,
  188. "error marshaling old acme challenge"))
  189. }
  190. }
  191. _, swapped, err := db.CmpAndSwap(challengeTable, []byte(bc.ID), oldB, newB)
  192. switch {
  193. case err != nil:
  194. return ServerInternalErr(errors.Wrap(err, "error saving acme challenge"))
  195. case !swapped:
  196. return ServerInternalErr(errors.New("error saving acme challenge; " +
  197. "acme challenge has changed since last read"))
  198. default:
  199. return nil
  200. }
  201. }
  202. func (bc *baseChallenge) clone() *baseChallenge {
  203. u := *bc
  204. return &u
  205. }
  206. func (bc *baseChallenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  207. return nil, ServerInternalErr(errors.New("unimplemented"))
  208. }
  209. func (bc *baseChallenge) storeError(db nosql.DB, err *Error) error {
  210. clone := bc.clone()
  211. clone.Error = err.ToACME()
  212. return clone.save(db, bc)
  213. }
  214. // unmarshalChallenge unmarshals a challenge type into the correct sub-type.
  215. func unmarshalChallenge(data []byte) (challenge, error) {
  216. var getType struct {
  217. Type string `json:"type"`
  218. }
  219. if err := json.Unmarshal(data, &getType); err != nil {
  220. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
  221. }
  222. switch getType.Type {
  223. case "dns-01":
  224. var bc baseChallenge
  225. if err := json.Unmarshal(data, &bc); err != nil {
  226. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  227. "challenge type into dns01Challenge"))
  228. }
  229. return &dns01Challenge{&bc}, nil
  230. case "http-01":
  231. var bc baseChallenge
  232. if err := json.Unmarshal(data, &bc); err != nil {
  233. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  234. "challenge type into http01Challenge"))
  235. }
  236. return &http01Challenge{&bc}, nil
  237. case "tls-alpn-01":
  238. var bc baseChallenge
  239. if err := json.Unmarshal(data, &bc); err != nil {
  240. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  241. "challenge type into tlsALPN01Challenge"))
  242. }
  243. return &tlsALPN01Challenge{&bc}, nil
  244. default:
  245. return nil, ServerInternalErr(errors.Errorf("unexpected challenge type %s", getType.Type))
  246. }
  247. }
  248. // http01Challenge represents an http-01 acme challenge.
  249. type http01Challenge struct {
  250. *baseChallenge
  251. }
  252. // newHTTP01Challenge returns a new acme http-01 challenge.
  253. func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  254. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  255. if err != nil {
  256. return nil, err
  257. }
  258. bc.Type = "http-01"
  259. bc.Value = ops.Identifier.Value
  260. hc := &http01Challenge{bc}
  261. if err := hc.save(db, nil); err != nil {
  262. return nil, err
  263. }
  264. return hc, nil
  265. }
  266. // Validate attempts to validate the challenge. If the challenge has been
  267. // satisfactorily validated, the 'status' and 'validated' attributes are
  268. // updated.
  269. func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  270. // If already valid or invalid then return without performing validation.
  271. if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
  272. return hc, nil
  273. }
  274. url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
  275. resp, err := vo.httpGet(url)
  276. if err != nil {
  277. if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
  278. "error doing http GET for url %s", url))); err != nil {
  279. return nil, err
  280. }
  281. return hc, nil
  282. }
  283. if resp.StatusCode >= 400 {
  284. if err = hc.storeError(db,
  285. ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
  286. url, resp.StatusCode))); err != nil {
  287. return nil, err
  288. }
  289. return hc, nil
  290. }
  291. defer resp.Body.Close()
  292. body, err := ioutil.ReadAll(resp.Body)
  293. if err != nil {
  294. return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
  295. "response body for url %s", url))
  296. }
  297. keyAuth := strings.Trim(string(body), "\r\n")
  298. expected, err := KeyAuthorization(hc.Token, jwk)
  299. if err != nil {
  300. return nil, err
  301. }
  302. if keyAuth != expected {
  303. if err = hc.storeError(db,
  304. RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
  305. "expected %s, but got %s", expected, keyAuth))); err != nil {
  306. return nil, err
  307. }
  308. return hc, nil
  309. }
  310. // Update and store the challenge.
  311. upd := &http01Challenge{hc.baseChallenge.clone()}
  312. upd.Status = StatusValid
  313. upd.Error = nil
  314. upd.Validated = clock.Now()
  315. if err := upd.save(db, hc); err != nil {
  316. return nil, err
  317. }
  318. return upd, nil
  319. }
  320. type tlsALPN01Challenge struct {
  321. *baseChallenge
  322. }
  323. // newTLSALPN01Challenge returns a new acme tls-alpn-01 challenge.
  324. func newTLSALPN01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  325. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  326. if err != nil {
  327. return nil, err
  328. }
  329. bc.Type = "tls-alpn-01"
  330. bc.Value = ops.Identifier.Value
  331. hc := &tlsALPN01Challenge{bc}
  332. if err := hc.save(db, nil); err != nil {
  333. return nil, err
  334. }
  335. return hc, nil
  336. }
  337. func (tc *tlsALPN01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  338. // If already valid or invalid then return without performing validation.
  339. if tc.getStatus() == StatusValid || tc.getStatus() == StatusInvalid {
  340. return tc, nil
  341. }
  342. config := &tls.Config{
  343. NextProtos: []string{"acme-tls/1"},
  344. ServerName: tc.Value,
  345. InsecureSkipVerify: true, // we expect a self-signed challenge certificate
  346. }
  347. hostPort := net.JoinHostPort(tc.Value, "443")
  348. conn, err := vo.tlsDial("tcp", hostPort, config)
  349. if err != nil {
  350. if err = tc.storeError(db,
  351. ConnectionErr(errors.Wrapf(err, "error doing TLS dial for %s", hostPort))); err != nil {
  352. return nil, err
  353. }
  354. return tc, nil
  355. }
  356. defer conn.Close()
  357. cs := conn.ConnectionState()
  358. certs := cs.PeerCertificates
  359. if len(certs) == 0 {
  360. if err = tc.storeError(db,
  361. RejectedIdentifierErr(errors.Errorf("%s challenge for %s resulted in no certificates",
  362. tc.Type, tc.Value))); err != nil {
  363. return nil, err
  364. }
  365. return tc, nil
  366. }
  367. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != "acme-tls/1" {
  368. if err = tc.storeError(db,
  369. RejectedIdentifierErr(errors.Errorf("cannot negotiate ALPN acme-tls/1 protocol for "+
  370. "tls-alpn-01 challenge"))); err != nil {
  371. return nil, err
  372. }
  373. return tc, nil
  374. }
  375. leafCert := certs[0]
  376. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], tc.Value) {
  377. if err = tc.storeError(db,
  378. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  379. "leaf certificate must contain a single DNS name, %v", tc.Value))); err != nil {
  380. return nil, err
  381. }
  382. return tc, nil
  383. }
  384. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  385. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  386. foundIDPeAcmeIdentifierV1Obsolete := false
  387. keyAuth, err := KeyAuthorization(tc.Token, jwk)
  388. if err != nil {
  389. return nil, err
  390. }
  391. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  392. for _, ext := range leafCert.Extensions {
  393. if idPeAcmeIdentifier.Equal(ext.Id) {
  394. if !ext.Critical {
  395. if err = tc.storeError(db,
  396. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  397. "acmeValidationV1 extension not critical"))); err != nil {
  398. return nil, err
  399. }
  400. return tc, nil
  401. }
  402. var extValue []byte
  403. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  404. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  405. if err = tc.storeError(db,
  406. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  407. "malformed acmeValidationV1 extension value"))); err != nil {
  408. return nil, err
  409. }
  410. return tc, nil
  411. }
  412. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  413. if err = tc.storeError(db,
  414. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  415. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  416. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))); err != nil {
  417. return nil, err
  418. }
  419. return tc, nil
  420. }
  421. upd := &tlsALPN01Challenge{tc.baseChallenge.clone()}
  422. upd.Status = StatusValid
  423. upd.Error = nil
  424. upd.Validated = clock.Now()
  425. if err := upd.save(db, tc); err != nil {
  426. return nil, err
  427. }
  428. return upd, nil
  429. }
  430. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  431. foundIDPeAcmeIdentifierV1Obsolete = true
  432. }
  433. }
  434. if foundIDPeAcmeIdentifierV1Obsolete {
  435. if err = tc.storeError(db,
  436. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  437. "obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))); err != nil {
  438. return nil, err
  439. }
  440. return tc, nil
  441. }
  442. if err = tc.storeError(db,
  443. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  444. "missing acmeValidationV1 extension"))); err != nil {
  445. return nil, err
  446. }
  447. return tc, nil
  448. }
  449. // dns01Challenge represents an dns-01 acme challenge.
  450. type dns01Challenge struct {
  451. *baseChallenge
  452. }
  453. // newDNS01Challenge returns a new acme dns-01 challenge.
  454. func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  455. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  456. if err != nil {
  457. return nil, err
  458. }
  459. bc.Type = "dns-01"
  460. bc.Value = ops.Identifier.Value
  461. dc := &dns01Challenge{bc}
  462. if err := dc.save(db, nil); err != nil {
  463. return nil, err
  464. }
  465. return dc, nil
  466. }
  467. // KeyAuthorization creates the ACME key authorization value from a token
  468. // and a jwk.
  469. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  470. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  471. if err != nil {
  472. return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
  473. }
  474. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  475. return fmt.Sprintf("%s.%s", token, encPrint), nil
  476. }
  477. // validate attempts to validate the challenge. If the challenge has been
  478. // satisfactorily validated, the 'status' and 'validated' attributes are
  479. // updated.
  480. func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  481. // If already valid or invalid then return without performing validation.
  482. if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
  483. return dc, nil
  484. }
  485. // Normalize domain for wildcard DNS names
  486. // This is done to avoid making TXT lookups for domains like
  487. // _acme-challenge.*.example.com
  488. // Instead perform txt lookup for _acme-challenge.example.com
  489. domain := strings.TrimPrefix(dc.Value, "*.")
  490. txtRecords, err := vo.lookupTxt("_acme-challenge." + domain)
  491. if err != nil {
  492. if err = dc.storeError(db,
  493. DNSErr(errors.Wrapf(err, "error looking up TXT "+
  494. "records for domain %s", domain))); err != nil {
  495. return nil, err
  496. }
  497. return dc, nil
  498. }
  499. expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
  500. if err != nil {
  501. return nil, err
  502. }
  503. h := sha256.Sum256([]byte(expectedKeyAuth))
  504. expected := base64.RawURLEncoding.EncodeToString(h[:])
  505. var found bool
  506. for _, r := range txtRecords {
  507. if r == expected {
  508. found = true
  509. break
  510. }
  511. }
  512. if !found {
  513. if err = dc.storeError(db,
  514. RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
  515. "does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
  516. return nil, err
  517. }
  518. return dc, nil
  519. }
  520. // Update and store the challenge.
  521. upd := &dns01Challenge{dc.baseChallenge.clone()}
  522. upd.Status = StatusValid
  523. upd.Error = nil
  524. upd.Validated = time.Now().UTC()
  525. if err := upd.save(db, dc); err != nil {
  526. return nil, err
  527. }
  528. return upd, nil
  529. }
  530. // getChallenge retrieves and unmarshals an ACME challenge type from the database.
  531. func getChallenge(db nosql.DB, id string) (challenge, error) {
  532. b, err := db.Get(challengeTable, []byte(id))
  533. if nosql.IsErrNotFound(err) {
  534. return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
  535. } else if err != nil {
  536. return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
  537. }
  538. ch, err := unmarshalChallenge(b)
  539. if err != nil {
  540. return nil, err
  541. }
  542. return ch, nil
  543. }