acmeClient.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package ca
  2. import (
  3. "crypto/x509"
  4. "encoding/base64"
  5. "encoding/json"
  6. "encoding/pem"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "github.com/pkg/errors"
  12. "go.step.sm/crypto/jose"
  13. "github.com/smallstep/certificates/acme"
  14. acmeAPI "github.com/smallstep/certificates/acme/api"
  15. )
  16. // ACMEClient implements an HTTP client to an ACME API.
  17. type ACMEClient struct {
  18. client *http.Client
  19. dirLoc string
  20. dir *acmeAPI.Directory
  21. acc *acme.Account
  22. Key *jose.JSONWebKey
  23. kid string
  24. }
  25. // NewACMEClient initializes a new ACMEClient.
  26. func NewACMEClient(endpoint string, contact []string, opts ...ClientOption) (*ACMEClient, error) {
  27. // Retrieve transport from options.
  28. o := defaultClientOptions()
  29. if err := o.apply(opts); err != nil {
  30. return nil, err
  31. }
  32. tr, err := o.getTransport(endpoint)
  33. if err != nil {
  34. return nil, err
  35. }
  36. ac := &ACMEClient{
  37. client: &http.Client{
  38. Transport: tr,
  39. },
  40. dirLoc: endpoint,
  41. }
  42. req, err := http.NewRequest("GET", endpoint, http.NoBody)
  43. if err != nil {
  44. return nil, errors.Wrapf(err, "creating GET request %s failed", endpoint)
  45. }
  46. req.Header.Set("User-Agent", UserAgent)
  47. enforceRequestID(req)
  48. resp, err := ac.client.Do(req)
  49. if err != nil {
  50. return nil, errors.Wrapf(err, "client GET %s failed", endpoint)
  51. }
  52. defer resp.Body.Close()
  53. if resp.StatusCode >= 400 {
  54. return nil, readACMEError(resp.Body)
  55. }
  56. var dir acmeAPI.Directory
  57. if err := readJSON(resp.Body, &dir); err != nil {
  58. return nil, errors.Wrapf(err, "error reading %s", endpoint)
  59. }
  60. ac.dir = &dir
  61. ac.Key, err = jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  62. if err != nil {
  63. return nil, err
  64. }
  65. nar := &acmeAPI.NewAccountRequest{
  66. Contact: contact,
  67. TermsOfServiceAgreed: true,
  68. }
  69. if o.eabKeyID != "" {
  70. if nar.ExternalAccountBinding, err = ac.externalAccountBinding(o.eabKeyID, o.eabHMACKey); err != nil {
  71. return nil, err
  72. }
  73. }
  74. payload, err := json.Marshal(nar)
  75. if err != nil {
  76. return nil, errors.Wrap(err, "error marshaling new account request")
  77. }
  78. resp, err = ac.post(payload, ac.dir.NewAccount, withJWK(ac))
  79. if err != nil {
  80. return nil, err
  81. }
  82. defer resp.Body.Close()
  83. if resp.StatusCode >= 400 {
  84. return nil, readACMEError(resp.Body)
  85. }
  86. var acc acme.Account
  87. if err := readJSON(resp.Body, &acc); err != nil {
  88. return nil, errors.Wrapf(err, "error reading %s", dir.NewAccount)
  89. }
  90. ac.acc = &acc
  91. ac.kid = resp.Header.Get("Location")
  92. return ac, nil
  93. }
  94. // externalAccountBinding returns the external account binding of a new account
  95. // request (RFC 8555 section 7.3.4): a JWS over the account's public key, signed
  96. // with the HMAC key, whose kid is the key ID and whose url is the new account
  97. // URL.
  98. func (c *ACMEClient) externalAccountBinding(keyID string, hmacKey []byte) (*acmeAPI.ExternalAccountBinding, error) {
  99. payload, err := json.Marshal(c.Key.Public())
  100. if err != nil {
  101. return nil, errors.Wrap(err, "error marshaling the account key")
  102. }
  103. so := new(jose.SignerOptions)
  104. so.WithHeader("kid", keyID)
  105. so.WithHeader("url", c.dir.NewAccount)
  106. signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: hmacKey}, so)
  107. if err != nil {
  108. return nil, errors.Wrap(err, "error creating external account binding signer")
  109. }
  110. signed, err := signer.Sign(payload)
  111. if err != nil {
  112. return nil, errors.Errorf("error signing external account binding: %s", jose.TrimPrefix(err))
  113. }
  114. raw, err := serialize(signed)
  115. if err != nil {
  116. return nil, err
  117. }
  118. eab := new(acmeAPI.ExternalAccountBinding)
  119. if err := json.Unmarshal([]byte(raw), eab); err != nil {
  120. return nil, errors.Wrap(err, "error reading external account binding")
  121. }
  122. return eab, nil
  123. }
  124. // GetDirectory makes a directory request to the ACME api and returns an
  125. // ACME directory object.
  126. func (c *ACMEClient) GetDirectory() (*acmeAPI.Directory, error) {
  127. return c.dir, nil
  128. }
  129. // GetNonce makes a nonce request to the ACME api and returns an
  130. // ACME directory object.
  131. func (c *ACMEClient) GetNonce() (string, error) {
  132. req, err := http.NewRequest("GET", c.dir.NewNonce, http.NoBody)
  133. if err != nil {
  134. return "", errors.Wrapf(err, "creating GET request %s failed", c.dir.NewNonce)
  135. }
  136. req.Header.Set("User-Agent", UserAgent)
  137. enforceRequestID(req)
  138. resp, err := c.client.Do(req)
  139. if err != nil {
  140. return "", errors.Wrapf(err, "client GET %s failed", c.dir.NewNonce)
  141. }
  142. defer resp.Body.Close()
  143. if resp.StatusCode >= 400 {
  144. return "", readACMEError(resp.Body)
  145. }
  146. return resp.Header.Get("Replay-Nonce"), nil
  147. }
  148. type withHeaderOption func(so *jose.SignerOptions)
  149. func withJWK(c *ACMEClient) withHeaderOption {
  150. return func(so *jose.SignerOptions) {
  151. so.WithHeader("jwk", c.Key.Public())
  152. }
  153. }
  154. func withKid(c *ACMEClient) withHeaderOption {
  155. return func(so *jose.SignerOptions) {
  156. so.WithHeader("kid", c.kid)
  157. }
  158. }
  159. // serialize serializes a json web signature and doesn't omit empty fields.
  160. func serialize(obj *jose.JSONWebSignature) (string, error) {
  161. raw, err := obj.CompactSerialize()
  162. if err != nil {
  163. return "", errors.Wrap(err, "error serializing JWS")
  164. }
  165. parts := strings.Split(raw, ".")
  166. msg := struct {
  167. Protected string `json:"protected"`
  168. Payload string `json:"payload"`
  169. Signature string `json:"signature"`
  170. }{Protected: parts[0], Payload: parts[1], Signature: parts[2]}
  171. b, err := json.Marshal(msg)
  172. if err != nil {
  173. return "", errors.Wrap(err, "error marshaling jws message")
  174. }
  175. return string(b), nil
  176. }
  177. func (c *ACMEClient) post(payload []byte, url string, headerOps ...withHeaderOption) (*http.Response, error) {
  178. if c.Key == nil {
  179. return nil, errors.New("acme client not configured with account")
  180. }
  181. nonce, err := c.GetNonce()
  182. if err != nil {
  183. return nil, err
  184. }
  185. so := new(jose.SignerOptions)
  186. so.WithHeader("nonce", nonce)
  187. so.WithHeader("url", url)
  188. for _, hop := range headerOps {
  189. hop(so)
  190. }
  191. signer, err := jose.NewSigner(jose.SigningKey{
  192. Algorithm: jose.SignatureAlgorithm(c.Key.Algorithm),
  193. Key: c.Key.Key,
  194. }, so)
  195. if err != nil {
  196. return nil, errors.Wrap(err, "error creating JWS signer")
  197. }
  198. signed, err := signer.Sign(payload)
  199. if err != nil {
  200. return nil, errors.Errorf("error signing payload: %s", jose.TrimPrefix(err))
  201. }
  202. raw, err := serialize(signed)
  203. if err != nil {
  204. return nil, err
  205. }
  206. req, err := http.NewRequest("POST", url, strings.NewReader(raw))
  207. if err != nil {
  208. return nil, errors.Wrapf(err, "creating POST request %s failed", url)
  209. }
  210. req.Header.Set("Content-Type", "application/jose+json")
  211. req.Header.Set("User-Agent", UserAgent)
  212. enforceRequestID(req)
  213. resp, err := c.client.Do(req)
  214. if err != nil {
  215. return nil, errors.Wrapf(err, "client POST %s failed", c.dir.NewOrder)
  216. }
  217. return resp, nil
  218. }
  219. // NewOrder creates and returns the information for a new ACME order.
  220. func (c *ACMEClient) NewOrder(payload []byte) (*acme.Order, error) {
  221. resp, err := c.post(payload, c.dir.NewOrder, withKid(c))
  222. if err != nil {
  223. return nil, err
  224. }
  225. defer resp.Body.Close()
  226. if resp.StatusCode >= 400 {
  227. return nil, readACMEError(resp.Body)
  228. }
  229. var o acme.Order
  230. if err := readJSON(resp.Body, &o); err != nil {
  231. return nil, errors.Wrapf(err, "error reading %s", c.dir.NewOrder)
  232. }
  233. o.ID = resp.Header.Get("Location")
  234. return &o, nil
  235. }
  236. // GetChallenge returns the Challenge at the given path.
  237. // With the validate parameter set to True this method will attempt to validate the
  238. // challenge before returning it.
  239. func (c *ACMEClient) GetChallenge(url string) (*acme.Challenge, error) {
  240. resp, err := c.post(nil, url, withKid(c))
  241. if err != nil {
  242. return nil, err
  243. }
  244. defer resp.Body.Close()
  245. if resp.StatusCode >= 400 {
  246. return nil, readACMEError(resp.Body)
  247. }
  248. var ch acme.Challenge
  249. if err := readJSON(resp.Body, &ch); err != nil {
  250. return nil, errors.Wrapf(err, "error reading %s", url)
  251. }
  252. return &ch, nil
  253. }
  254. // ValidateChallenge returns the Challenge at the given path.
  255. // With the validate parameter set to True this method will attempt to validate the
  256. // challenge before returning it.
  257. func (c *ACMEClient) ValidateChallenge(url string) error {
  258. resp, err := c.post([]byte("{}"), url, withKid(c))
  259. if err != nil {
  260. return err
  261. }
  262. defer resp.Body.Close()
  263. if resp.StatusCode >= 400 {
  264. return readACMEError(resp.Body)
  265. }
  266. return nil
  267. }
  268. // ValidateWithPayload will attempt to validate the challenge at the given url
  269. // with the given attestation payload.
  270. func (c *ACMEClient) ValidateWithPayload(url string, payload []byte) error {
  271. resp, err := c.post(payload, url, withKid(c))
  272. if err != nil {
  273. return err
  274. }
  275. defer resp.Body.Close()
  276. if resp.StatusCode >= 400 {
  277. return readACMEError(resp.Body)
  278. }
  279. return nil
  280. }
  281. // GetAuthz returns the Authz at the given path.
  282. func (c *ACMEClient) GetAuthz(url string) (*acme.Authorization, error) {
  283. resp, err := c.post(nil, url, withKid(c))
  284. if err != nil {
  285. return nil, err
  286. }
  287. defer resp.Body.Close()
  288. if resp.StatusCode >= 400 {
  289. return nil, readACMEError(resp.Body)
  290. }
  291. var az acme.Authorization
  292. if err := readJSON(resp.Body, &az); err != nil {
  293. return nil, errors.Wrapf(err, "error reading %s", url)
  294. }
  295. return &az, nil
  296. }
  297. // GetOrder returns the Order at the given path.
  298. func (c *ACMEClient) GetOrder(url string) (*acme.Order, error) {
  299. resp, err := c.post(nil, url, withKid(c))
  300. if err != nil {
  301. return nil, err
  302. }
  303. defer resp.Body.Close()
  304. if resp.StatusCode >= 400 {
  305. return nil, readACMEError(resp.Body)
  306. }
  307. var o acme.Order
  308. if err := readJSON(resp.Body, &o); err != nil {
  309. return nil, errors.Wrapf(err, "error reading %s", url)
  310. }
  311. return &o, nil
  312. }
  313. // FinalizeOrder makes a finalize request to the ACME api.
  314. func (c *ACMEClient) FinalizeOrder(url string, csr *x509.CertificateRequest) error {
  315. payload, err := json.Marshal(acmeAPI.FinalizeRequest{
  316. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  317. })
  318. if err != nil {
  319. return errors.Wrap(err, "error marshaling finalize request")
  320. }
  321. resp, err := c.post(payload, url, withKid(c))
  322. if err != nil {
  323. return err
  324. }
  325. defer resp.Body.Close()
  326. if resp.StatusCode >= 400 {
  327. return readACMEError(resp.Body)
  328. }
  329. return nil
  330. }
  331. // GetCertificate retrieves the certificate along with all intermediates.
  332. func (c *ACMEClient) GetCertificate(url string) (*x509.Certificate, []*x509.Certificate, error) {
  333. resp, err := c.post(nil, url, withKid(c))
  334. if err != nil {
  335. return nil, nil, err
  336. }
  337. defer resp.Body.Close()
  338. if resp.StatusCode >= 400 {
  339. return nil, nil, readACMEError(resp.Body)
  340. }
  341. defer resp.Body.Close()
  342. bodyBytes, err := io.ReadAll(resp.Body)
  343. if err != nil {
  344. return nil, nil, errors.Wrap(err, "error reading GET certificate response")
  345. }
  346. var certs []*x509.Certificate
  347. block, rest := pem.Decode(bodyBytes)
  348. if block == nil {
  349. return nil, nil, errors.New("failed to parse any certificates from response")
  350. }
  351. for block != nil {
  352. cert, err := x509.ParseCertificate(block.Bytes)
  353. if err != nil {
  354. return nil, nil, errors.Wrap(err, "error parsing certificate pem response")
  355. }
  356. certs = append(certs, cert)
  357. block, rest = pem.Decode(rest)
  358. }
  359. return certs[0], certs[1:], nil
  360. }
  361. // GetAccountOrders retrieves the orders belonging to the given account.
  362. func (c *ACMEClient) GetAccountOrders() ([]string, error) {
  363. if c.acc == nil {
  364. return nil, errors.New("acme client not configured with account")
  365. }
  366. resp, err := c.post(nil, c.acc.OrdersURL, withKid(c))
  367. if err != nil {
  368. return nil, err
  369. }
  370. defer resp.Body.Close()
  371. if resp.StatusCode >= 400 {
  372. return nil, readACMEError(resp.Body)
  373. }
  374. var orders []string
  375. if err := readJSON(resp.Body, &orders); err != nil {
  376. return nil, errors.Wrapf(err, "error reading %s", c.acc.OrdersURL)
  377. }
  378. return orders, nil
  379. }
  380. func readACMEError(r io.ReadCloser) error {
  381. defer r.Close()
  382. b, err := io.ReadAll(r)
  383. if err != nil {
  384. return errors.Wrap(err, "error reading from body")
  385. }
  386. ae := new(acme.Error)
  387. err = json.Unmarshal(b, &ae)
  388. // If we successfully marshaled to an ACMEError then return the ACMEError.
  389. if err != nil || ae.Error() == "" {
  390. fmt.Printf("b = %s\n", b)
  391. // Throw up our hands.
  392. return errors.Errorf("%s", b)
  393. }
  394. return ae
  395. }