client.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. package ca
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "crypto/tls"
  10. "crypto/x509"
  11. "crypto/x509/pkix"
  12. "encoding/hex"
  13. "encoding/json"
  14. "io"
  15. "io/ioutil"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "github.com/pkg/errors"
  23. "github.com/smallstep/certificates/api"
  24. "github.com/smallstep/certificates/authority"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. "github.com/smallstep/cli/config"
  27. "github.com/smallstep/cli/crypto/x509util"
  28. "gopkg.in/square/go-jose.v2/jwt"
  29. )
  30. // ClientOption is the type of options passed to the Client constructor.
  31. type ClientOption func(o *clientOptions) error
  32. type clientOptions struct {
  33. transport http.RoundTripper
  34. rootSHA256 string
  35. rootFilename string
  36. rootBundle []byte
  37. }
  38. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  39. for _, fn := range opts {
  40. if err = fn(o); err != nil {
  41. return
  42. }
  43. }
  44. return
  45. }
  46. // checkTransport checks if other ways to set up a transport have been provided.
  47. // If they have it returns an error.
  48. func (o *clientOptions) checkTransport() error {
  49. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  50. return errors.New("multiple transport methods have been configured")
  51. }
  52. return nil
  53. }
  54. // getTransport returns the transport configured in the clientOptions.
  55. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  56. if o.transport != nil {
  57. tr = o.transport
  58. }
  59. if o.rootFilename != "" {
  60. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  61. return nil, err
  62. }
  63. }
  64. if o.rootSHA256 != "" {
  65. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  66. return nil, err
  67. }
  68. }
  69. if o.rootBundle != nil {
  70. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  71. return nil, err
  72. }
  73. }
  74. // As the last option attempt to load the default root ca
  75. if tr == nil {
  76. rootFile := getRootCAPath()
  77. if _, err := os.Stat(rootFile); err == nil {
  78. if tr, err = getTransportFromFile(rootFile); err != nil {
  79. return nil, err
  80. }
  81. return tr, nil
  82. }
  83. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  84. }
  85. return tr, nil
  86. }
  87. // WithTransport adds a custom transport to the Client. It will fail if a
  88. // previous option to create the transport has been configured.
  89. func WithTransport(tr http.RoundTripper) ClientOption {
  90. return func(o *clientOptions) error {
  91. if err := o.checkTransport(); err != nil {
  92. return err
  93. }
  94. o.transport = tr
  95. return nil
  96. }
  97. }
  98. // WithRootFile will create the transport using the given root certificate. It
  99. // will fail if a previous option to create the transport has been configured.
  100. func WithRootFile(filename string) ClientOption {
  101. return func(o *clientOptions) error {
  102. if err := o.checkTransport(); err != nil {
  103. return err
  104. }
  105. o.rootFilename = filename
  106. return nil
  107. }
  108. }
  109. // WithRootSHA256 will create the transport using an insecure client to retrieve
  110. // the root certificate using its fingerprint. It will fail if a previous option
  111. // to create the transport has been configured.
  112. func WithRootSHA256(sum string) ClientOption {
  113. return func(o *clientOptions) error {
  114. if err := o.checkTransport(); err != nil {
  115. return err
  116. }
  117. o.rootSHA256 = sum
  118. return nil
  119. }
  120. }
  121. // WithCABundle will create the transport using the given root certificates. It
  122. // will fail if a previous option to create the transport has been configured.
  123. func WithCABundle(bundle []byte) ClientOption {
  124. return func(o *clientOptions) error {
  125. if err := o.checkTransport(); err != nil {
  126. return err
  127. }
  128. o.rootBundle = bundle
  129. return nil
  130. }
  131. }
  132. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  133. data, err := ioutil.ReadFile(filename)
  134. if err != nil {
  135. return nil, errors.Wrapf(err, "error reading %s", filename)
  136. }
  137. pool := x509.NewCertPool()
  138. if !pool.AppendCertsFromPEM(data) {
  139. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  140. }
  141. return getDefaultTransport(&tls.Config{
  142. MinVersion: tls.VersionTLS12,
  143. PreferServerCipherSuites: true,
  144. RootCAs: pool,
  145. })
  146. }
  147. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  148. u, err := parseEndpoint(endpoint)
  149. if err != nil {
  150. return nil, err
  151. }
  152. client := &Client{endpoint: u}
  153. root, err := client.Root(sum)
  154. if err != nil {
  155. return nil, err
  156. }
  157. pool := x509.NewCertPool()
  158. pool.AddCert(root.RootPEM.Certificate)
  159. return getDefaultTransport(&tls.Config{
  160. MinVersion: tls.VersionTLS12,
  161. PreferServerCipherSuites: true,
  162. RootCAs: pool,
  163. })
  164. }
  165. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  166. pool := x509.NewCertPool()
  167. if !pool.AppendCertsFromPEM(bundle) {
  168. return nil, errors.New("error parsing ca bundle: no certificates found")
  169. }
  170. return getDefaultTransport(&tls.Config{
  171. MinVersion: tls.VersionTLS12,
  172. PreferServerCipherSuites: true,
  173. RootCAs: pool,
  174. })
  175. }
  176. // parseEndpoint parses and validates the given endpoint. It supports general
  177. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  178. // ca.smallstep.com[:port][/path].
  179. func parseEndpoint(endpoint string) (*url.URL, error) {
  180. u, err := url.Parse(endpoint)
  181. if err != nil {
  182. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  183. }
  184. // URLs are generally parsed as:
  185. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  186. // But URLs that do not start with a slash after the scheme are interpreted as
  187. // scheme:opaque[?query][#fragment]
  188. if u.Opaque == "" {
  189. if u.Scheme == "" {
  190. u.Scheme = "https"
  191. }
  192. if u.Host == "" {
  193. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  194. if u.Path != "" {
  195. parts := strings.SplitN(u.Path, "/", 2)
  196. u.Host = parts[0]
  197. if len(parts) == 2 {
  198. u.Path = parts[1]
  199. } else {
  200. u.Path = ""
  201. }
  202. return parseEndpoint(u.String())
  203. }
  204. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  205. }
  206. return u, nil
  207. }
  208. // scheme:opaque[?query][#fragment]
  209. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  210. return parseEndpoint("https://" + endpoint)
  211. }
  212. // ProvisionerOption is the type of options passed to the Provisioner method.
  213. type ProvisionerOption func(o *provisionerOptions) error
  214. type provisionerOptions struct {
  215. cursor string
  216. limit int
  217. }
  218. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  219. for _, fn := range opts {
  220. if err = fn(o); err != nil {
  221. return
  222. }
  223. }
  224. return
  225. }
  226. func (o *provisionerOptions) rawQuery() string {
  227. v := url.Values{}
  228. if len(o.cursor) > 0 {
  229. v.Set("cursor", o.cursor)
  230. }
  231. if o.limit > 0 {
  232. v.Set("limit", strconv.Itoa(o.limit))
  233. }
  234. return v.Encode()
  235. }
  236. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  237. func WithProvisionerCursor(cursor string) ProvisionerOption {
  238. return func(o *provisionerOptions) error {
  239. o.cursor = cursor
  240. return nil
  241. }
  242. }
  243. // WithProvisionerLimit will request the given number of provisioners.
  244. func WithProvisionerLimit(limit int) ProvisionerOption {
  245. return func(o *provisionerOptions) error {
  246. o.limit = limit
  247. return nil
  248. }
  249. }
  250. // Client implements an HTTP client for the CA server.
  251. type Client struct {
  252. client *http.Client
  253. endpoint *url.URL
  254. }
  255. // NewClient creates a new Client with the given endpoint and options.
  256. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  257. u, err := parseEndpoint(endpoint)
  258. if err != nil {
  259. return nil, err
  260. }
  261. // Retrieve transport from options.
  262. o := new(clientOptions)
  263. if err := o.apply(opts); err != nil {
  264. return nil, err
  265. }
  266. tr, err := o.getTransport(endpoint)
  267. if err != nil {
  268. return nil, err
  269. }
  270. return &Client{
  271. client: &http.Client{
  272. Transport: tr,
  273. },
  274. endpoint: u,
  275. }, nil
  276. }
  277. // SetTransport updates the transport of the internal HTTP client.
  278. func (c *Client) SetTransport(tr http.RoundTripper) {
  279. c.client.Transport = tr
  280. }
  281. // Health performs the health request to the CA and returns the
  282. // api.HealthResponse struct.
  283. func (c *Client) Health() (*api.HealthResponse, error) {
  284. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  285. resp, err := c.client.Get(u.String())
  286. if err != nil {
  287. return nil, errors.Wrapf(err, "client GET %s failed", u)
  288. }
  289. if resp.StatusCode >= 400 {
  290. return nil, readError(resp.Body)
  291. }
  292. var health api.HealthResponse
  293. if err := readJSON(resp.Body, &health); err != nil {
  294. return nil, errors.Wrapf(err, "error reading %s", u)
  295. }
  296. return &health, nil
  297. }
  298. // Root performs the root request to the CA with the given SHA256 and returns
  299. // the api.RootResponse struct. It uses an insecure client, but it checks the
  300. // resulting root certificate with the given SHA256, returning an error if they
  301. // do not match.
  302. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  303. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  304. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  305. resp, err := getInsecureClient().Get(u.String())
  306. if err != nil {
  307. return nil, errors.Wrapf(err, "client GET %s failed", u)
  308. }
  309. if resp.StatusCode >= 400 {
  310. return nil, readError(resp.Body)
  311. }
  312. var root api.RootResponse
  313. if err := readJSON(resp.Body, &root); err != nil {
  314. return nil, errors.Wrapf(err, "error reading %s", u)
  315. }
  316. // verify the sha256
  317. sum := sha256.Sum256(root.RootPEM.Raw)
  318. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  319. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  320. }
  321. return &root, nil
  322. }
  323. // Sign performs the sign request to the CA and returns the api.SignResponse
  324. // struct.
  325. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  326. body, err := json.Marshal(req)
  327. if err != nil {
  328. return nil, errors.Wrap(err, "error marshaling request")
  329. }
  330. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  331. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  332. if err != nil {
  333. return nil, errors.Wrapf(err, "client POST %s failed", u)
  334. }
  335. if resp.StatusCode >= 400 {
  336. return nil, readError(resp.Body)
  337. }
  338. var sign api.SignResponse
  339. if err := readJSON(resp.Body, &sign); err != nil {
  340. return nil, errors.Wrapf(err, "error reading %s", u)
  341. }
  342. // Add tls.ConnectionState:
  343. // We'll extract the root certificate from the verified chains
  344. sign.TLS = resp.TLS
  345. return &sign, nil
  346. }
  347. // Renew performs the renew request to the CA and returns the api.SignResponse
  348. // struct.
  349. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  350. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  351. client := &http.Client{Transport: tr}
  352. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  353. if err != nil {
  354. return nil, errors.Wrapf(err, "client POST %s failed", u)
  355. }
  356. if resp.StatusCode >= 400 {
  357. return nil, readError(resp.Body)
  358. }
  359. var sign api.SignResponse
  360. if err := readJSON(resp.Body, &sign); err != nil {
  361. return nil, errors.Wrapf(err, "error reading %s", u)
  362. }
  363. return &sign, nil
  364. }
  365. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  366. // struct.
  367. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  368. body, err := json.Marshal(req)
  369. if err != nil {
  370. return nil, errors.Wrap(err, "error marshaling request")
  371. }
  372. var client *http.Client
  373. if tr != nil {
  374. client = &http.Client{Transport: tr}
  375. } else {
  376. client = c.client
  377. }
  378. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  379. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  380. if err != nil {
  381. return nil, errors.Wrapf(err, "client POST %s failed", u)
  382. }
  383. if resp.StatusCode >= 400 {
  384. return nil, readError(resp.Body)
  385. }
  386. var revoke api.RevokeResponse
  387. if err := readJSON(resp.Body, &revoke); err != nil {
  388. return nil, errors.Wrapf(err, "error reading %s", u)
  389. }
  390. return &revoke, nil
  391. }
  392. // Provisioners performs the provisioners request to the CA and returns the
  393. // api.ProvisionersResponse struct with a map of provisioners.
  394. //
  395. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  396. // paginate the provisioners.
  397. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  398. o := new(provisionerOptions)
  399. if err := o.apply(opts); err != nil {
  400. return nil, err
  401. }
  402. u := c.endpoint.ResolveReference(&url.URL{
  403. Path: "/provisioners",
  404. RawQuery: o.rawQuery(),
  405. })
  406. resp, err := c.client.Get(u.String())
  407. if err != nil {
  408. return nil, errors.Wrapf(err, "client GET %s failed", u)
  409. }
  410. if resp.StatusCode >= 400 {
  411. return nil, readError(resp.Body)
  412. }
  413. var provisioners api.ProvisionersResponse
  414. if err := readJSON(resp.Body, &provisioners); err != nil {
  415. return nil, errors.Wrapf(err, "error reading %s", u)
  416. }
  417. return &provisioners, nil
  418. }
  419. // ProvisionerKey performs the request to the CA to get the encrypted key for
  420. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  421. // with the encrypted key.
  422. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  423. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  424. resp, err := c.client.Get(u.String())
  425. if err != nil {
  426. return nil, errors.Wrapf(err, "client GET %s failed", u)
  427. }
  428. if resp.StatusCode >= 400 {
  429. return nil, readError(resp.Body)
  430. }
  431. var key api.ProvisionerKeyResponse
  432. if err := readJSON(resp.Body, &key); err != nil {
  433. return nil, errors.Wrapf(err, "error reading %s", u)
  434. }
  435. return &key, nil
  436. }
  437. // Roots performs the get roots request to the CA and returns the
  438. // api.RootsResponse struct.
  439. func (c *Client) Roots() (*api.RootsResponse, error) {
  440. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  441. resp, err := c.client.Get(u.String())
  442. if err != nil {
  443. return nil, errors.Wrapf(err, "client GET %s failed", u)
  444. }
  445. if resp.StatusCode >= 400 {
  446. return nil, readError(resp.Body)
  447. }
  448. var roots api.RootsResponse
  449. if err := readJSON(resp.Body, &roots); err != nil {
  450. return nil, errors.Wrapf(err, "error reading %s", u)
  451. }
  452. return &roots, nil
  453. }
  454. // Federation performs the get federation request to the CA and returns the
  455. // api.FederationResponse struct.
  456. func (c *Client) Federation() (*api.FederationResponse, error) {
  457. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  458. resp, err := c.client.Get(u.String())
  459. if err != nil {
  460. return nil, errors.Wrapf(err, "client GET %s failed", u)
  461. }
  462. if resp.StatusCode >= 400 {
  463. return nil, readError(resp.Body)
  464. }
  465. var federation api.FederationResponse
  466. if err := readJSON(resp.Body, &federation); err != nil {
  467. return nil, errors.Wrapf(err, "error reading %s", u)
  468. }
  469. return &federation, nil
  470. }
  471. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  472. // api.SSHSignResponse struct.
  473. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  474. body, err := json.Marshal(req)
  475. if err != nil {
  476. return nil, errors.Wrap(err, "error marshaling request")
  477. }
  478. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  479. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  480. if err != nil {
  481. return nil, errors.Wrapf(err, "client POST %s failed", u)
  482. }
  483. if resp.StatusCode >= 400 {
  484. return nil, readError(resp.Body)
  485. }
  486. var sign api.SSHSignResponse
  487. if err := readJSON(resp.Body, &sign); err != nil {
  488. return nil, errors.Wrapf(err, "error reading %s", u)
  489. }
  490. return &sign, nil
  491. }
  492. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  493. // api.SSHRenewResponse struct.
  494. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  495. body, err := json.Marshal(req)
  496. if err != nil {
  497. return nil, errors.Wrap(err, "error marshaling request")
  498. }
  499. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  500. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  501. if err != nil {
  502. return nil, errors.Wrapf(err, "client POST %s failed", u)
  503. }
  504. if resp.StatusCode >= 400 {
  505. return nil, readError(resp.Body)
  506. }
  507. var renew api.SSHRenewResponse
  508. if err := readJSON(resp.Body, &renew); err != nil {
  509. return nil, errors.Wrapf(err, "error reading %s", u)
  510. }
  511. return &renew, nil
  512. }
  513. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  514. // api.SSHRekeyResponse struct.
  515. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  516. body, err := json.Marshal(req)
  517. if err != nil {
  518. return nil, errors.Wrap(err, "error marshaling request")
  519. }
  520. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  521. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  522. if err != nil {
  523. return nil, errors.Wrapf(err, "client POST %s failed", u)
  524. }
  525. if resp.StatusCode >= 400 {
  526. return nil, readError(resp.Body)
  527. }
  528. var rekey api.SSHRekeyResponse
  529. if err := readJSON(resp.Body, &rekey); err != nil {
  530. return nil, errors.Wrapf(err, "error reading %s", u)
  531. }
  532. return &rekey, nil
  533. }
  534. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  535. // api.SSHRevokeResponse struct.
  536. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  537. body, err := json.Marshal(req)
  538. if err != nil {
  539. return nil, errors.Wrap(err, "error marshaling request")
  540. }
  541. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  542. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  543. if err != nil {
  544. return nil, errors.Wrapf(err, "client POST %s failed", u)
  545. }
  546. if resp.StatusCode >= 400 {
  547. return nil, readError(resp.Body)
  548. }
  549. var revoke api.SSHRevokeResponse
  550. if err := readJSON(resp.Body, &revoke); err != nil {
  551. return nil, errors.Wrapf(err, "error reading %s", u)
  552. }
  553. return &revoke, nil
  554. }
  555. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  556. // api.SSHRootsResponse struct.
  557. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  558. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  559. resp, err := c.client.Get(u.String())
  560. if err != nil {
  561. return nil, errors.Wrapf(err, "client GET %s failed", u)
  562. }
  563. if resp.StatusCode >= 400 {
  564. return nil, readError(resp.Body)
  565. }
  566. var keys api.SSHRootsResponse
  567. if err := readJSON(resp.Body, &keys); err != nil {
  568. return nil, errors.Wrapf(err, "error reading %s", u)
  569. }
  570. return &keys, nil
  571. }
  572. // SSHFederation performs the get /ssh/federation request to the CA and returns
  573. // the api.SSHRootsResponse struct.
  574. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  575. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  576. resp, err := c.client.Get(u.String())
  577. if err != nil {
  578. return nil, errors.Wrapf(err, "client GET %s failed", u)
  579. }
  580. if resp.StatusCode >= 400 {
  581. return nil, readError(resp.Body)
  582. }
  583. var keys api.SSHRootsResponse
  584. if err := readJSON(resp.Body, &keys); err != nil {
  585. return nil, errors.Wrapf(err, "error reading %s", u)
  586. }
  587. return &keys, nil
  588. }
  589. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  590. // configuration templates.
  591. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  592. body, err := json.Marshal(req)
  593. if err != nil {
  594. return nil, errors.Wrap(err, "error marshaling request")
  595. }
  596. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  597. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  598. if err != nil {
  599. return nil, errors.Wrapf(err, "client POST %s failed", u)
  600. }
  601. if resp.StatusCode >= 400 {
  602. return nil, readError(resp.Body)
  603. }
  604. var config api.SSHConfigResponse
  605. if err := readJSON(resp.Body, &config); err != nil {
  606. return nil, errors.Wrapf(err, "error reading %s", u)
  607. }
  608. return &config, nil
  609. }
  610. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  611. // given principal.
  612. func (c *Client) SSHCheckHost(principal string) (*api.SSHCheckPrincipalResponse, error) {
  613. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  614. Type: provisioner.SSHHostCert,
  615. Principal: principal,
  616. })
  617. if err != nil {
  618. return nil, errors.Wrap(err, "error marshaling request")
  619. }
  620. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  621. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  622. if err != nil {
  623. return nil, errors.Wrapf(err, "client POST %s failed", u)
  624. }
  625. if resp.StatusCode >= 400 {
  626. return nil, readError(resp.Body)
  627. }
  628. var check api.SSHCheckPrincipalResponse
  629. if err := readJSON(resp.Body, &check); err != nil {
  630. return nil, errors.Wrapf(err, "error reading %s", u)
  631. }
  632. return &check, nil
  633. }
  634. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  635. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  636. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/get-hosts"})
  637. resp, err := c.client.Get(u.String())
  638. if err != nil {
  639. return nil, errors.Wrapf(err, "client GET %s failed", u)
  640. }
  641. if resp.StatusCode >= 400 {
  642. return nil, readError(resp.Body)
  643. }
  644. var hosts api.SSHGetHostsResponse
  645. if err := readJSON(resp.Body, &hosts); err != nil {
  646. return nil, errors.Wrapf(err, "error reading %s", u)
  647. }
  648. return &hosts, nil
  649. }
  650. // RootFingerprint is a helper method that returns the current root fingerprint.
  651. // It does an health connection and gets the fingerprint from the TLS verified
  652. // chains.
  653. func (c *Client) RootFingerprint() (string, error) {
  654. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  655. resp, err := c.client.Get(u.String())
  656. if err != nil {
  657. return "", errors.Wrapf(err, "client GET %s failed", u)
  658. }
  659. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  660. return "", errors.New("missing verified chains")
  661. }
  662. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  663. if len(lastChain) == 0 {
  664. return "", errors.New("missing verified chains")
  665. }
  666. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  667. }
  668. // CreateSignRequest is a helper function that given an x509 OTT returns a
  669. // simple but secure sign request as well as the private key used.
  670. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  671. token, err := jwt.ParseSigned(ott)
  672. if err != nil {
  673. return nil, nil, errors.Wrap(err, "error parsing ott")
  674. }
  675. var claims authority.Claims
  676. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  677. return nil, nil, errors.Wrap(err, "error parsing ott")
  678. }
  679. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  680. if err != nil {
  681. return nil, nil, errors.Wrap(err, "error generating key")
  682. }
  683. dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
  684. if claims.Email != "" {
  685. emails = append(emails, claims.Email)
  686. }
  687. template := &x509.CertificateRequest{
  688. Subject: pkix.Name{
  689. CommonName: claims.Subject,
  690. },
  691. SignatureAlgorithm: x509.ECDSAWithSHA256,
  692. DNSNames: dnsNames,
  693. IPAddresses: ips,
  694. EmailAddresses: emails,
  695. }
  696. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  697. if err != nil {
  698. return nil, nil, errors.Wrap(err, "error creating certificate request")
  699. }
  700. cr, err := x509.ParseCertificateRequest(csr)
  701. if err != nil {
  702. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  703. }
  704. if err := cr.CheckSignature(); err != nil {
  705. return nil, nil, errors.Wrap(err, "error signing certificate request")
  706. }
  707. return &api.SignRequest{
  708. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  709. OTT: ott,
  710. }, pk, nil
  711. }
  712. func getInsecureClient() *http.Client {
  713. return &http.Client{
  714. Transport: &http.Transport{
  715. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  716. },
  717. }
  718. }
  719. // getRootCAPath returns the path where the root CA is stored based on the
  720. // STEPPATH environment variable.
  721. func getRootCAPath() string {
  722. return filepath.Join(config.StepPath(), "certs", "root_ca.crt")
  723. }
  724. func readJSON(r io.ReadCloser, v interface{}) error {
  725. defer r.Close()
  726. return json.NewDecoder(r).Decode(v)
  727. }
  728. func readError(r io.ReadCloser) error {
  729. defer r.Close()
  730. apiErr := new(api.Error)
  731. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  732. return err
  733. }
  734. return apiErr
  735. }