client.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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/asn1"
  13. "encoding/hex"
  14. "encoding/json"
  15. "encoding/pem"
  16. "io"
  17. "io/ioutil"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "github.com/pkg/errors"
  25. "github.com/smallstep/certificates/api"
  26. "github.com/smallstep/certificates/authority"
  27. "github.com/smallstep/certificates/authority/provisioner"
  28. "github.com/smallstep/certificates/ca/identity"
  29. "github.com/smallstep/certificates/errs"
  30. "go.step.sm/cli-utils/step"
  31. "go.step.sm/crypto/jose"
  32. "go.step.sm/crypto/keyutil"
  33. "go.step.sm/crypto/pemutil"
  34. "go.step.sm/crypto/x509util"
  35. "golang.org/x/net/http2"
  36. "google.golang.org/protobuf/encoding/protojson"
  37. "google.golang.org/protobuf/proto"
  38. "gopkg.in/square/go-jose.v2/jwt"
  39. )
  40. // DisableIdentity is a global variable to disable the identity.
  41. var DisableIdentity = false
  42. // UserAgent will set the User-Agent header in the client requests.
  43. var UserAgent = "step-http-client/1.0"
  44. type uaClient struct {
  45. Client *http.Client
  46. }
  47. func newClient(transport http.RoundTripper) *uaClient {
  48. return &uaClient{
  49. Client: &http.Client{
  50. Transport: transport,
  51. },
  52. }
  53. }
  54. func newInsecureClient() *uaClient {
  55. return &uaClient{
  56. Client: &http.Client{
  57. Transport: getDefaultTransport(&tls.Config{InsecureSkipVerify: true}),
  58. },
  59. }
  60. }
  61. func (c *uaClient) GetTransport() http.RoundTripper {
  62. return c.Client.Transport
  63. }
  64. func (c *uaClient) SetTransport(tr http.RoundTripper) {
  65. c.Client.Transport = tr
  66. }
  67. func (c *uaClient) Get(u string) (*http.Response, error) {
  68. req, err := http.NewRequest("GET", u, nil)
  69. if err != nil {
  70. return nil, errors.Wrapf(err, "new request GET %s failed", u)
  71. }
  72. req.Header.Set("User-Agent", UserAgent)
  73. return c.Client.Do(req)
  74. }
  75. func (c *uaClient) Post(u, contentType string, body io.Reader) (*http.Response, error) {
  76. req, err := http.NewRequest("POST", u, body)
  77. if err != nil {
  78. return nil, err
  79. }
  80. req.Header.Set("Content-Type", contentType)
  81. req.Header.Set("User-Agent", UserAgent)
  82. return c.Client.Do(req)
  83. }
  84. func (c *uaClient) Do(req *http.Request) (*http.Response, error) {
  85. req.Header.Set("User-Agent", UserAgent)
  86. return c.Client.Do(req)
  87. }
  88. // RetryFunc defines the method used to retry a request. If it returns true, the
  89. // request will be retried once.
  90. type RetryFunc func(code int) bool
  91. // ClientOption is the type of options passed to the Client constructor.
  92. type ClientOption func(o *clientOptions) error
  93. type clientOptions struct {
  94. transport http.RoundTripper
  95. rootSHA256 string
  96. rootFilename string
  97. rootBundle []byte
  98. certificate tls.Certificate
  99. getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
  100. retryFunc RetryFunc
  101. x5cJWK *jose.JSONWebKey
  102. x5cCertFile string
  103. x5cCertStrs []string
  104. x5cCert *x509.Certificate
  105. x5cIssuer string
  106. x5cSubject string
  107. }
  108. func (o *clientOptions) apply(opts []ClientOption) (err error) {
  109. if err = o.applyDefaultIdentity(); err != nil {
  110. return
  111. }
  112. for _, fn := range opts {
  113. if err = fn(o); err != nil {
  114. return
  115. }
  116. }
  117. return
  118. }
  119. // applyDefaultIdentity sets the options for the default identity if the
  120. // identity file is present. The identity is enabled by default.
  121. func (o *clientOptions) applyDefaultIdentity() error {
  122. if DisableIdentity {
  123. return nil
  124. }
  125. // Do not load an identity if something fails
  126. i, err := identity.LoadDefaultIdentity()
  127. if err != nil {
  128. return nil
  129. }
  130. if err := i.Validate(); err != nil {
  131. return nil
  132. }
  133. crt, err := i.TLSCertificate()
  134. if err != nil {
  135. return nil
  136. }
  137. o.certificate = crt
  138. o.getClientCertificate = i.GetClientCertificateFunc()
  139. return nil
  140. }
  141. // checkTransport checks if other ways to set up a transport have been provided.
  142. // If they have it returns an error.
  143. func (o *clientOptions) checkTransport() error {
  144. if o.transport != nil || o.rootFilename != "" || o.rootSHA256 != "" || o.rootBundle != nil {
  145. return errors.New("multiple transport methods have been configured")
  146. }
  147. return nil
  148. }
  149. // getTransport returns the transport configured in the clientOptions.
  150. func (o *clientOptions) getTransport(endpoint string) (tr http.RoundTripper, err error) {
  151. if o.transport != nil {
  152. tr = o.transport
  153. }
  154. if o.rootFilename != "" {
  155. if tr, err = getTransportFromFile(o.rootFilename); err != nil {
  156. return nil, err
  157. }
  158. }
  159. if o.rootSHA256 != "" {
  160. if tr, err = getTransportFromSHA256(endpoint, o.rootSHA256); err != nil {
  161. return nil, err
  162. }
  163. }
  164. if o.rootBundle != nil {
  165. if tr, err = getTransportFromCABundle(o.rootBundle); err != nil {
  166. return nil, err
  167. }
  168. }
  169. // As the last option attempt to load the default root ca
  170. if tr == nil {
  171. rootFile := getRootCAPath()
  172. if _, err := os.Stat(rootFile); err == nil {
  173. if tr, err = getTransportFromFile(rootFile); err != nil {
  174. return nil, err
  175. }
  176. }
  177. if tr == nil {
  178. return nil, errors.New("a transport, a root cert, or a root sha256 must be used")
  179. }
  180. }
  181. // Add client certificate if available
  182. if o.certificate.Certificate != nil {
  183. switch tr := tr.(type) {
  184. case *http.Transport:
  185. if tr.TLSClientConfig == nil {
  186. tr.TLSClientConfig = &tls.Config{}
  187. }
  188. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  189. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  190. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  191. }
  192. case *http2.Transport:
  193. if tr.TLSClientConfig == nil {
  194. tr.TLSClientConfig = &tls.Config{}
  195. }
  196. if len(tr.TLSClientConfig.Certificates) == 0 && tr.TLSClientConfig.GetClientCertificate == nil {
  197. tr.TLSClientConfig.Certificates = []tls.Certificate{o.certificate}
  198. tr.TLSClientConfig.GetClientCertificate = o.getClientCertificate
  199. }
  200. default:
  201. return nil, errors.Errorf("unsupported transport type %T", tr)
  202. }
  203. }
  204. return tr, nil
  205. }
  206. // WithTransport adds a custom transport to the Client. It will fail if a
  207. // previous option to create the transport has been configured.
  208. func WithTransport(tr http.RoundTripper) ClientOption {
  209. return func(o *clientOptions) error {
  210. if err := o.checkTransport(); err != nil {
  211. return err
  212. }
  213. o.transport = tr
  214. return nil
  215. }
  216. }
  217. // WithInsecure adds a insecure transport that bypasses TLS verification.
  218. func WithInsecure() ClientOption {
  219. return func(o *clientOptions) error {
  220. o.transport = &http.Transport{
  221. Proxy: http.ProxyFromEnvironment,
  222. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  223. }
  224. return nil
  225. }
  226. }
  227. // WithRootFile will create the transport using the given root certificate. It
  228. // will fail if a previous option to create the transport has been configured.
  229. func WithRootFile(filename string) ClientOption {
  230. return func(o *clientOptions) error {
  231. if err := o.checkTransport(); err != nil {
  232. return err
  233. }
  234. o.rootFilename = filename
  235. return nil
  236. }
  237. }
  238. // WithRootSHA256 will create the transport using an insecure client to retrieve
  239. // the root certificate using its fingerprint. It will fail if a previous option
  240. // to create the transport has been configured.
  241. func WithRootSHA256(sum string) ClientOption {
  242. return func(o *clientOptions) error {
  243. if err := o.checkTransport(); err != nil {
  244. return err
  245. }
  246. o.rootSHA256 = sum
  247. return nil
  248. }
  249. }
  250. // WithCABundle will create the transport using the given root certificates. It
  251. // will fail if a previous option to create the transport has been configured.
  252. func WithCABundle(bundle []byte) ClientOption {
  253. return func(o *clientOptions) error {
  254. if err := o.checkTransport(); err != nil {
  255. return err
  256. }
  257. o.rootBundle = bundle
  258. return nil
  259. }
  260. }
  261. // WithCertificate will set the given certificate as the TLS client certificate
  262. // in the client.
  263. func WithCertificate(cert tls.Certificate) ClientOption {
  264. return func(o *clientOptions) error {
  265. o.certificate = cert
  266. return nil
  267. }
  268. }
  269. var (
  270. stepOIDRoot = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
  271. stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
  272. )
  273. type stepProvisionerASN1 struct {
  274. Type int
  275. Name []byte
  276. CredentialID []byte
  277. KeyValuePairs []string `asn1:"optional,omitempty"`
  278. }
  279. // WithAdminX5C will set the given file as the X5C certificate for use
  280. // by the client.
  281. func WithAdminX5C(certs []*x509.Certificate, key interface{}, passwordFile string) ClientOption {
  282. return func(o *clientOptions) error {
  283. // Get private key from given key file
  284. var (
  285. err error
  286. opts []jose.Option
  287. )
  288. if passwordFile != "" {
  289. opts = append(opts, jose.WithPasswordFile(passwordFile))
  290. }
  291. blk, err := pemutil.Serialize(key)
  292. if err != nil {
  293. return errors.Wrap(err, "error serializing private key")
  294. }
  295. o.x5cJWK, err = jose.ParseKey(pem.EncodeToMemory(blk), opts...)
  296. if err != nil {
  297. return err
  298. }
  299. o.x5cCertStrs, err = jose.ValidateX5C(certs, o.x5cJWK.Key)
  300. if err != nil {
  301. return errors.Wrap(err, "error validating x5c certificate chain and key for use in x5c header")
  302. }
  303. o.x5cCert = certs[0]
  304. o.x5cSubject = o.x5cCert.Subject.CommonName
  305. for _, e := range o.x5cCert.Extensions {
  306. if e.Id.Equal(stepOIDProvisioner) {
  307. var prov stepProvisionerASN1
  308. if _, err := asn1.Unmarshal(e.Value, &prov); err != nil {
  309. return errors.Wrap(err, "error unmarshaling provisioner OID from certificate")
  310. }
  311. o.x5cIssuer = string(prov.Name)
  312. }
  313. }
  314. if o.x5cIssuer == "" {
  315. return errors.New("provisioner extension not found in certificate")
  316. }
  317. return nil
  318. }
  319. }
  320. // WithRetryFunc defines a method used to retry a request.
  321. func WithRetryFunc(fn RetryFunc) ClientOption {
  322. return func(o *clientOptions) error {
  323. o.retryFunc = fn
  324. return nil
  325. }
  326. }
  327. func getTransportFromFile(filename string) (http.RoundTripper, error) {
  328. data, err := ioutil.ReadFile(filename)
  329. if err != nil {
  330. return nil, errors.Wrapf(err, "error reading %s", filename)
  331. }
  332. pool := x509.NewCertPool()
  333. if !pool.AppendCertsFromPEM(data) {
  334. return nil, errors.Errorf("error parsing %s: no certificates found", filename)
  335. }
  336. return getDefaultTransport(&tls.Config{
  337. MinVersion: tls.VersionTLS12,
  338. PreferServerCipherSuites: true,
  339. RootCAs: pool,
  340. }), nil
  341. }
  342. func getTransportFromSHA256(endpoint, sum string) (http.RoundTripper, error) {
  343. u, err := parseEndpoint(endpoint)
  344. if err != nil {
  345. return nil, err
  346. }
  347. client := &Client{endpoint: u}
  348. root, err := client.Root(sum)
  349. if err != nil {
  350. return nil, err
  351. }
  352. pool := x509.NewCertPool()
  353. pool.AddCert(root.RootPEM.Certificate)
  354. return getDefaultTransport(&tls.Config{
  355. MinVersion: tls.VersionTLS12,
  356. PreferServerCipherSuites: true,
  357. RootCAs: pool,
  358. }), nil
  359. }
  360. func getTransportFromCABundle(bundle []byte) (http.RoundTripper, error) {
  361. pool := x509.NewCertPool()
  362. if !pool.AppendCertsFromPEM(bundle) {
  363. return nil, errors.New("error parsing ca bundle: no certificates found")
  364. }
  365. return getDefaultTransport(&tls.Config{
  366. MinVersion: tls.VersionTLS12,
  367. PreferServerCipherSuites: true,
  368. RootCAs: pool,
  369. }), nil
  370. }
  371. // parseEndpoint parses and validates the given endpoint. It supports general
  372. // URLs like https://ca.smallstep.com[:port][/path], and incomplete URLs like
  373. // ca.smallstep.com[:port][/path].
  374. func parseEndpoint(endpoint string) (*url.URL, error) {
  375. u, err := url.Parse(endpoint)
  376. if err != nil {
  377. return nil, errors.Wrapf(err, "error parsing endpoint '%s'", endpoint)
  378. }
  379. // URLs are generally parsed as:
  380. // [scheme:][//[userinfo@]host][/]path[?query][#fragment]
  381. // But URLs that do not start with a slash after the scheme are interpreted as
  382. // scheme:opaque[?query][#fragment]
  383. if u.Opaque == "" {
  384. if u.Scheme == "" {
  385. u.Scheme = "https"
  386. }
  387. if u.Host == "" {
  388. // endpoint looks like ca.smallstep.com or ca.smallstep.com/1.0/sign
  389. if u.Path != "" {
  390. parts := strings.SplitN(u.Path, "/", 2)
  391. u.Host = parts[0]
  392. if len(parts) == 2 {
  393. u.Path = parts[1]
  394. } else {
  395. u.Path = ""
  396. }
  397. return parseEndpoint(u.String())
  398. }
  399. return nil, errors.Errorf("error parsing endpoint: url '%s' is not valid", endpoint)
  400. }
  401. return u, nil
  402. }
  403. // scheme:opaque[?query][#fragment]
  404. // endpoint looks like ca.smallstep.com:443 or ca.smallstep.com:443/1.0/sign
  405. return parseEndpoint("https://" + endpoint)
  406. }
  407. // ProvisionerOption is the type of options passed to the Provisioner method.
  408. type ProvisionerOption func(o *provisionerOptions) error
  409. type provisionerOptions struct {
  410. cursor string
  411. limit int
  412. id string
  413. name string
  414. }
  415. func (o *provisionerOptions) apply(opts []ProvisionerOption) (err error) {
  416. for _, fn := range opts {
  417. if err = fn(o); err != nil {
  418. return
  419. }
  420. }
  421. return
  422. }
  423. func (o *provisionerOptions) rawQuery() string {
  424. v := url.Values{}
  425. if len(o.cursor) > 0 {
  426. v.Set("cursor", o.cursor)
  427. }
  428. if o.limit > 0 {
  429. v.Set("limit", strconv.Itoa(o.limit))
  430. }
  431. if len(o.id) > 0 {
  432. v.Set("id", o.id)
  433. }
  434. if len(o.name) > 0 {
  435. v.Set("name", o.name)
  436. }
  437. return v.Encode()
  438. }
  439. // WithProvisionerCursor will request the provisioners starting with the given cursor.
  440. func WithProvisionerCursor(cursor string) ProvisionerOption {
  441. return func(o *provisionerOptions) error {
  442. o.cursor = cursor
  443. return nil
  444. }
  445. }
  446. // WithProvisionerLimit will request the given number of provisioners.
  447. func WithProvisionerLimit(limit int) ProvisionerOption {
  448. return func(o *provisionerOptions) error {
  449. o.limit = limit
  450. return nil
  451. }
  452. }
  453. // WithProvisionerID will request the given provisioner.
  454. func WithProvisionerID(id string) ProvisionerOption {
  455. return func(o *provisionerOptions) error {
  456. o.id = id
  457. return nil
  458. }
  459. }
  460. // WithProvisionerName will request the given provisioner.
  461. func WithProvisionerName(name string) ProvisionerOption {
  462. return func(o *provisionerOptions) error {
  463. o.name = name
  464. return nil
  465. }
  466. }
  467. // Client implements an HTTP client for the CA server.
  468. type Client struct {
  469. client *uaClient
  470. endpoint *url.URL
  471. retryFunc RetryFunc
  472. opts []ClientOption
  473. }
  474. // NewClient creates a new Client with the given endpoint and options.
  475. func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
  476. u, err := parseEndpoint(endpoint)
  477. if err != nil {
  478. return nil, err
  479. }
  480. // Retrieve transport from options.
  481. o := new(clientOptions)
  482. if err := o.apply(opts); err != nil {
  483. return nil, err
  484. }
  485. tr, err := o.getTransport(endpoint)
  486. if err != nil {
  487. return nil, err
  488. }
  489. return &Client{
  490. client: newClient(tr),
  491. endpoint: u,
  492. retryFunc: o.retryFunc,
  493. opts: opts,
  494. }, nil
  495. }
  496. func (c *Client) retryOnError(r *http.Response) bool {
  497. if c.retryFunc != nil {
  498. if c.retryFunc(r.StatusCode) {
  499. o := new(clientOptions)
  500. if err := o.apply(c.opts); err != nil {
  501. return false
  502. }
  503. tr, err := o.getTransport(c.endpoint.String())
  504. if err != nil {
  505. return false
  506. }
  507. r.Body.Close()
  508. c.client.SetTransport(tr)
  509. return true
  510. }
  511. }
  512. return false
  513. }
  514. // GetRootCAs returns the RootCAs certificate pool from the configured
  515. // transport.
  516. func (c *Client) GetRootCAs() *x509.CertPool {
  517. switch t := c.client.GetTransport().(type) {
  518. case *http.Transport:
  519. if t.TLSClientConfig != nil {
  520. return t.TLSClientConfig.RootCAs
  521. }
  522. return nil
  523. case *http2.Transport:
  524. if t.TLSClientConfig != nil {
  525. return t.TLSClientConfig.RootCAs
  526. }
  527. return nil
  528. default:
  529. return nil
  530. }
  531. }
  532. // SetTransport updates the transport of the internal HTTP client.
  533. func (c *Client) SetTransport(tr http.RoundTripper) {
  534. c.client.SetTransport(tr)
  535. }
  536. // Version performs the version request to the CA and returns the
  537. // api.VersionResponse struct.
  538. func (c *Client) Version() (*api.VersionResponse, error) {
  539. var retried bool
  540. u := c.endpoint.ResolveReference(&url.URL{Path: "/version"})
  541. retry:
  542. resp, err := c.client.Get(u.String())
  543. if err != nil {
  544. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; client GET %s failed", u)
  545. }
  546. if resp.StatusCode >= 400 {
  547. if !retried && c.retryOnError(resp) {
  548. retried = true
  549. goto retry
  550. }
  551. return nil, readError(resp.Body)
  552. }
  553. var version api.VersionResponse
  554. if err := readJSON(resp.Body, &version); err != nil {
  555. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Version; error reading %s", u)
  556. }
  557. return &version, nil
  558. }
  559. // Health performs the health request to the CA and returns the
  560. // api.HealthResponse struct.
  561. func (c *Client) Health() (*api.HealthResponse, error) {
  562. var retried bool
  563. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  564. retry:
  565. resp, err := c.client.Get(u.String())
  566. if err != nil {
  567. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; client GET %s failed", u)
  568. }
  569. if resp.StatusCode >= 400 {
  570. if !retried && c.retryOnError(resp) {
  571. retried = true
  572. goto retry
  573. }
  574. return nil, readError(resp.Body)
  575. }
  576. var health api.HealthResponse
  577. if err := readJSON(resp.Body, &health); err != nil {
  578. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Health; error reading %s", u)
  579. }
  580. return &health, nil
  581. }
  582. // Root performs the root request to the CA with the given SHA256 and returns
  583. // the api.RootResponse struct. It uses an insecure client, but it checks the
  584. // resulting root certificate with the given SHA256, returning an error if they
  585. // do not match.
  586. func (c *Client) Root(sha256Sum string) (*api.RootResponse, error) {
  587. var retried bool
  588. sha256Sum = strings.ToLower(strings.ReplaceAll(sha256Sum, "-", ""))
  589. u := c.endpoint.ResolveReference(&url.URL{Path: "/root/" + sha256Sum})
  590. retry:
  591. resp, err := newInsecureClient().Get(u.String())
  592. if err != nil {
  593. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; 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 root api.RootResponse
  603. if err := readJSON(resp.Body, &root); err != nil {
  604. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Root; error reading %s", u)
  605. }
  606. // verify the sha256
  607. sum := sha256.Sum256(root.RootPEM.Raw)
  608. if !strings.EqualFold(sha256Sum, strings.ToLower(hex.EncodeToString(sum[:]))) {
  609. return nil, errs.BadRequest("client.Root; root certificate SHA256 fingerprint do not match")
  610. }
  611. return &root, nil
  612. }
  613. // Sign performs the sign request to the CA and returns the api.SignResponse
  614. // struct.
  615. func (c *Client) Sign(req *api.SignRequest) (*api.SignResponse, error) {
  616. var retried bool
  617. body, err := json.Marshal(req)
  618. if err != nil {
  619. return nil, errs.Wrap(http.StatusInternalServerError, err, "client.Sign; error marshaling request")
  620. }
  621. u := c.endpoint.ResolveReference(&url.URL{Path: "/sign"})
  622. retry:
  623. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  624. if err != nil {
  625. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; client POST %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 sign api.SignResponse
  635. if err := readJSON(resp.Body, &sign); err != nil {
  636. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Sign; error reading %s", u)
  637. }
  638. // Add tls.ConnectionState:
  639. // We'll extract the root certificate from the verified chains
  640. sign.TLS = resp.TLS
  641. return &sign, nil
  642. }
  643. // Renew performs the renew request to the CA and returns the api.SignResponse
  644. // struct.
  645. func (c *Client) Renew(tr http.RoundTripper) (*api.SignResponse, error) {
  646. var retried bool
  647. u := c.endpoint.ResolveReference(&url.URL{Path: "/renew"})
  648. client := &http.Client{Transport: tr}
  649. retry:
  650. resp, err := client.Post(u.String(), "application/json", http.NoBody)
  651. if err != nil {
  652. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; client POST %s failed", u)
  653. }
  654. if resp.StatusCode >= 400 {
  655. if !retried && c.retryOnError(resp) {
  656. retried = true
  657. goto retry
  658. }
  659. return nil, readError(resp.Body)
  660. }
  661. var sign api.SignResponse
  662. if err := readJSON(resp.Body, &sign); err != nil {
  663. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Renew; error reading %s", u)
  664. }
  665. return &sign, nil
  666. }
  667. // Rekey performs the rekey request to the CA and returns the api.SignResponse
  668. // struct.
  669. func (c *Client) Rekey(req *api.RekeyRequest, tr http.RoundTripper) (*api.SignResponse, error) {
  670. var retried bool
  671. body, err := json.Marshal(req)
  672. if err != nil {
  673. return nil, errors.Wrap(err, "error marshaling request")
  674. }
  675. u := c.endpoint.ResolveReference(&url.URL{Path: "/rekey"})
  676. client := &http.Client{Transport: tr}
  677. retry:
  678. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  679. if err != nil {
  680. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; client POST %s failed", u)
  681. }
  682. if resp.StatusCode >= 400 {
  683. if !retried && c.retryOnError(resp) {
  684. retried = true
  685. goto retry
  686. }
  687. return nil, readError(resp.Body)
  688. }
  689. var sign api.SignResponse
  690. if err := readJSON(resp.Body, &sign); err != nil {
  691. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client.Rekey; error reading %s", u)
  692. }
  693. return &sign, nil
  694. }
  695. // Revoke performs the revoke request to the CA and returns the api.RevokeResponse
  696. // struct.
  697. func (c *Client) Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error) {
  698. var retried bool
  699. body, err := json.Marshal(req)
  700. if err != nil {
  701. return nil, errors.Wrap(err, "error marshaling request")
  702. }
  703. var client *uaClient
  704. retry:
  705. if tr != nil {
  706. client = newClient(tr)
  707. } else {
  708. client = c.client
  709. }
  710. u := c.endpoint.ResolveReference(&url.URL{Path: "/revoke"})
  711. resp, err := client.Post(u.String(), "application/json", bytes.NewReader(body))
  712. if err != nil {
  713. return nil, errors.Wrapf(err, "client POST %s failed", u)
  714. }
  715. if resp.StatusCode >= 400 {
  716. if !retried && c.retryOnError(resp) {
  717. retried = true
  718. goto retry
  719. }
  720. return nil, readError(resp.Body)
  721. }
  722. var revoke api.RevokeResponse
  723. if err := readJSON(resp.Body, &revoke); err != nil {
  724. return nil, errors.Wrapf(err, "error reading %s", u)
  725. }
  726. return &revoke, nil
  727. }
  728. // Provisioners performs the provisioners request to the CA and returns the
  729. // api.ProvisionersResponse struct with a map of provisioners.
  730. //
  731. // ProvisionerOption WithProvisionerCursor and WithProvisionLimit can be used to
  732. // paginate the provisioners.
  733. func (c *Client) Provisioners(opts ...ProvisionerOption) (*api.ProvisionersResponse, error) {
  734. var retried bool
  735. o := new(provisionerOptions)
  736. if err := o.apply(opts); err != nil {
  737. return nil, err
  738. }
  739. u := c.endpoint.ResolveReference(&url.URL{
  740. Path: "/provisioners",
  741. RawQuery: o.rawQuery(),
  742. })
  743. retry:
  744. resp, err := c.client.Get(u.String())
  745. if err != nil {
  746. return nil, errors.Wrapf(err, "client GET %s failed", u)
  747. }
  748. if resp.StatusCode >= 400 {
  749. if !retried && c.retryOnError(resp) {
  750. retried = true
  751. goto retry
  752. }
  753. return nil, readError(resp.Body)
  754. }
  755. var provisioners api.ProvisionersResponse
  756. if err := readJSON(resp.Body, &provisioners); err != nil {
  757. return nil, errors.Wrapf(err, "error reading %s", u)
  758. }
  759. return &provisioners, nil
  760. }
  761. // ProvisionerKey performs the request to the CA to get the encrypted key for
  762. // the given provisioner kid and returns the api.ProvisionerKeyResponse struct
  763. // with the encrypted key.
  764. func (c *Client) ProvisionerKey(kid string) (*api.ProvisionerKeyResponse, error) {
  765. var retried bool
  766. u := c.endpoint.ResolveReference(&url.URL{Path: "/provisioners/" + kid + "/encrypted-key"})
  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 key api.ProvisionerKeyResponse
  780. if err := readJSON(resp.Body, &key); err != nil {
  781. return nil, errors.Wrapf(err, "error reading %s", u)
  782. }
  783. return &key, nil
  784. }
  785. // Roots performs the get roots request to the CA and returns the
  786. // api.RootsResponse struct.
  787. func (c *Client) Roots() (*api.RootsResponse, error) {
  788. var retried bool
  789. u := c.endpoint.ResolveReference(&url.URL{Path: "/roots"})
  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 roots api.RootsResponse
  803. if err := readJSON(resp.Body, &roots); err != nil {
  804. return nil, errors.Wrapf(err, "error reading %s", u)
  805. }
  806. return &roots, nil
  807. }
  808. // Federation performs the get federation request to the CA and returns the
  809. // api.FederationResponse struct.
  810. func (c *Client) Federation() (*api.FederationResponse, error) {
  811. var retried bool
  812. u := c.endpoint.ResolveReference(&url.URL{Path: "/federation"})
  813. retry:
  814. resp, err := c.client.Get(u.String())
  815. if err != nil {
  816. return nil, errors.Wrapf(err, "client GET %s failed", u)
  817. }
  818. if resp.StatusCode >= 400 {
  819. if !retried && c.retryOnError(resp) {
  820. retried = true
  821. goto retry
  822. }
  823. return nil, readError(resp.Body)
  824. }
  825. var federation api.FederationResponse
  826. if err := readJSON(resp.Body, &federation); err != nil {
  827. return nil, errors.Wrapf(err, "error reading %s", u)
  828. }
  829. return &federation, nil
  830. }
  831. // SSHSign performs the POST /ssh/sign request to the CA and returns the
  832. // api.SSHSignResponse struct.
  833. func (c *Client) SSHSign(req *api.SSHSignRequest) (*api.SSHSignResponse, error) {
  834. var retried bool
  835. body, err := json.Marshal(req)
  836. if err != nil {
  837. return nil, errors.Wrap(err, "error marshaling request")
  838. }
  839. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/sign"})
  840. retry:
  841. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  842. if err != nil {
  843. return nil, errors.Wrapf(err, "client POST %s failed", u)
  844. }
  845. if resp.StatusCode >= 400 {
  846. if !retried && c.retryOnError(resp) {
  847. retried = true
  848. goto retry
  849. }
  850. return nil, readError(resp.Body)
  851. }
  852. var sign api.SSHSignResponse
  853. if err := readJSON(resp.Body, &sign); err != nil {
  854. return nil, errors.Wrapf(err, "error reading %s", u)
  855. }
  856. return &sign, nil
  857. }
  858. // SSHRenew performs the POST /ssh/renew request to the CA and returns the
  859. // api.SSHRenewResponse struct.
  860. func (c *Client) SSHRenew(req *api.SSHRenewRequest) (*api.SSHRenewResponse, error) {
  861. var retried bool
  862. body, err := json.Marshal(req)
  863. if err != nil {
  864. return nil, errors.Wrap(err, "error marshaling request")
  865. }
  866. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/renew"})
  867. retry:
  868. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  869. if err != nil {
  870. return nil, errors.Wrapf(err, "client POST %s failed", u)
  871. }
  872. if resp.StatusCode >= 400 {
  873. if !retried && c.retryOnError(resp) {
  874. retried = true
  875. goto retry
  876. }
  877. return nil, readError(resp.Body)
  878. }
  879. var renew api.SSHRenewResponse
  880. if err := readJSON(resp.Body, &renew); err != nil {
  881. return nil, errors.Wrapf(err, "error reading %s", u)
  882. }
  883. return &renew, nil
  884. }
  885. // SSHRekey performs the POST /ssh/rekey request to the CA and returns the
  886. // api.SSHRekeyResponse struct.
  887. func (c *Client) SSHRekey(req *api.SSHRekeyRequest) (*api.SSHRekeyResponse, error) {
  888. var retried bool
  889. body, err := json.Marshal(req)
  890. if err != nil {
  891. return nil, errors.Wrap(err, "error marshaling request")
  892. }
  893. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/rekey"})
  894. retry:
  895. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  896. if err != nil {
  897. return nil, errors.Wrapf(err, "client POST %s failed", u)
  898. }
  899. if resp.StatusCode >= 400 {
  900. if !retried && c.retryOnError(resp) {
  901. retried = true
  902. goto retry
  903. }
  904. return nil, readError(resp.Body)
  905. }
  906. var rekey api.SSHRekeyResponse
  907. if err := readJSON(resp.Body, &rekey); err != nil {
  908. return nil, errors.Wrapf(err, "error reading %s", u)
  909. }
  910. return &rekey, nil
  911. }
  912. // SSHRevoke performs the POST /ssh/revoke request to the CA and returns the
  913. // api.SSHRevokeResponse struct.
  914. func (c *Client) SSHRevoke(req *api.SSHRevokeRequest) (*api.SSHRevokeResponse, error) {
  915. var retried bool
  916. body, err := json.Marshal(req)
  917. if err != nil {
  918. return nil, errors.Wrap(err, "error marshaling request")
  919. }
  920. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/revoke"})
  921. retry:
  922. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  923. if err != nil {
  924. return nil, errors.Wrapf(err, "client POST %s failed", u)
  925. }
  926. if resp.StatusCode >= 400 {
  927. if !retried && c.retryOnError(resp) {
  928. retried = true
  929. goto retry
  930. }
  931. return nil, readError(resp.Body)
  932. }
  933. var revoke api.SSHRevokeResponse
  934. if err := readJSON(resp.Body, &revoke); err != nil {
  935. return nil, errors.Wrapf(err, "error reading %s", u)
  936. }
  937. return &revoke, nil
  938. }
  939. // SSHRoots performs the GET /ssh/roots request to the CA and returns the
  940. // api.SSHRootsResponse struct.
  941. func (c *Client) SSHRoots() (*api.SSHRootsResponse, error) {
  942. var retried bool
  943. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/roots"})
  944. retry:
  945. resp, err := c.client.Get(u.String())
  946. if err != nil {
  947. return nil, errors.Wrapf(err, "client GET %s failed", u)
  948. }
  949. if resp.StatusCode >= 400 {
  950. if !retried && c.retryOnError(resp) {
  951. retried = true
  952. goto retry
  953. }
  954. return nil, readError(resp.Body)
  955. }
  956. var keys api.SSHRootsResponse
  957. if err := readJSON(resp.Body, &keys); err != nil {
  958. return nil, errors.Wrapf(err, "error reading %s", u)
  959. }
  960. return &keys, nil
  961. }
  962. // SSHFederation performs the get /ssh/federation request to the CA and returns
  963. // the api.SSHRootsResponse struct.
  964. func (c *Client) SSHFederation() (*api.SSHRootsResponse, error) {
  965. var retried bool
  966. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/federation"})
  967. retry:
  968. resp, err := c.client.Get(u.String())
  969. if err != nil {
  970. return nil, errors.Wrapf(err, "client GET %s failed", u)
  971. }
  972. if resp.StatusCode >= 400 {
  973. if !retried && c.retryOnError(resp) {
  974. retried = true
  975. goto retry
  976. }
  977. return nil, readError(resp.Body)
  978. }
  979. var keys api.SSHRootsResponse
  980. if err := readJSON(resp.Body, &keys); err != nil {
  981. return nil, errors.Wrapf(err, "error reading %s", u)
  982. }
  983. return &keys, nil
  984. }
  985. // SSHConfig performs the POST /ssh/config request to the CA to get the ssh
  986. // configuration templates.
  987. func (c *Client) SSHConfig(req *api.SSHConfigRequest) (*api.SSHConfigResponse, error) {
  988. var retried bool
  989. body, err := json.Marshal(req)
  990. if err != nil {
  991. return nil, errors.Wrap(err, "error marshaling request")
  992. }
  993. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/config"})
  994. retry:
  995. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  996. if err != nil {
  997. return nil, errors.Wrapf(err, "client POST %s failed", u)
  998. }
  999. if resp.StatusCode >= 400 {
  1000. if !retried && c.retryOnError(resp) {
  1001. retried = true
  1002. goto retry
  1003. }
  1004. return nil, readError(resp.Body)
  1005. }
  1006. var cfg api.SSHConfigResponse
  1007. if err := readJSON(resp.Body, &cfg); err != nil {
  1008. return nil, errors.Wrapf(err, "error reading %s", u)
  1009. }
  1010. return &cfg, nil
  1011. }
  1012. // SSHCheckHost performs the POST /ssh/check-host request to the CA with the
  1013. // given principal.
  1014. func (c *Client) SSHCheckHost(principal, token string) (*api.SSHCheckPrincipalResponse, error) {
  1015. var retried bool
  1016. body, err := json.Marshal(&api.SSHCheckPrincipalRequest{
  1017. Type: provisioner.SSHHostCert,
  1018. Principal: principal,
  1019. Token: token,
  1020. })
  1021. if err != nil {
  1022. return nil, errs.Wrap(http.StatusInternalServerError, err, "error marshaling request",
  1023. errs.WithMessage("Failed to marshal the check-host request"))
  1024. }
  1025. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/check-host"})
  1026. retry:
  1027. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1028. if err != nil {
  1029. return nil, errs.Wrapf(http.StatusInternalServerError, err, "client POST %s failed",
  1030. []interface{}{u, errs.WithMessage("Failed to perform POST request to %s", u)}...)
  1031. }
  1032. if resp.StatusCode >= 400 {
  1033. if !retried && c.retryOnError(resp) {
  1034. retried = true
  1035. goto retry
  1036. }
  1037. return nil, errs.StatusCodeError(resp.StatusCode, readError(resp.Body))
  1038. }
  1039. var check api.SSHCheckPrincipalResponse
  1040. if err := readJSON(resp.Body, &check); err != nil {
  1041. return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response",
  1042. []interface{}{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")})
  1043. }
  1044. return &check, nil
  1045. }
  1046. // SSHGetHosts performs the GET /ssh/get-hosts request to the CA.
  1047. func (c *Client) SSHGetHosts() (*api.SSHGetHostsResponse, error) {
  1048. var retried bool
  1049. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/hosts"})
  1050. retry:
  1051. resp, err := c.client.Get(u.String())
  1052. if err != nil {
  1053. return nil, errors.Wrapf(err, "client GET %s failed", u)
  1054. }
  1055. if resp.StatusCode >= 400 {
  1056. if !retried && c.retryOnError(resp) {
  1057. retried = true
  1058. goto retry
  1059. }
  1060. return nil, readError(resp.Body)
  1061. }
  1062. var hosts api.SSHGetHostsResponse
  1063. if err := readJSON(resp.Body, &hosts); err != nil {
  1064. return nil, errors.Wrapf(err, "error reading %s", u)
  1065. }
  1066. return &hosts, nil
  1067. }
  1068. // SSHBastion performs the POST /ssh/bastion request to the CA.
  1069. func (c *Client) SSHBastion(req *api.SSHBastionRequest) (*api.SSHBastionResponse, error) {
  1070. var retried bool
  1071. body, err := json.Marshal(req)
  1072. if err != nil {
  1073. return nil, errors.Wrap(err, "client.SSHBastion; error marshaling request")
  1074. }
  1075. u := c.endpoint.ResolveReference(&url.URL{Path: "/ssh/bastion"})
  1076. retry:
  1077. resp, err := c.client.Post(u.String(), "application/json", bytes.NewReader(body))
  1078. if err != nil {
  1079. return nil, errors.Wrapf(err, "client.SSHBastion; client POST %s failed", u)
  1080. }
  1081. if resp.StatusCode >= 400 {
  1082. if !retried && c.retryOnError(resp) {
  1083. retried = true
  1084. goto retry
  1085. }
  1086. return nil, readError(resp.Body)
  1087. }
  1088. var bastion api.SSHBastionResponse
  1089. if err := readJSON(resp.Body, &bastion); err != nil {
  1090. return nil, errors.Wrapf(err, "client.SSHBastion; error reading %s", u)
  1091. }
  1092. return &bastion, nil
  1093. }
  1094. // RootFingerprint is a helper method that returns the current root fingerprint.
  1095. // It does an health connection and gets the fingerprint from the TLS verified
  1096. // chains.
  1097. func (c *Client) RootFingerprint() (string, error) {
  1098. u := c.endpoint.ResolveReference(&url.URL{Path: "/health"})
  1099. resp, err := c.client.Get(u.String())
  1100. if err != nil {
  1101. return "", errors.Wrapf(err, "client GET %s failed", u)
  1102. }
  1103. if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 {
  1104. return "", errors.New("missing verified chains")
  1105. }
  1106. lastChain := resp.TLS.VerifiedChains[len(resp.TLS.VerifiedChains)-1]
  1107. if len(lastChain) == 0 {
  1108. return "", errors.New("missing verified chains")
  1109. }
  1110. return x509util.Fingerprint(lastChain[len(lastChain)-1]), nil
  1111. }
  1112. // CreateSignRequest is a helper function that given an x509 OTT returns a
  1113. // simple but secure sign request as well as the private key used.
  1114. func CreateSignRequest(ott string) (*api.SignRequest, crypto.PrivateKey, error) {
  1115. token, err := jwt.ParseSigned(ott)
  1116. if err != nil {
  1117. return nil, nil, errors.Wrap(err, "error parsing ott")
  1118. }
  1119. var claims authority.Claims
  1120. if err := token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  1121. return nil, nil, errors.Wrap(err, "error parsing ott")
  1122. }
  1123. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1124. if err != nil {
  1125. return nil, nil, errors.Wrap(err, "error generating key")
  1126. }
  1127. dnsNames, ips, emails, uris := x509util.SplitSANs(claims.SANs)
  1128. if claims.Email != "" {
  1129. emails = append(emails, claims.Email)
  1130. }
  1131. template := &x509.CertificateRequest{
  1132. Subject: pkix.Name{
  1133. CommonName: claims.Subject,
  1134. },
  1135. SignatureAlgorithm: x509.ECDSAWithSHA256,
  1136. DNSNames: dnsNames,
  1137. IPAddresses: ips,
  1138. EmailAddresses: emails,
  1139. URIs: uris,
  1140. }
  1141. csr, err := x509.CreateCertificateRequest(rand.Reader, template, pk)
  1142. if err != nil {
  1143. return nil, nil, errors.Wrap(err, "error creating certificate request")
  1144. }
  1145. cr, err := x509.ParseCertificateRequest(csr)
  1146. if err != nil {
  1147. return nil, nil, errors.Wrap(err, "error parsing certificate request")
  1148. }
  1149. if err := cr.CheckSignature(); err != nil {
  1150. return nil, nil, errors.Wrap(err, "error signing certificate request")
  1151. }
  1152. return &api.SignRequest{
  1153. CsrPEM: api.CertificateRequest{CertificateRequest: cr},
  1154. OTT: ott,
  1155. }, pk, nil
  1156. }
  1157. // CreateCertificateRequest creates a new CSR with the given common name and
  1158. // SANs. If no san is provided the commonName will set also a SAN.
  1159. func CreateCertificateRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1160. key, err := keyutil.GenerateDefaultKey()
  1161. if err != nil {
  1162. return nil, nil, err
  1163. }
  1164. return createCertificateRequest(commonName, sans, key)
  1165. }
  1166. // CreateIdentityRequest returns a new CSR to create the identity. If an
  1167. // identity was already present it reuses the private key.
  1168. func CreateIdentityRequest(commonName string, sans ...string) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1169. var identityKey crypto.PrivateKey
  1170. if i, err := identity.LoadDefaultIdentity(); err == nil && i.Key != "" {
  1171. if k, err := pemutil.Read(i.Key); err == nil {
  1172. identityKey = k
  1173. }
  1174. }
  1175. if identityKey == nil {
  1176. return CreateCertificateRequest(commonName, sans...)
  1177. }
  1178. return createCertificateRequest(commonName, sans, identityKey)
  1179. }
  1180. // LoadDefaultIdentity is a wrapper for identity.LoadDefaultIdentity.
  1181. func LoadDefaultIdentity() (*identity.Identity, error) {
  1182. return identity.LoadDefaultIdentity()
  1183. }
  1184. // WriteDefaultIdentity is a wrapper for identity.WriteDefaultIdentity.
  1185. func WriteDefaultIdentity(certChain []api.Certificate, key crypto.PrivateKey) error {
  1186. return identity.WriteDefaultIdentity(certChain, key)
  1187. }
  1188. func createCertificateRequest(commonName string, sans []string, key crypto.PrivateKey) (*api.CertificateRequest, crypto.PrivateKey, error) {
  1189. if len(sans) == 0 {
  1190. sans = []string{commonName}
  1191. }
  1192. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  1193. template := &x509.CertificateRequest{
  1194. Subject: pkix.Name{
  1195. CommonName: commonName,
  1196. },
  1197. DNSNames: dnsNames,
  1198. IPAddresses: ips,
  1199. EmailAddresses: emails,
  1200. URIs: uris,
  1201. }
  1202. csr, err := x509.CreateCertificateRequest(rand.Reader, template, key)
  1203. if err != nil {
  1204. return nil, nil, err
  1205. }
  1206. cr, err := x509.ParseCertificateRequest(csr)
  1207. if err != nil {
  1208. return nil, nil, err
  1209. }
  1210. if err := cr.CheckSignature(); err != nil {
  1211. return nil, nil, err
  1212. }
  1213. return &api.CertificateRequest{CertificateRequest: cr}, key, nil
  1214. }
  1215. // getRootCAPath returns the path where the root CA is stored based on the
  1216. // STEPPATH environment variable.
  1217. func getRootCAPath() string {
  1218. return filepath.Join(step.Path(), "certs", "root_ca.crt")
  1219. }
  1220. func readJSON(r io.ReadCloser, v interface{}) error {
  1221. defer r.Close()
  1222. return json.NewDecoder(r).Decode(v)
  1223. }
  1224. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  1225. defer r.Close()
  1226. data, err := ioutil.ReadAll(r)
  1227. if err != nil {
  1228. return err
  1229. }
  1230. return protojson.Unmarshal(data, m)
  1231. }
  1232. func readError(r io.ReadCloser) error {
  1233. defer r.Close()
  1234. apiErr := new(errs.Error)
  1235. if err := json.NewDecoder(r).Decode(apiErr); err != nil {
  1236. return err
  1237. }
  1238. return apiErr
  1239. }