acmeClient.go 10 KB

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