challenge.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. if err := clone.save(db, bc); err != nil {
  213. return ServerInternalErr(errors.Wrap(err, "failure saving error to acme challenge"))
  214. }
  215. return nil
  216. }
  217. // unmarshalChallenge unmarshals a challenge type into the correct sub-type.
  218. func unmarshalChallenge(data []byte) (challenge, error) {
  219. var getType struct {
  220. Type string `json:"type"`
  221. }
  222. if err := json.Unmarshal(data, &getType); err != nil {
  223. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
  224. }
  225. switch getType.Type {
  226. case "dns-01":
  227. var bc baseChallenge
  228. if err := json.Unmarshal(data, &bc); err != nil {
  229. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  230. "challenge type into dns01Challenge"))
  231. }
  232. return &dns01Challenge{&bc}, nil
  233. case "http-01":
  234. var bc baseChallenge
  235. if err := json.Unmarshal(data, &bc); err != nil {
  236. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  237. "challenge type into http01Challenge"))
  238. }
  239. return &http01Challenge{&bc}, nil
  240. case "tls-alpn-01":
  241. var bc baseChallenge
  242. if err := json.Unmarshal(data, &bc); err != nil {
  243. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  244. "challenge type into tlsALPN01Challenge"))
  245. }
  246. return &tlsALPN01Challenge{&bc}, nil
  247. default:
  248. return nil, ServerInternalErr(errors.Errorf("unexpected challenge type %s", getType.Type))
  249. }
  250. }
  251. // http01Challenge represents an http-01 acme challenge.
  252. type http01Challenge struct {
  253. *baseChallenge
  254. }
  255. // newHTTP01Challenge returns a new acme http-01 challenge.
  256. func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  257. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  258. if err != nil {
  259. return nil, err
  260. }
  261. bc.Type = "http-01"
  262. bc.Value = ops.Identifier.Value
  263. hc := &http01Challenge{bc}
  264. if err := hc.save(db, nil); err != nil {
  265. return nil, err
  266. }
  267. return hc, nil
  268. }
  269. // Validate attempts to validate the challenge. If the challenge has been
  270. // satisfactorily validated, the 'status' and 'validated' attributes are
  271. // updated.
  272. func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  273. // If already valid or invalid then return without performing validation.
  274. if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
  275. return hc, nil
  276. }
  277. url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
  278. resp, err := vo.httpGet(url)
  279. if err != nil {
  280. if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
  281. "error doing http GET for url %s", url))); err != nil {
  282. return nil, err
  283. }
  284. return hc, nil
  285. }
  286. if resp.StatusCode >= 400 {
  287. if err = hc.storeError(db,
  288. ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
  289. url, resp.StatusCode))); err != nil {
  290. return nil, err
  291. }
  292. return hc, nil
  293. }
  294. defer resp.Body.Close()
  295. body, err := ioutil.ReadAll(resp.Body)
  296. if err != nil {
  297. return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
  298. "response body for url %s", url))
  299. }
  300. keyAuth := strings.Trim(string(body), "\r\n")
  301. expected, err := KeyAuthorization(hc.Token, jwk)
  302. if err != nil {
  303. return nil, err
  304. }
  305. if keyAuth != expected {
  306. if err = hc.storeError(db,
  307. RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
  308. "expected %s, but got %s", expected, keyAuth))); err != nil {
  309. return nil, err
  310. }
  311. return hc, nil
  312. }
  313. // Update and store the challenge.
  314. upd := &http01Challenge{hc.baseChallenge.clone()}
  315. upd.Status = StatusValid
  316. upd.Error = nil
  317. upd.Validated = clock.Now()
  318. if err := upd.save(db, hc); err != nil {
  319. return nil, err
  320. }
  321. return upd, nil
  322. }
  323. type tlsALPN01Challenge struct {
  324. *baseChallenge
  325. }
  326. // newTLSALPN01Challenge returns a new acme tls-alpn-01 challenge.
  327. func newTLSALPN01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  328. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  329. if err != nil {
  330. return nil, err
  331. }
  332. bc.Type = "tls-alpn-01"
  333. bc.Value = ops.Identifier.Value
  334. hc := &tlsALPN01Challenge{bc}
  335. if err := hc.save(db, nil); err != nil {
  336. return nil, err
  337. }
  338. return hc, nil
  339. }
  340. func (tc *tlsALPN01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  341. // If already valid or invalid then return without performing validation.
  342. if tc.getStatus() == StatusValid || tc.getStatus() == StatusInvalid {
  343. return tc, nil
  344. }
  345. config := &tls.Config{
  346. NextProtos: []string{"acme-tls/1"},
  347. ServerName: tc.Value,
  348. InsecureSkipVerify: true, // we expect a self-signed challenge certificate
  349. }
  350. hostPort := net.JoinHostPort(tc.Value, "443")
  351. conn, err := vo.tlsDial("tcp", hostPort, config)
  352. if err != nil {
  353. if err = tc.storeError(db,
  354. ConnectionErr(errors.Wrapf(err, "error doing TLS dial for %s", hostPort))); err != nil {
  355. return nil, err
  356. }
  357. return tc, nil
  358. }
  359. defer conn.Close()
  360. cs := conn.ConnectionState()
  361. certs := cs.PeerCertificates
  362. if len(certs) == 0 {
  363. if err = tc.storeError(db,
  364. RejectedIdentifierErr(errors.Errorf("%s challenge for %s resulted in no certificates",
  365. tc.Type, tc.Value))); err != nil {
  366. return nil, err
  367. }
  368. return tc, nil
  369. }
  370. if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != "acme-tls/1" {
  371. if err = tc.storeError(db,
  372. RejectedIdentifierErr(errors.Errorf("cannot negotiate ALPN acme-tls/1 protocol for "+
  373. "tls-alpn-01 challenge"))); err != nil {
  374. return nil, err
  375. }
  376. return tc, nil
  377. }
  378. leafCert := certs[0]
  379. if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], tc.Value) {
  380. if err = tc.storeError(db,
  381. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  382. "leaf certificate must contain a single DNS name, %v", tc.Value))); err != nil {
  383. return nil, err
  384. }
  385. return tc, nil
  386. }
  387. idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
  388. idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  389. foundIDPeAcmeIdentifierV1Obsolete := false
  390. keyAuth, err := KeyAuthorization(tc.Token, jwk)
  391. if err != nil {
  392. return nil, err
  393. }
  394. hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
  395. for _, ext := range leafCert.Extensions {
  396. if idPeAcmeIdentifier.Equal(ext.Id) {
  397. if !ext.Critical {
  398. if err = tc.storeError(db,
  399. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  400. "acmeValidationV1 extension not critical"))); err != nil {
  401. return nil, err
  402. }
  403. return tc, nil
  404. }
  405. var extValue []byte
  406. rest, err := asn1.Unmarshal(ext.Value, &extValue)
  407. if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
  408. if err = tc.storeError(db,
  409. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  410. "malformed acmeValidationV1 extension value"))); err != nil {
  411. return nil, err
  412. }
  413. return tc, nil
  414. }
  415. if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
  416. if err = tc.storeError(db,
  417. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  418. "expected acmeValidationV1 extension value %s for this challenge but got %s",
  419. hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))); err != nil {
  420. return nil, err
  421. }
  422. return tc, nil
  423. }
  424. upd := &tlsALPN01Challenge{tc.baseChallenge.clone()}
  425. upd.Status = StatusValid
  426. upd.Error = nil
  427. upd.Validated = clock.Now()
  428. if err := upd.save(db, tc); err != nil {
  429. return nil, err
  430. }
  431. return upd, nil
  432. }
  433. if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
  434. foundIDPeAcmeIdentifierV1Obsolete = true
  435. }
  436. }
  437. if foundIDPeAcmeIdentifierV1Obsolete {
  438. if err = tc.storeError(db,
  439. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  440. "obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))); err != nil {
  441. return nil, err
  442. }
  443. return tc, nil
  444. }
  445. if err = tc.storeError(db,
  446. RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
  447. "missing acmeValidationV1 extension"))); err != nil {
  448. return nil, err
  449. }
  450. return tc, nil
  451. }
  452. // dns01Challenge represents an dns-01 acme challenge.
  453. type dns01Challenge struct {
  454. *baseChallenge
  455. }
  456. // newDNS01Challenge returns a new acme dns-01 challenge.
  457. func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  458. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  459. if err != nil {
  460. return nil, err
  461. }
  462. bc.Type = "dns-01"
  463. bc.Value = ops.Identifier.Value
  464. dc := &dns01Challenge{bc}
  465. if err := dc.save(db, nil); err != nil {
  466. return nil, err
  467. }
  468. return dc, nil
  469. }
  470. // KeyAuthorization creates the ACME key authorization value from a token
  471. // and a jwk.
  472. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  473. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  474. if err != nil {
  475. return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
  476. }
  477. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  478. return fmt.Sprintf("%s.%s", token, encPrint), nil
  479. }
  480. // validate attempts to validate the challenge. If the challenge has been
  481. // satisfactorily validated, the 'status' and 'validated' attributes are
  482. // updated.
  483. func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  484. // If already valid or invalid then return without performing validation.
  485. if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
  486. return dc, nil
  487. }
  488. // Normalize domain for wildcard DNS names
  489. // This is done to avoid making TXT lookups for domains like
  490. // _acme-challenge.*.example.com
  491. // Instead perform txt lookup for _acme-challenge.example.com
  492. domain := strings.TrimPrefix(dc.Value, "*.")
  493. txtRecords, err := vo.lookupTxt("_acme-challenge." + domain)
  494. if err != nil {
  495. if err = dc.storeError(db,
  496. DNSErr(errors.Wrapf(err, "error looking up TXT "+
  497. "records for domain %s", domain))); err != nil {
  498. return nil, err
  499. }
  500. return dc, nil
  501. }
  502. expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
  503. if err != nil {
  504. return nil, err
  505. }
  506. h := sha256.Sum256([]byte(expectedKeyAuth))
  507. expected := base64.RawURLEncoding.EncodeToString(h[:])
  508. var found bool
  509. for _, r := range txtRecords {
  510. if r == expected {
  511. found = true
  512. break
  513. }
  514. }
  515. if !found {
  516. if err = dc.storeError(db,
  517. RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
  518. "does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
  519. return nil, err
  520. }
  521. return dc, nil
  522. }
  523. // Update and store the challenge.
  524. upd := &dns01Challenge{dc.baseChallenge.clone()}
  525. upd.Status = StatusValid
  526. upd.Error = nil
  527. upd.Validated = time.Now().UTC()
  528. if err := upd.save(db, dc); err != nil {
  529. return nil, err
  530. }
  531. return upd, nil
  532. }
  533. // getChallenge retrieves and unmarshals an ACME challenge type from the database.
  534. func getChallenge(db nosql.DB, id string) (challenge, error) {
  535. b, err := db.Get(challengeTable, []byte(id))
  536. if nosql.IsErrNotFound(err) {
  537. return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
  538. } else if err != nil {
  539. return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
  540. }
  541. ch, err := unmarshalChallenge(b)
  542. if err != nil {
  543. return nil, err
  544. }
  545. return ch, nil
  546. }