client.go 31 KB

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