acmeClient.go 10.0 KB

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