acmeClient.go 9.1 KB

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