acmeClient.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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) //nolint:gosec // request to configured ACME server
  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. payload, err := json.Marshal(nar)
  70. if err != nil {
  71. return nil, errors.Wrap(err, "error marshaling new account request")
  72. }
  73. resp, err = ac.post(payload, ac.dir.NewAccount, withJWK(ac))
  74. if err != nil {
  75. return nil, err
  76. }
  77. defer resp.Body.Close()
  78. if resp.StatusCode >= 400 {
  79. return nil, readACMEError(resp.Body)
  80. }
  81. var acc acme.Account
  82. if err := readJSON(resp.Body, &acc); err != nil {
  83. return nil, errors.Wrapf(err, "error reading %s", dir.NewAccount)
  84. }
  85. ac.acc = &acc
  86. ac.kid = resp.Header.Get("Location")
  87. return ac, nil
  88. }
  89. // GetDirectory makes a directory request to the ACME api and returns an
  90. // ACME directory object.
  91. func (c *ACMEClient) GetDirectory() (*acmeAPI.Directory, error) {
  92. return c.dir, nil
  93. }
  94. // GetNonce makes a nonce request to the ACME api and returns an
  95. // ACME directory object.
  96. func (c *ACMEClient) GetNonce() (string, error) {
  97. req, err := http.NewRequest("GET", c.dir.NewNonce, http.NoBody)
  98. if err != nil {
  99. return "", errors.Wrapf(err, "creating GET request %s failed", c.dir.NewNonce)
  100. }
  101. req.Header.Set("User-Agent", UserAgent)
  102. enforceRequestID(req)
  103. resp, err := c.client.Do(req) //nolint:gosec // request to configured ACME server
  104. if err != nil {
  105. return "", errors.Wrapf(err, "client GET %s failed", c.dir.NewNonce)
  106. }
  107. defer resp.Body.Close()
  108. if resp.StatusCode >= 400 {
  109. return "", readACMEError(resp.Body)
  110. }
  111. return resp.Header.Get("Replay-Nonce"), nil
  112. }
  113. type withHeaderOption func(so *jose.SignerOptions)
  114. func withJWK(c *ACMEClient) withHeaderOption {
  115. return func(so *jose.SignerOptions) {
  116. so.WithHeader("jwk", c.Key.Public())
  117. }
  118. }
  119. func withKid(c *ACMEClient) withHeaderOption {
  120. return func(so *jose.SignerOptions) {
  121. so.WithHeader("kid", c.kid)
  122. }
  123. }
  124. // serialize serializes a json web signature and doesn't omit empty fields.
  125. func serialize(obj *jose.JSONWebSignature) (string, error) {
  126. raw, err := obj.CompactSerialize()
  127. if err != nil {
  128. return "", errors.Wrap(err, "error serializing JWS")
  129. }
  130. parts := strings.Split(raw, ".")
  131. msg := struct {
  132. Protected string `json:"protected"`
  133. Payload string `json:"payload"`
  134. Signature string `json:"signature"`
  135. }{Protected: parts[0], Payload: parts[1], Signature: parts[2]}
  136. b, err := json.Marshal(msg)
  137. if err != nil {
  138. return "", errors.Wrap(err, "error marshaling jws message")
  139. }
  140. return string(b), nil
  141. }
  142. func (c *ACMEClient) post(payload []byte, url string, headerOps ...withHeaderOption) (*http.Response, error) {
  143. if c.Key == nil {
  144. return nil, errors.New("acme client not configured with account")
  145. }
  146. nonce, err := c.GetNonce()
  147. if err != nil {
  148. return nil, err
  149. }
  150. so := new(jose.SignerOptions)
  151. so.WithHeader("nonce", nonce)
  152. so.WithHeader("url", url)
  153. for _, hop := range headerOps {
  154. hop(so)
  155. }
  156. signer, err := jose.NewSigner(jose.SigningKey{
  157. Algorithm: jose.SignatureAlgorithm(c.Key.Algorithm),
  158. Key: c.Key.Key,
  159. }, so)
  160. if err != nil {
  161. return nil, errors.Wrap(err, "error creating JWS signer")
  162. }
  163. signed, err := signer.Sign(payload)
  164. if err != nil {
  165. return nil, errors.Errorf("error signing payload: %s", jose.TrimPrefix(err))
  166. }
  167. raw, err := serialize(signed)
  168. if err != nil {
  169. return nil, err
  170. }
  171. req, err := http.NewRequest("POST", url, strings.NewReader(raw))
  172. if err != nil {
  173. return nil, errors.Wrapf(err, "creating POST request %s failed", url)
  174. }
  175. req.Header.Set("Content-Type", "application/jose+json")
  176. req.Header.Set("User-Agent", UserAgent)
  177. enforceRequestID(req)
  178. resp, err := c.client.Do(req) //nolint:gosec // request to configured ACME server
  179. if err != nil {
  180. return nil, errors.Wrapf(err, "client POST %s failed", c.dir.NewOrder)
  181. }
  182. return resp, nil
  183. }
  184. // NewOrder creates and returns the information for a new ACME order.
  185. func (c *ACMEClient) NewOrder(payload []byte) (*acme.Order, error) {
  186. resp, err := c.post(payload, c.dir.NewOrder, withKid(c))
  187. if err != nil {
  188. return nil, err
  189. }
  190. defer resp.Body.Close()
  191. if resp.StatusCode >= 400 {
  192. return nil, readACMEError(resp.Body)
  193. }
  194. var o acme.Order
  195. if err := readJSON(resp.Body, &o); err != nil {
  196. return nil, errors.Wrapf(err, "error reading %s", c.dir.NewOrder)
  197. }
  198. o.ID = resp.Header.Get("Location")
  199. return &o, nil
  200. }
  201. // GetChallenge returns the Challenge at the given path.
  202. // With the validate parameter set to True this method will attempt to validate the
  203. // challenge before returning it.
  204. func (c *ACMEClient) GetChallenge(url string) (*acme.Challenge, error) {
  205. resp, err := c.post(nil, url, withKid(c))
  206. if err != nil {
  207. return nil, err
  208. }
  209. defer resp.Body.Close()
  210. if resp.StatusCode >= 400 {
  211. return nil, readACMEError(resp.Body)
  212. }
  213. var ch acme.Challenge
  214. if err := readJSON(resp.Body, &ch); err != nil {
  215. return nil, errors.Wrapf(err, "error reading %s", url)
  216. }
  217. return &ch, nil
  218. }
  219. // ValidateChallenge returns the Challenge at the given path.
  220. // With the validate parameter set to True this method will attempt to validate the
  221. // challenge before returning it.
  222. func (c *ACMEClient) ValidateChallenge(url string) error {
  223. resp, err := c.post([]byte("{}"), url, withKid(c))
  224. if err != nil {
  225. return err
  226. }
  227. defer resp.Body.Close()
  228. if resp.StatusCode >= 400 {
  229. return readACMEError(resp.Body)
  230. }
  231. return nil
  232. }
  233. // ValidateWithPayload will attempt to validate the challenge at the given url
  234. // with the given attestation payload.
  235. func (c *ACMEClient) ValidateWithPayload(url string, payload []byte) error {
  236. resp, err := c.post(payload, url, withKid(c))
  237. if err != nil {
  238. return err
  239. }
  240. defer resp.Body.Close()
  241. if resp.StatusCode >= 400 {
  242. return readACMEError(resp.Body)
  243. }
  244. return nil
  245. }
  246. // GetAuthz returns the Authz at the given path.
  247. func (c *ACMEClient) GetAuthz(url string) (*acme.Authorization, error) {
  248. resp, err := c.post(nil, url, withKid(c))
  249. if err != nil {
  250. return nil, err
  251. }
  252. defer resp.Body.Close()
  253. if resp.StatusCode >= 400 {
  254. return nil, readACMEError(resp.Body)
  255. }
  256. var az acme.Authorization
  257. if err := readJSON(resp.Body, &az); err != nil {
  258. return nil, errors.Wrapf(err, "error reading %s", url)
  259. }
  260. return &az, nil
  261. }
  262. // GetOrder returns the Order at the given path.
  263. func (c *ACMEClient) GetOrder(url string) (*acme.Order, error) {
  264. resp, err := c.post(nil, url, withKid(c))
  265. if err != nil {
  266. return nil, err
  267. }
  268. defer resp.Body.Close()
  269. if resp.StatusCode >= 400 {
  270. return nil, readACMEError(resp.Body)
  271. }
  272. var o acme.Order
  273. if err := readJSON(resp.Body, &o); err != nil {
  274. return nil, errors.Wrapf(err, "error reading %s", url)
  275. }
  276. return &o, nil
  277. }
  278. // FinalizeOrder makes a finalize request to the ACME api.
  279. func (c *ACMEClient) FinalizeOrder(url string, csr *x509.CertificateRequest) error {
  280. payload, err := json.Marshal(acmeAPI.FinalizeRequest{
  281. CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
  282. })
  283. if err != nil {
  284. return errors.Wrap(err, "error marshaling finalize request")
  285. }
  286. resp, err := c.post(payload, url, withKid(c))
  287. if err != nil {
  288. return err
  289. }
  290. defer resp.Body.Close()
  291. if resp.StatusCode >= 400 {
  292. return readACMEError(resp.Body)
  293. }
  294. return nil
  295. }
  296. // GetCertificate retrieves the certificate along with all intermediates.
  297. func (c *ACMEClient) GetCertificate(url string) (*x509.Certificate, []*x509.Certificate, error) {
  298. resp, err := c.post(nil, url, withKid(c))
  299. if err != nil {
  300. return nil, nil, err
  301. }
  302. defer resp.Body.Close()
  303. if resp.StatusCode >= 400 {
  304. return nil, nil, readACMEError(resp.Body)
  305. }
  306. defer resp.Body.Close()
  307. bodyBytes, err := io.ReadAll(resp.Body)
  308. if err != nil {
  309. return nil, nil, errors.Wrap(err, "error reading GET certificate response")
  310. }
  311. var certs []*x509.Certificate
  312. block, rest := pem.Decode(bodyBytes)
  313. if block == nil {
  314. return nil, nil, errors.New("failed to parse any certificates from response")
  315. }
  316. for block != nil {
  317. cert, err := x509.ParseCertificate(block.Bytes)
  318. if err != nil {
  319. return nil, nil, errors.Wrap(err, "error parsing certificate pem response")
  320. }
  321. certs = append(certs, cert)
  322. block, rest = pem.Decode(rest)
  323. }
  324. return certs[0], certs[1:], nil
  325. }
  326. // GetAccountOrders retrieves the orders belonging to the given account.
  327. func (c *ACMEClient) GetAccountOrders() ([]string, error) {
  328. if c.acc == nil {
  329. return nil, errors.New("acme client not configured with account")
  330. }
  331. resp, err := c.post(nil, c.acc.OrdersURL, withKid(c))
  332. if err != nil {
  333. return nil, err
  334. }
  335. defer resp.Body.Close()
  336. if resp.StatusCode >= 400 {
  337. return nil, readACMEError(resp.Body)
  338. }
  339. var orders []string
  340. if err := readJSON(resp.Body, &orders); err != nil {
  341. return nil, errors.Wrapf(err, "error reading %s", c.acc.OrdersURL)
  342. }
  343. return orders, nil
  344. }
  345. func readACMEError(r io.ReadCloser) error {
  346. defer r.Close()
  347. b, err := io.ReadAll(r)
  348. if err != nil {
  349. return errors.Wrap(err, "error reading from body")
  350. }
  351. ae := new(acme.Error)
  352. err = json.Unmarshal(b, &ae)
  353. // If we successfully marshaled to an ACMEError then return the ACMEError.
  354. if err != nil || ae.Error() == "" {
  355. fmt.Printf("b = %s\n", b)
  356. // Throw up our hands.
  357. return errors.Errorf("%s", b)
  358. }
  359. return ae
  360. }