client.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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/keys"
  28. "github.com/smallstep/cli/crypto/x509util"
  29. "golang.org/x/net/http2"
  30. "gopkg.in/square/go-jose.v2/jwt"
  31. )
  32. // RetryFunc defines the method used to retry a request. If it returns true, the
  33. // request will be retried once.
  34. type RetryFunc func(code int) bool
  35. // ClientOption is the type of options passed to the Client constructor.
  36. type ClientOption func(o *clientOptions) error
  37. type clientOptions struct {
  38. transport http.RoundTripper
  39. rootSHA256 string
  40. rootFilename string
  41. rootBundle []byte
  42. certificate tls.Certificate
  43. retryFunc RetryFunc
  44. }
  45. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  46. if err = o.applyDefaultIdentity(); err != nil {
  47. return
  48. }
  49. for _, fn := range opts {
  50. if err = fn(o); err != nil {
  51. return
  52. }
  53. }
  54. return
  55. }
  56. // applyDefaultIdentity sets the options for the default identity if the
  57. // identity file is present. The identity is enabled by default.
  58. func (o *clientOptions) applyDefaultIdentity() error {
  59. b, err := ioutil.ReadFile(IdentityFile)
  60. if err != nil {
  61. return nil
  62. }
  63. var identity Identity
  64. if err := json.Unmarshal(b, &identity); err != nil {
  65. return errors.Wrapf(err, "error unmarshaling %s", IdentityFile)
  66. }
  67. if err := identity.Validate(); err != nil {
  68. return err
  69. }
  70. opts, err := identity.Options()
  71. if err != nil {
  72. return err
  73. }
  74. for _, fn := range opts {
  75. if err := fn(o); err != nil {
  76. return err
  77. }
  78. }
  79. return nil
  80. }
  81. // checkTransport checks if other ways to set up a transport have been provided.
  82. // If they have it returns an error.
  83. func (o *clientOptions) checkTransport() error {
  84. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  85. return errors.New("multiple transport methods have been configured")
  86. }
  87. return nil
  88. }
  89. // getTransport returns the transport configured in the clientOptions.
  90. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  91. if o.transport != nil {
  92. tr = o.transport
  93. }
  94. if o.rootFilename != "" {
  95. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  96. return nil, err
  97. }
  98. }
  99. if o.rootSHA256 != "" {
  100. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  101. return nil, err
  102. }
  103. }
  104. if o.rootBundle != nil {
  105. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  106. return nil, err
  107. }
  108. }
  109. // As the last option attempt to load the default root ca
  110. if tr == nil {
  111. rootFile := getRootCAPath()
  112. if _, err := os.Stat(rootFile); err == nil {
  113. if tr, err = getTransportFromFile(rootFile); err != nil {
  114. return nil, err
  115. }
  116. }
  117. if tr == nil {
  118. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  119. }
  120. }
  121. // Add client certificate if available
  122. if o.certificate.Certificate != nil {
  123. switch tr := tr.(type) {
  124. case *http.Transport:
  125. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  126. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  127. }
  128. case *http2.Transport:
  129. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  130. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  131. }
  132. default:
  133. return nil, errors.Errorf("unsupported transport type %T", tr)
  134. }
  135. }
  136. return tr, nil
  137. }
  138. // WithTransport adds a custom transport to the Client. It will fail if a
  139. // previous option to create the transport has been configured.
  140. func WithTransport(tr http.RoundTripper) ClientOption {
  141. return func(o *clientOptions) error {
  142. if err := o.checkTransport(); err != nil {
  143. return err
  144. }
  145. o.transport = tr
  146. return nil
  147. }
  148. }
  149. // WithRootFile will create the transport using the given root certificate. It
  150. // will fail if a previous option to create the transport has been configured.
  151. func WithRootFile(filename string) ClientOption {
  152. return func(o *clientOptions) error {
  153. if err := o.checkTransport(); err != nil {
  154. return err
  155. }
  156. o.rootFilename = filename
  157. return nil
  158. }
  159. }
  160. // WithRootSHA256 will create the transport using an insecure client to retrieve
  161. // the root certificate using its fingerprint. It will fail if a previous option
  162. // to create the transport has been configured.
  163. func WithRootSHA256(sum string) ClientOption {
  164. return func(o *clientOptions) error {
  165. if err := o.checkTransport(); err != nil {
  166. return err
  167. }
  168. o.rootSHA256 = sum
  169. return nil
  170. }
  171. }
  172. // WithCABundle will create the transport using the given root certificates. It
  173. // will fail if a previous option to create the transport has been configured.
  174. func WithCABundle(bundle []byte) ClientOption {
  175. return func(o *clientOptions) error {
  176. if err := o.checkTransport(); err != nil {
  177. return err
  178. }
  179. o.rootBundle = bundle
  180. return nil
  181. }
  182. }
  183. // WithCertificate will set the given certificate as the TLS client certificate
  184. // in the client.
  185. func WithCertificate(crt tls.Certificate) ClientOption {
  186. return func(o *clientOptions) error {
  187. o.certificate = crt
  188. return nil
  189. }
  190. }
  191. // WithRetryFunc defines a method used to retry a request.
  192. func WithRetryFunc(fn RetryFunc) ClientOption {
  193. return func(o *clientOptions) error {
  194. o.retryFunc = fn
  195. return nil
  196. }
  197. }
  198. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  199. data, err := ioutil.ReadFile(filename)
  200. if err != nil {
  201. return nil, errors.Wrapf(err, "error reading %s", filename)
  202. }
  203. pool := x509.NewCertPool()
  204. if !pool.AppendCertsFromPEM(data) {
  205. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  206. }
  207. return getDefaultTransport(&tls.Config{
  208. MinVersion: tls.VersionTLS12,
  209. PreferServerCipherSuites: true,
  210. RootCAs: pool,
  211. })
  212. }
  213. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  214. u, err := parseEndpoint(endpoint)
  215. if err != nil {
  216. return nil, err
  217. }
  218. client := &Client{endpoint: u}
  219. root, err := client.Root(sum)
  220. if err != nil {
  221. return nil, err
  222. }
  223. pool := x509.NewCertPool()
  224. pool.AddCert(root.RootPEM.Certificate)
  225. return getDefaultTransport(&tls.Config{
  226. MinVersion: tls.VersionTLS12,
  227. PreferServerCipherSuites: true,
  228. RootCAs: pool,
  229. })
  230. }
  231. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  232. pool := x509.NewCertPool()
  233. if !pool.AppendCertsFromPEM(bundle) {
  234. return nil, errors.New("error parsing ca bundle: no certificates found")
  235. }
  236. return getDefaultTransport(&tls.Config{
  237. MinVersion: tls.VersionTLS12,
  238. PreferServerCipherSuites: true,
  239. RootCAs: pool,
  240. })
  241. }
  242. // parseEndpoint parses and validates the given endpoint. It supports general
  243. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  244. // ca.smallstep.com[:port][/path].
  245. func parseEndpoint(endpoint string) (*url.URL, error) {
  246. u, err := url.Parse(endpoint)
  247. if err != nil {
  248. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  249. }
  250. // URLs are generally parsed as:
  251. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  252. // But URLs that do not start with a slash after the scheme are interpreted as
  253. // scheme:opaque[?query][#fragment]
  254. if u.Opaque == "" {
  255. if u.Scheme == "" {
  256. u.Scheme = "https"
  257. }
  258. if u.Host == "" {
  259. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  260. if u.Path != "" {
  261. parts := strings.SplitN(u.Path, "/", 2)
  262. u.Host = parts[0]
  263. if len(parts) == 2 {
  264. u.Path = parts[1]
  265. } else {
  266. u.Path = ""
  267. }
  268. return parseEndpoint(u.String())
  269. }
  270. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  271. }
  272. return u, nil
  273. }
  274. // scheme:opaque[?query][#fragment]
  275. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  276. return parseEndpoint("https://" + endpoint)
  277. }
  278. // ProvisionerOption is the type of options passed to the Provisioner method.
  279. type ProvisionerOption func(o *provisionerOptions) error
  280. type provisionerOptions struct {
  281. cursor string
  282. limit int
  283. }
  284. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  285. for _, fn := range opts {
  286. if err = fn(o); err != nil {
  287. return
  288. }
  289. }
  290. return
  291. }
  292. func (o *provisionerOptions) rawQuery() string {
  293. v := url.Values{}
  294. if len(o.cursor) > 0 {
  295. v.Set("cursor", o.cursor)
  296. }
  297. if o.limit > 0 {
  298. v.Set("limit", strconv.Itoa(o.limit))
  299. }
  300. return v.Encode()
  301. }
  302. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  303. func WithProvisionerCursor(cursor string) ProvisionerOption {
  304. return func(o *provisionerOptions) error {
  305. o.cursor = cursor
  306. return nil
  307. }
  308. }
  309. // WithProvisionerLimit will request the given number of provisioners.
  310. func WithProvisionerLimit(limit int) ProvisionerOption {
  311. return func(o *provisionerOptions) error {
  312. o.limit = limit
  313. return nil
  314. }
  315. }
  316. // Client implements an HTTP client for the CA server.
  317. type Client struct {
  318. client *http.Client
  319. endpoint *url.URL
  320. retryFunc RetryFunc
  321. opts []ClientOption
  322. }
  323. // NewClient creates a new Client with the given endpoint and options.
  324. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  325. u, err := parseEndpoint(endpoint)
  326. if err != nil {
  327. return nil, err
  328. }
  329. // Retrieve transport from options.
  330. o := new(clientOptions)
  331. if err := o.apply(opts); err != nil {
  332. return nil, err
  333. }
  334. tr, err := o.getTransport(endpoint)
  335. if err != nil {
  336. return nil, err
  337. }
  338. return &Client{
  339. client: &http.Client{
  340. Transport: tr,
  341. },
  342. endpoint: u,
  343. retryFunc: o.retryFunc,
  344. opts: opts,
  345. }, nil
  346. }
  347. func (c *Client) retryOnError(r *http.Response) bool {
  348. if c.retryFunc != nil {
  349. if c.retryFunc(r.StatusCode) {
  350. o := new(clientOptions)
  351. if err := o.apply(c.opts); err != nil {
  352. return false
  353. }
  354. tr, err := o.getTransport(c.endpoint.String())
  355. if err != nil {
  356. return false
  357. }
  358. r.Body.Close()
  359. c.client.Transport = tr
  360. return true
  361. }
  362. }
  363. return false
  364. }
  365. // GetRootCAs returns the RootCAs certificate pool from the configured
  366. // transport.
  367. func (c *Client) GetRootCAs() *x509.CertPool {
  368. switch t := c.client.Transport.(type) {
  369. case *http.Transport:
  370. if t.TLSClientConfig != nil {
  371. return t.TLSClientConfig.RootCAs
  372. }
  373. return nil
  374. case *http2.Transport:
  375. if t.TLSClientConfig != nil {
  376. return t.TLSClientConfig.RootCAs
  377. }
  378. return nil
  379. default:
  380. return nil
  381. }
  382. }
  383. // SetTransport updates the transport of the internal HTTP client.
  384. func (c *Client) SetTransport(tr http.RoundTripper) {
  385. c.client.Transport = tr
  386. }
  387. // Version performs the version request to the CA and returns the
  388. // api.VersionResponse struct.
  389. func (c *Client) Version() (*api.VersionResponse, error) {
  390. var retried bool
  391. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  392. retry:
  393. resp, err := c.client.Get(u.String())
  394. if err != nil {
  395. return nil, errors.Wrapf(err, "client GET %s failed", u)
  396. }
  397. if resp.StatusCode >= 400 {
  398. if !retried && c.retryOnError(resp) {
  399. retried = true
  400. goto retry
  401. }
  402. return nil, readError(resp.Body)
  403. }
  404. var version api.VersionResponse
  405. if err := readJSON(resp.Body, &version); err != nil {
  406. return nil, errors.Wrapf(err, "error reading %s", u)
  407. }
  408. return &version, nil
  409. }
  410. // Health performs the health request to the CA and returns the
  411. // api.HealthResponse struct.
  412. func (c *Client) Health() (*api.HealthResponse, error) {
  413. var retried bool
  414. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  415. retry:
  416. resp, err := c.client.Get(u.String())
  417. if err != nil {
  418. return nil, errors.Wrapf(err, "client GET %s failed", u)
  419. }
  420. if resp.StatusCode >= 400 {
  421. if !retried && c.retryOnError(resp) {
  422. retried = true
  423. goto retry
  424. }
  425. return nil, readError(resp.Body)
  426. }
  427. var health api.HealthResponse
  428. if err := readJSON(resp.Body, &health); err != nil {
  429. return nil, errors.Wrapf(err, "error reading %s", u)
  430. }
  431. return &health, nil
  432. }
  433. // Root performs the root request to the CA with the given SHA256 and returns
  434. // the api.RootResponse struct. It uses an insecure client, but it checks the
  435. // resulting root certificate with the given SHA256, returning an error if they
  436. // do not match.
  437. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  438. var retried bool
  439. sha256Sum = strings.ToLower(strings.Replace(sha256Sum, "-", "", -1))
  440. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  441. retry:
  442. resp, err := getInsecureClient().Get(u.String())
  443. if err != nil {
  444. return nil, errors.Wrapf(err, "client GET %s failed", u)
  445. }
  446. if resp.StatusCode >= 400 {
  447. if !retried && c.retryOnError(resp) {
  448. retried = true
  449. goto retry
  450. }
  451. return nil, readError(resp.Body)
  452. }
  453. var root api.RootResponse
  454. if err := readJSON(resp.Body, &root); err != nil {
  455. return nil, errors.Wrapf(err, "error reading %s", u)
  456. }
  457. // verify the sha256
  458. sum := sha256.Sum256(root.RootPEM.Raw)
  459. if sha256Sum != strings.ToLower(hex.EncodeToString(sum[:])) {
  460. return nil, errors.New("root certificate SHA256 fingerprint do not match")
  461. }
  462. return &root, nil
  463. }
  464. // Sign performs the sign request to the CA and returns the api.SignResponse
  465. // struct.
  466. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  467. var retried bool
  468. body, err := json.Marshal(req)
  469. if err != nil {
  470. return nil, errors.Wrap(err, "error marshaling request")
  471. }
  472. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  473. retry:
  474. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  475. if err != nil {
  476. return nil, errors.Wrapf(err, "client POST %s failed", u)
  477. }
  478. if resp.StatusCode >= 400 {
  479. if !retried && c.retryOnError(resp) {
  480. retried = true
  481. goto retry
  482. }
  483. return nil, readError(resp.Body)
  484. }
  485. var sign api.SignResponse
  486. if err := readJSON(resp.Body, &sign); err != nil {
  487. return nil, errors.Wrapf(err, "error reading %s", u)
  488. }
  489. // Add tls.ConnectionState:
  490. // We'll extract the root certificate from the verified chains
  491. sign.TLS = resp.TLS
  492. return &sign, nil
  493. }
  494. // Renew performs the renew request to the CA and returns the api.SignResponse
  495. // struct.
  496. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  497. var retried bool
  498. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  499. client := &http.Client{Transport: tr}
  500. retry:
  501. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  502. if err != nil {
  503. return nil, errors.Wrapf(err, "client POST %s failed", u)
  504. }
  505. if resp.StatusCode >= 400 {
  506. if !retried && c.retryOnError(resp) {
  507. retried = true
  508. goto retry
  509. }
  510. return nil, readError(resp.Body)
  511. }
  512. var sign api.SignResponse
  513. if err := readJSON(resp.Body, &sign); err != nil {
  514. return nil, errors.Wrapf(err, "error reading %s", u)
  515. }
  516. return &sign, nil
  517. }
  518. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  519. // struct.
  520. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  521. var retried bool
  522. body, err := json.Marshal(req)
  523. if err != nil {
  524. return nil, errors.Wrap(err, "error marshaling request")
  525. }
  526. var client *http.Client
  527. retry:
  528. if tr != nil {
  529. client = &http.Client{Transport: tr}
  530. } else {
  531. client = c.client
  532. }
  533. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  534. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  535. if err != nil {
  536. return nil, errors.Wrapf(err, "client POST %s failed", u)
  537. }
  538. if resp.StatusCode >= 400 {
  539. if !retried && c.retryOnError(resp) {
  540. retried = true
  541. goto retry
  542. }
  543. return nil, readError(resp.Body)
  544. }
  545. var revoke api.RevokeResponse
  546. if err := readJSON(resp.Body, &revoke); err != nil {
  547. return nil, errors.Wrapf(err, "error reading %s", u)
  548. }
  549. return &revoke, nil
  550. }
  551. // Provisioners performs the provisioners request to the CA and returns the
  552. // api.ProvisionersResponse struct with a map of provisioners.
  553. //
  554. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  555. // paginate the provisioners.
  556. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  557. var retried bool
  558. o := new(provisionerOptions)
  559. if err := o.apply(opts); err != nil {
  560. return nil, err
  561. }
  562. u := c.endpoint.ResolveReference(&url.URL{
  563. Path: "/provisioners",
  564. RawQuery: o.rawQuery(),
  565. })
  566. retry:
  567. resp, err := c.client.Get(u.String())
  568. if err != nil {
  569. return nil, errors.Wrapf(err, "client GET %s failed", u)
  570. }
  571. if resp.StatusCode >= 400 {
  572. if !retried && c.retryOnError(resp) {
  573. retried = true
  574. goto retry
  575. }
  576. return nil, readError(resp.Body)
  577. }
  578. var provisioners api.ProvisionersResponse
  579. if err := readJSON(resp.Body, &provisioners); err != nil {
  580. return nil, errors.Wrapf(err, "error reading %s", u)
  581. }
  582. return &provisioners, nil
  583. }
  584. // ProvisionerKey performs the request to the CA to get the encrypted key for
  585. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  586. // with the encrypted key.
  587. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  588. var retried bool
  589. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  590. retry:
  591. resp, err := c.client.Get(u.String())
  592. if err != nil {
  593. return nil, errors.Wrapf(err, "client GET %s failed", u)
  594. }
  595. if resp.StatusCode >= 400 {
  596. if !retried && c.retryOnError(resp) {
  597. retried = true
  598. goto retry
  599. }
  600. return nil, readError(resp.Body)
  601. }
  602. var key api.ProvisionerKeyResponse
  603. if err := readJSON(resp.Body, &key); err != nil {
  604. return nil, errors.Wrapf(err, "error reading %s", u)
  605. }
  606. return &key, nil
  607. }
  608. // Roots performs the get roots request to the CA and returns the
  609. // api.RootsResponse struct.
  610. func (c *Client) Roots() (*api.RootsResponse, error) {
  611. var retried bool
  612. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  613. retry:
  614. resp, err := c.client.Get(u.String())
  615. if err != nil {
  616. return nil, errors.Wrapf(err, "client GET %s failed", u)
  617. }
  618. if resp.StatusCode >= 400 {
  619. if !retried && c.retryOnError(resp) {
  620. retried = true
  621. goto retry
  622. }
  623. return nil, readError(resp.Body)
  624. }
  625. var roots api.RootsResponse
  626. if err := readJSON(resp.Body, &roots); err != nil {
  627. return nil, errors.Wrapf(err, "error reading %s", u)
  628. }
  629. return &roots, nil
  630. }
  631. // Federation performs the get federation request to the CA and returns the
  632. // api.FederationResponse struct.
  633. func (c *Client) Federation() (*api.FederationResponse, error) {
  634. var retried bool
  635. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  636. retry:
  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. if !retried && c.retryOnError(resp) {
  643. retried = true
  644. goto retry
  645. }
  646. return nil, readError(resp.Body)
  647. }
  648. var federation api.FederationResponse
  649. if err := readJSON(resp.Body, &federation); err != nil {
  650. return nil, errors.Wrapf(err, "error reading %s", u)
  651. }
  652. return &federation, nil
  653. }
  654. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  655. // api.SSHSignResponse struct.
  656. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  657. var retried bool
  658. body, err := json.Marshal(req)
  659. if err != nil {
  660. return nil, errors.Wrap(err, "error marshaling request")
  661. }
  662. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  663. retry:
  664. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  665. if err != nil {
  666. return nil, errors.Wrapf(err, "client POST %s failed", u)
  667. }
  668. if resp.StatusCode >= 400 {
  669. if !retried && c.retryOnError(resp) {
  670. retried = true
  671. goto retry
  672. }
  673. return nil, readError(resp.Body)
  674. }
  675. var sign api.SSHSignResponse
  676. if err := readJSON(resp.Body, &sign); err != nil {
  677. return nil, errors.Wrapf(err, "error reading %s", u)
  678. }
  679. return &sign, nil
  680. }
  681. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  682. // api.SSHRenewResponse struct.
  683. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  684. var retried bool
  685. body, err := json.Marshal(req)
  686. if err != nil {
  687. return nil, errors.Wrap(err, "error marshaling request")
  688. }
  689. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  690. retry:
  691. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  692. if err != nil {
  693. return nil, errors.Wrapf(err, "client POST %s failed", u)
  694. }
  695. if resp.StatusCode >= 400 {
  696. if !retried && c.retryOnError(resp) {
  697. retried = true
  698. goto retry
  699. }
  700. return nil, readError(resp.Body)
  701. }
  702. var renew api.SSHRenewResponse
  703. if err := readJSON(resp.Body, &renew); err != nil {
  704. return nil, errors.Wrapf(err, "error reading %s", u)
  705. }
  706. return &renew, nil
  707. }
  708. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  709. // api.SSHRekeyResponse struct.
  710. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  711. var retried bool
  712. body, err := json.Marshal(req)
  713. if err != nil {
  714. return nil, errors.Wrap(err, "error marshaling request")
  715. }
  716. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  717. retry:
  718. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  719. if err != nil {
  720. return nil, errors.Wrapf(err, "client POST %s failed", u)
  721. }
  722. if resp.StatusCode >= 400 {
  723. if !retried && c.retryOnError(resp) {
  724. retried = true
  725. goto retry
  726. }
  727. return nil, readError(resp.Body)
  728. }
  729. var rekey api.SSHRekeyResponse
  730. if err := readJSON(resp.Body, &rekey); err != nil {
  731. return nil, errors.Wrapf(err, "error reading %s", u)
  732. }
  733. return &rekey, nil
  734. }
  735. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  736. // api.SSHRevokeResponse struct.
  737. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  738. var retried bool
  739. body, err := json.Marshal(req)
  740. if err != nil {
  741. return nil, errors.Wrap(err, "error marshaling request")
  742. }
  743. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  744. retry:
  745. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  746. if err != nil {
  747. return nil, errors.Wrapf(err, "client POST %s failed", u)
  748. }
  749. if resp.StatusCode >= 400 {
  750. if !retried && c.retryOnError(resp) {
  751. retried = true
  752. goto retry
  753. }
  754. return nil, readError(resp.Body)
  755. }
  756. var revoke api.SSHRevokeResponse
  757. if err := readJSON(resp.Body, &revoke); err != nil {
  758. return nil, errors.Wrapf(err, "error reading %s", u)
  759. }
  760. return &revoke, nil
  761. }
  762. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  763. // api.SSHRootsResponse struct.
  764. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  765. var retried bool
  766. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  767. retry:
  768. resp, err := c.client.Get(u.String())
  769. if err != nil {
  770. return nil, errors.Wrapf(err, "client GET %s failed", u)
  771. }
  772. if resp.StatusCode >= 400 {
  773. if !retried && c.retryOnError(resp) {
  774. retried = true
  775. goto retry
  776. }
  777. return nil, readError(resp.Body)
  778. }
  779. var keys api.SSHRootsResponse
  780. if err := readJSON(resp.Body, &keys); err != nil {
  781. return nil, errors.Wrapf(err, "error reading %s", u)
  782. }
  783. return &keys, nil
  784. }
  785. // SSHFederation performs the get /ssh/federation request to the CA and returns
  786. // the api.SSHRootsResponse struct.
  787. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  788. var retried bool
  789. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  790. retry:
  791. resp, err := c.client.Get(u.String())
  792. if err != nil {
  793. return nil, errors.Wrapf(err, "client GET %s failed", u)
  794. }
  795. if resp.StatusCode >= 400 {
  796. if !retried && c.retryOnError(resp) {
  797. retried = true
  798. goto retry
  799. }
  800. return nil, readError(resp.Body)
  801. }
  802. var keys api.SSHRootsResponse
  803. if err := readJSON(resp.Body, &keys); err != nil {
  804. return nil, errors.Wrapf(err, "error reading %s", u)
  805. }
  806. return &keys, nil
  807. }
  808. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  809. // configuration templates.
  810. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  811. var retried bool
  812. body, err := json.Marshal(req)
  813. if err != nil {
  814. return nil, errors.Wrap(err, "error marshaling request")
  815. }
  816. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  817. retry:
  818. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  819. if err != nil {
  820. return nil, errors.Wrapf(err, "client POST %s failed", u)
  821. }
  822. if resp.StatusCode >= 400 {
  823. if !retried && c.retryOnError(resp) {
  824. retried = true
  825. goto retry
  826. }
  827. return nil, readError(resp.Body)
  828. }
  829. var config api.SSHConfigResponse
  830. if err := readJSON(resp.Body, &config); err != nil {
  831. return nil, errors.Wrapf(err, "error reading %s", u)
  832. }
  833. return &config, nil
  834. }
  835. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  836. // given principal.
  837. func (c *Client) SSHCheckHost(principal string) (*api.SSHCheckPrincipalResponse, error) {
  838. var retried bool
  839. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  840. Type: provisioner.SSHHostCert,
  841. Principal: principal,
  842. })
  843. if err != nil {
  844. return nil, errors.Wrap(err, "error marshaling request")
  845. }
  846. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  847. retry:
  848. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  849. if err != nil {
  850. return nil, errors.Wrapf(err, "client POST %s failed", u)
  851. }
  852. if resp.StatusCode >= 400 {
  853. if !retried && c.retryOnError(resp) {
  854. retried = true
  855. goto retry
  856. }
  857. return nil, readError(resp.Body)
  858. }
  859. var check api.SSHCheckPrincipalResponse
  860. if err := readJSON(resp.Body, &check); err != nil {
  861. return nil, errors.Wrapf(err, "error reading %s", u)
  862. }
  863. return &check, nil
  864. }
  865. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  866. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  867. var retried bool
  868. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/get-hosts"})
  869. retry:
  870. resp, err := c.client.Get(u.String())
  871. if err != nil {
  872. return nil, errors.Wrapf(err, "client GET %s failed", u)
  873. }
  874. if resp.StatusCode >= 400 {
  875. if !retried && c.retryOnError(resp) {
  876. retried = true
  877. goto retry
  878. }
  879. return nil, readError(resp.Body)
  880. }
  881. var hosts api.SSHGetHostsResponse
  882. if err := readJSON(resp.Body, &hosts); err != nil {
  883. return nil, errors.Wrapf(err, "error reading %s", u)
  884. }
  885. return &hosts, nil
  886. }
  887. // SSHBastion performs the POST /ssh/bastion request to the CA.
  888. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  889. var retried bool
  890. body, err := json.Marshal(req)
  891. if err != nil {
  892. return nil, errors.Wrap(err, "error marshaling request")
  893. }
  894. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  895. retry:
  896. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  897. if err != nil {
  898. return nil, errors.Wrapf(err, "client POST %s failed", u)
  899. }
  900. if resp.StatusCode >= 400 {
  901. if !retried && c.retryOnError(resp) {
  902. retried = true
  903. goto retry
  904. }
  905. return nil, readError(resp.Body)
  906. }
  907. var bastion api.SSHBastionResponse
  908. if err := readJSON(resp.Body, &bastion); err != nil {
  909. return nil, errors.Wrapf(err, "error reading %s", u)
  910. }
  911. return &bastion, nil
  912. }
  913. // RootFingerprint is a helper method that returns the current root fingerprint.
  914. // It does an health connection and gets the fingerprint from the TLS verified
  915. // chains.
  916. func (c *Client) RootFingerprint() (string, error) {
  917. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  918. resp, err := c.client.Get(u.String())
  919. if err != nil {
  920. return "", errors.Wrapf(err, "client GET %s failed", u)
  921. }
  922. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  923. return "", errors.New("missing verified chains")
  924. }
  925. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  926. if len(lastChain) == 0 {
  927. return "", errors.New("missing verified chains")
  928. }
  929. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  930. }
  931. // CreateSignRequest is a helper function that given an x509 OTT returns a
  932. // simple but secure sign request as well as the private key used.
  933. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  934. token, err := jwt.ParseSigned(ott)
  935. if err != nil {
  936. return nil, nil, errors.Wrap(err, "error parsing ott")
  937. }
  938. var claims authority.Claims
  939. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  940. return nil, nil, errors.Wrap(err, "error parsing ott")
  941. }
  942. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  943. if err != nil {
  944. return nil, nil, errors.Wrap(err, "error generating key")
  945. }
  946. dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
  947. if claims.Email != "" {
  948. emails = append(emails, claims.Email)
  949. }
  950. template := &x509.CertificateRequest{
  951. Subject: pkix.Name{
  952. CommonName: claims.Subject,
  953. },
  954. SignatureAlgorithm: x509.ECDSAWithSHA256,
  955. DNSNames: dnsNames,
  956. IPAddresses: ips,
  957. EmailAddresses: emails,
  958. }
  959. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  960. if err != nil {
  961. return nil, nil, errors.Wrap(err, "error creating certificate request")
  962. }
  963. cr, err := x509.ParseCertificateRequest(csr)
  964. if err != nil {
  965. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  966. }
  967. if err := cr.CheckSignature(); err != nil {
  968. return nil, nil, errors.Wrap(err, "error signing certificate request")
  969. }
  970. return &api.SignRequest{
  971. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  972. OTT: ott,
  973. }, pk, nil
  974. }
  975. // CreateCertificateRequest creates a new CSR with the given common name and
  976. // SANs. If no san is provided the commonName will set also a SAN.
  977. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  978. key, err := keys.GenerateDefaultKey()
  979. if err != nil {
  980. return nil, nil, err
  981. }
  982. return createCertificateRequest(commonName, sans, key)
  983. }
  984. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  985. if len(sans) == 0 {
  986. sans = []string{commonName}
  987. }
  988. dnsNames, ips, emails := x509util.SplitSANs(sans)
  989. template := &x509.CertificateRequest{
  990. Subject: pkix.Name{
  991. CommonName: commonName,
  992. },
  993. DNSNames: dnsNames,
  994. IPAddresses: ips,
  995. EmailAddresses: emails,
  996. }
  997. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  998. if err != nil {
  999. return nil, nil, err
  1000. }
  1001. cr, err := x509.ParseCertificateRequest(csr)
  1002. if err != nil {
  1003. return nil, nil, err
  1004. }
  1005. if err := cr.CheckSignature(); err != nil {
  1006. return nil, nil, err
  1007. }
  1008. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1009. }
  1010. func getInsecureClient() *http.Client {
  1011. return &http.Client{
  1012. Transport: &http.Transport{
  1013. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  1014. },
  1015. }
  1016. }
  1017. // getRootCAPath returns the path where the root CA is stored based on the
  1018. // STEPPATH environment variable.
  1019. func getRootCAPath() string {
  1020. return filepath.Join(config.StepPath(), "certs", "root_ca.crt")
  1021. }
  1022. func readJSON(r io.ReadCloser, v interface{}) error {
  1023. defer r.Close()
  1024. return json.NewDecoder(r).Decode(v)
  1025. }
  1026. func readError(r io.ReadCloser) error {
  1027. defer r.Close()
  1028. apiErr := new(api.Error)
  1029. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1030. return err
  1031. }
  1032. return apiErr
  1033. }