4
0

client.go 38 KB

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