challenge.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package acme
  2. import (
  3. "crypto"
  4. "crypto/sha256"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/pkg/errors"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. "github.com/smallstep/cli/jose"
  15. "github.com/smallstep/nosql"
  16. )
  17. // Challenge is a subset of the challenge type containing only those attributes
  18. // required for responses in the ACME protocol.
  19. type Challenge struct {
  20. Type string `json:"type"`
  21. Status string `json:"status"`
  22. Token string `json:"token"`
  23. Validated string `json:"validated,omitempty"`
  24. URL string `json:"url"`
  25. Error *AError `json:"error,omitempty"`
  26. ID string `json:"-"`
  27. AuthzID string `json:"-"`
  28. }
  29. // ToLog enables response logging.
  30. func (c *Challenge) ToLog() (interface{}, error) {
  31. b, err := json.Marshal(c)
  32. if err != nil {
  33. return nil, ServerInternalErr(errors.Wrap(err, "error marshaling challenge for logging"))
  34. }
  35. return string(b), nil
  36. }
  37. // GetID returns the Challenge ID.
  38. func (c *Challenge) GetID() string {
  39. return c.ID
  40. }
  41. // GetAuthzID returns the parent Authz ID that owns the Challenge.
  42. func (c *Challenge) GetAuthzID() string {
  43. return c.AuthzID
  44. }
  45. type httpGetter func(string) (*http.Response, error)
  46. type lookupTxt func(string) ([]string, error)
  47. type validateOptions struct {
  48. httpGet httpGetter
  49. lookupTxt lookupTxt
  50. }
  51. // challenge is the interface ACME challenege types must implement.
  52. type challenge interface {
  53. save(db nosql.DB, swap challenge) error
  54. validate(nosql.DB, *jose.JSONWebKey, validateOptions) (challenge, error)
  55. getType() string
  56. getError() *AError
  57. getValue() string
  58. getStatus() string
  59. getID() string
  60. getAuthzID() string
  61. getToken() string
  62. clone() *baseChallenge
  63. getAccountID() string
  64. getValidated() time.Time
  65. getCreated() time.Time
  66. toACME(nosql.DB, *directory, provisioner.Interface) (*Challenge, error)
  67. }
  68. // ChallengeOptions is the type used to created a new Challenge.
  69. type ChallengeOptions struct {
  70. AccountID string
  71. AuthzID string
  72. Identifier Identifier
  73. }
  74. // baseChallenge is the base Challenge type that others build from.
  75. type baseChallenge struct {
  76. ID string `json:"id"`
  77. AccountID string `json:"accountID"`
  78. AuthzID string `json:"authzID"`
  79. Type string `json:"type"`
  80. Status string `json:"status"`
  81. Token string `json:"token"`
  82. Value string `json:"value"`
  83. Validated time.Time `json:"validated"`
  84. Created time.Time `json:"created"`
  85. Error *AError `json:"error"`
  86. }
  87. func newBaseChallenge(accountID, authzID string) (*baseChallenge, error) {
  88. id, err := randID()
  89. if err != nil {
  90. return nil, Wrap(err, "error generating random id for ACME challenge")
  91. }
  92. token, err := randID()
  93. if err != nil {
  94. return nil, Wrap(err, "error generating token for ACME challenge")
  95. }
  96. return &baseChallenge{
  97. ID: id,
  98. AccountID: accountID,
  99. AuthzID: authzID,
  100. Status: StatusPending,
  101. Token: token,
  102. Created: clock.Now(),
  103. }, nil
  104. }
  105. // getID returns the id of the baseChallenge.
  106. func (bc *baseChallenge) getID() string {
  107. return bc.ID
  108. }
  109. // getAuthzID returns the authz ID of the baseChallenge.
  110. func (bc *baseChallenge) getAuthzID() string {
  111. return bc.AuthzID
  112. }
  113. // getAccountID returns the account id of the baseChallenge.
  114. func (bc *baseChallenge) getAccountID() string {
  115. return bc.AccountID
  116. }
  117. // getType returns the type of the baseChallenge.
  118. func (bc *baseChallenge) getType() string {
  119. return bc.Type
  120. }
  121. // getValue returns the type of the baseChallenge.
  122. func (bc *baseChallenge) getValue() string {
  123. return bc.Value
  124. }
  125. // getStatus returns the status of the baseChallenge.
  126. func (bc *baseChallenge) getStatus() string {
  127. return bc.Status
  128. }
  129. // getToken returns the token of the baseChallenge.
  130. func (bc *baseChallenge) getToken() string {
  131. return bc.Token
  132. }
  133. // getValidated returns the validated time of the baseChallenge.
  134. func (bc *baseChallenge) getValidated() time.Time {
  135. return bc.Validated
  136. }
  137. // getCreated returns the created time of the baseChallenge.
  138. func (bc *baseChallenge) getCreated() time.Time {
  139. return bc.Created
  140. }
  141. // getCreated returns the created time of the baseChallenge.
  142. func (bc *baseChallenge) getError() *AError {
  143. return bc.Error
  144. }
  145. // toACME converts the internal Challenge type into the public acmeChallenge
  146. // type for presentation in the ACME protocol.
  147. func (bc *baseChallenge) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Challenge, error) {
  148. ac := &Challenge{
  149. Type: bc.getType(),
  150. Status: bc.getStatus(),
  151. Token: bc.getToken(),
  152. URL: dir.getLink(ChallengeLink, URLSafeProvisionerName(p), true, bc.getID()),
  153. ID: bc.getID(),
  154. AuthzID: bc.getAuthzID(),
  155. }
  156. if !bc.Validated.IsZero() {
  157. ac.Validated = bc.Validated.Format(time.RFC3339)
  158. }
  159. if bc.Error != nil {
  160. ac.Error = bc.Error
  161. }
  162. return ac, nil
  163. }
  164. // save writes the challenge to disk. For new challenges 'old' should be nil,
  165. // otherwise 'old' should be a pointer to the acme challenge as it was at the
  166. // start of the request. This method will fail if the value currently found
  167. // in the bucket/row does not match the value of 'old'.
  168. func (bc *baseChallenge) save(db nosql.DB, old challenge) error {
  169. newB, err := json.Marshal(bc)
  170. if err != nil {
  171. return ServerInternalErr(errors.Wrap(err,
  172. "error marshaling new acme challenge"))
  173. }
  174. var oldB []byte
  175. if old == nil {
  176. oldB = nil
  177. } else {
  178. oldB, err = json.Marshal(old)
  179. if err != nil {
  180. return ServerInternalErr(errors.Wrap(err,
  181. "error marshaling old acme challenge"))
  182. }
  183. }
  184. _, swapped, err := db.CmpAndSwap(challengeTable, []byte(bc.ID), oldB, newB)
  185. switch {
  186. case err != nil:
  187. return ServerInternalErr(errors.Wrap(err, "error saving acme challenge"))
  188. case !swapped:
  189. return ServerInternalErr(errors.New("error saving acme challenge; " +
  190. "acme challenge has changed since last read"))
  191. default:
  192. return nil
  193. }
  194. }
  195. func (bc *baseChallenge) clone() *baseChallenge {
  196. u := *bc
  197. return &u
  198. }
  199. func (bc *baseChallenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  200. return nil, ServerInternalErr(errors.New("unimplemented"))
  201. }
  202. func (bc *baseChallenge) storeError(db nosql.DB, err *Error) error {
  203. clone := bc.clone()
  204. clone.Error = err.ToACME()
  205. return clone.save(db, bc)
  206. }
  207. // unmarshalChallenge unmarshals a challenge type into the correct sub-type.
  208. func unmarshalChallenge(data []byte) (challenge, error) {
  209. var getType struct {
  210. Type string `json:"type"`
  211. }
  212. if err := json.Unmarshal(data, &getType); err != nil {
  213. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
  214. }
  215. switch getType.Type {
  216. case "dns-01":
  217. var bc baseChallenge
  218. if err := json.Unmarshal(data, &bc); err != nil {
  219. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
  220. "challenge type into dns01Challenge"))
  221. }
  222. return &dns01Challenge{&bc}, nil
  223. case "http-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 http01Challenge"))
  228. }
  229. return &http01Challenge{&bc}, nil
  230. default:
  231. return nil, ServerInternalErr(errors.Errorf("unexpected challenge type %s", getType.Type))
  232. }
  233. }
  234. // http01Challenge represents an http-01 acme challenge.
  235. type http01Challenge struct {
  236. *baseChallenge
  237. }
  238. // newHTTP01Challenge returns a new acme http-01 challenge.
  239. func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  240. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  241. if err != nil {
  242. return nil, err
  243. }
  244. bc.Type = "http-01"
  245. bc.Value = ops.Identifier.Value
  246. hc := &http01Challenge{bc}
  247. if err := hc.save(db, nil); err != nil {
  248. return nil, err
  249. }
  250. return hc, nil
  251. }
  252. // Validate attempts to validate the challenge. If the challenge has been
  253. // satisfactorily validated, the 'status' and 'validated' attributes are
  254. // updated.
  255. func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  256. // If already valid or invalid then return without performing validation.
  257. if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
  258. return hc, nil
  259. }
  260. url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
  261. resp, err := vo.httpGet(url)
  262. if err != nil {
  263. if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
  264. "error doing http GET for url %s", url))); err != nil {
  265. return nil, err
  266. }
  267. return hc, nil
  268. }
  269. if resp.StatusCode >= 400 {
  270. if err = hc.storeError(db,
  271. ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
  272. url, resp.StatusCode))); err != nil {
  273. return nil, err
  274. }
  275. return hc, nil
  276. }
  277. defer resp.Body.Close()
  278. body, err := ioutil.ReadAll(resp.Body)
  279. if err != nil {
  280. return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
  281. "response body for url %s", url))
  282. }
  283. keyAuth := strings.Trim(string(body), "\r\n")
  284. expected, err := KeyAuthorization(hc.Token, jwk)
  285. if err != nil {
  286. return nil, err
  287. }
  288. if keyAuth != expected {
  289. if err = hc.storeError(db,
  290. RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
  291. "expected %s, but got %s", expected, keyAuth))); err != nil {
  292. return nil, err
  293. }
  294. return hc, nil
  295. }
  296. // Update and store the challenge.
  297. upd := &http01Challenge{hc.baseChallenge.clone()}
  298. upd.Status = StatusValid
  299. upd.Error = nil
  300. upd.Validated = clock.Now()
  301. if err := upd.save(db, hc); err != nil {
  302. return nil, err
  303. }
  304. return upd, nil
  305. }
  306. // dns01Challenge represents an dns-01 acme challenge.
  307. type dns01Challenge struct {
  308. *baseChallenge
  309. }
  310. // newDNS01Challenge returns a new acme dns-01 challenge.
  311. func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
  312. bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
  313. if err != nil {
  314. return nil, err
  315. }
  316. bc.Type = "dns-01"
  317. bc.Value = ops.Identifier.Value
  318. dc := &dns01Challenge{bc}
  319. if err := dc.save(db, nil); err != nil {
  320. return nil, err
  321. }
  322. return dc, nil
  323. }
  324. // KeyAuthorization creates the ACME key authorization value from a token
  325. // and a jwk.
  326. func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
  327. thumbprint, err := jwk.Thumbprint(crypto.SHA256)
  328. if err != nil {
  329. return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
  330. }
  331. encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
  332. return fmt.Sprintf("%s.%s", token, encPrint), nil
  333. }
  334. // validate attempts to validate the challenge. If the challenge has been
  335. // satisfactorily validated, the 'status' and 'validated' attributes are
  336. // updated.
  337. func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
  338. // If already valid or invalid then return without performing validation.
  339. if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
  340. return dc, nil
  341. }
  342. txtRecords, err := vo.lookupTxt("_acme-challenge." + dc.Value)
  343. if err != nil {
  344. if err = dc.storeError(db,
  345. DNSErr(errors.Wrapf(err, "error looking up TXT "+
  346. "records for domain %s", dc.Value))); err != nil {
  347. return nil, err
  348. }
  349. return dc, nil
  350. }
  351. expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
  352. if err != nil {
  353. return nil, err
  354. }
  355. h := sha256.Sum256([]byte(expectedKeyAuth))
  356. expected := base64.RawURLEncoding.EncodeToString(h[:])
  357. var found bool
  358. for _, r := range txtRecords {
  359. if r == expected {
  360. found = true
  361. break
  362. }
  363. }
  364. if !found {
  365. if err = dc.storeError(db,
  366. RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
  367. "does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
  368. return nil, err
  369. }
  370. return dc, nil
  371. }
  372. // Update and store the challenge.
  373. upd := &dns01Challenge{dc.baseChallenge.clone()}
  374. upd.Status = StatusValid
  375. upd.Error = nil
  376. upd.Validated = time.Now().UTC()
  377. if err := upd.save(db, dc); err != nil {
  378. return nil, err
  379. }
  380. return upd, nil
  381. }
  382. // getChallenge retrieves and unmarshals an ACME challenge type from the database.
  383. func getChallenge(db nosql.DB, id string) (challenge, error) {
  384. b, err := db.Get(challengeTable, []byte(id))
  385. if nosql.IsErrNotFound(err) {
  386. return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
  387. } else if err != nil {
  388. return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
  389. }
  390. ch, err := unmarshalChallenge(b)
  391. if err != nil {
  392. return nil, err
  393. }
  394. return ch, nil
  395. }