acmeClient.go 9.1 KB

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