api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. package api
  2. import (
  3. "context"
  4. "crypto/dsa"
  5. "crypto/ecdsa"
  6. "crypto/rsa"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/asn1"
  10. "encoding/base64"
  11. "encoding/json"
  12. "encoding/pem"
  13. "fmt"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/go-chi/chi"
  19. "github.com/pkg/errors"
  20. "github.com/smallstep/certificates/authority"
  21. "github.com/smallstep/certificates/authority/provisioner"
  22. "github.com/smallstep/certificates/logging"
  23. "github.com/smallstep/cli/crypto/tlsutil"
  24. )
  25. // Authority is the interface implemented by a CA authority.
  26. type Authority interface {
  27. SSHAuthority
  28. // context specifies the Authorize[Sign|Revoke|etc.] method.
  29. Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  30. AuthorizeSign(ott string) ([]provisioner.SignOption, error)
  31. GetTLSOptions() *tlsutil.TLSOptions
  32. Root(shasum string) (*x509.Certificate, error)
  33. Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  34. Renew(peer *x509.Certificate) ([]*x509.Certificate, error)
  35. LoadProvisionerByCertificate(*x509.Certificate) (provisioner.Interface, error)
  36. LoadProvisionerByID(string) (provisioner.Interface, error)
  37. GetProvisioners(cursor string, limit int) (provisioner.List, string, error)
  38. Revoke(context.Context, *authority.RevokeOptions) error
  39. GetEncryptedKey(kid string) (string, error)
  40. GetRoots() (federation []*x509.Certificate, err error)
  41. GetFederation() ([]*x509.Certificate, error)
  42. Version() authority.Version
  43. }
  44. // TimeDuration is an alias of provisioner.TimeDuration
  45. type TimeDuration = provisioner.TimeDuration
  46. // NewTimeDuration returns a TimeDuration with the defined time.
  47. func NewTimeDuration(t time.Time) TimeDuration {
  48. return provisioner.NewTimeDuration(t)
  49. }
  50. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  51. // time.Duration string.
  52. func ParseTimeDuration(s string) (TimeDuration, error) {
  53. return provisioner.ParseTimeDuration(s)
  54. }
  55. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  56. type Certificate struct {
  57. *x509.Certificate
  58. }
  59. // NewCertificate is a helper method that returns a Certificate from a
  60. // *x509.Certificate.
  61. func NewCertificate(cr *x509.Certificate) Certificate {
  62. return Certificate{
  63. Certificate: cr,
  64. }
  65. }
  66. // reset sets the inner x509.CertificateRequest to nil
  67. func (c *Certificate) reset() {
  68. if c != nil {
  69. c.Certificate = nil
  70. }
  71. }
  72. // MarshalJSON implements the json.Marshaler interface. The certificate is
  73. // quoted string using the PEM encoding.
  74. func (c Certificate) MarshalJSON() ([]byte, error) {
  75. if c.Certificate == nil {
  76. return []byte("null"), nil
  77. }
  78. block := pem.EncodeToMemory(&pem.Block{
  79. Type: "CERTIFICATE",
  80. Bytes: c.Raw,
  81. })
  82. return json.Marshal(string(block))
  83. }
  84. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  85. // expected to be a quoted string using the PEM encoding.
  86. func (c *Certificate) UnmarshalJSON(data []byte) error {
  87. var s string
  88. if err := json.Unmarshal(data, &s); err != nil {
  89. return errors.Wrap(err, "error decoding certificate")
  90. }
  91. // Make sure the inner x509.Certificate is nil
  92. if s == "null" || s == "" {
  93. c.reset()
  94. return nil
  95. }
  96. block, _ := pem.Decode([]byte(s))
  97. if block == nil {
  98. return errors.New("error decoding certificate")
  99. }
  100. cert, err := x509.ParseCertificate(block.Bytes)
  101. if err != nil {
  102. return errors.Wrap(err, "error decoding certificate")
  103. }
  104. c.Certificate = cert
  105. return nil
  106. }
  107. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  108. // json.Unmarshaler interface.
  109. type CertificateRequest struct {
  110. *x509.CertificateRequest
  111. }
  112. // NewCertificateRequest is a helper method that returns a CertificateRequest
  113. // from a *x509.CertificateRequest.
  114. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  115. return CertificateRequest{
  116. CertificateRequest: cr,
  117. }
  118. }
  119. // reset sets the inner x509.CertificateRequest to nil
  120. func (c *CertificateRequest) reset() {
  121. if c != nil {
  122. c.CertificateRequest = nil
  123. }
  124. }
  125. // MarshalJSON implements the json.Marshaler interface. The certificate request
  126. // is a quoted string using the PEM encoding.
  127. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  128. if c.CertificateRequest == nil {
  129. return []byte("null"), nil
  130. }
  131. block := pem.EncodeToMemory(&pem.Block{
  132. Type: "CERTIFICATE REQUEST",
  133. Bytes: c.Raw,
  134. })
  135. return json.Marshal(string(block))
  136. }
  137. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  138. // request is expected to be a quoted string using the PEM encoding.
  139. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  140. var s string
  141. if err := json.Unmarshal(data, &s); err != nil {
  142. return errors.Wrap(err, "error decoding csr")
  143. }
  144. // Make sure the inner x509.CertificateRequest is nil
  145. if s == "null" || s == "" {
  146. c.reset()
  147. return nil
  148. }
  149. block, _ := pem.Decode([]byte(s))
  150. if block == nil {
  151. return errors.New("error decoding csr")
  152. }
  153. cr, err := x509.ParseCertificateRequest(block.Bytes)
  154. if err != nil {
  155. return errors.Wrap(err, "error decoding csr")
  156. }
  157. c.CertificateRequest = cr
  158. return nil
  159. }
  160. // Router defines a common router interface.
  161. type Router interface {
  162. // MethodFunc adds routes for `pattern` that matches
  163. // the `method` HTTP method.
  164. MethodFunc(method, pattern string, h http.HandlerFunc)
  165. }
  166. // RouterHandler is the interface that a HTTP handler that manages multiple
  167. // endpoints will implement.
  168. type RouterHandler interface {
  169. Route(r Router)
  170. }
  171. // VersionResponse is the response object that returns the version of the
  172. // server.
  173. type VersionResponse struct {
  174. Version string `json:"version"`
  175. RequireClientAuthentication bool `json:"requireClientAuthentication,omitempty"`
  176. }
  177. // HealthResponse is the response object that returns the health of the server.
  178. type HealthResponse struct {
  179. Status string `json:"status"`
  180. }
  181. // RootResponse is the response object that returns the PEM of a root certificate.
  182. type RootResponse struct {
  183. RootPEM Certificate `json:"ca"`
  184. }
  185. // SignRequest is the request body for a certificate signature request.
  186. type SignRequest struct {
  187. CsrPEM CertificateRequest `json:"csr"`
  188. OTT string `json:"ott"`
  189. NotAfter TimeDuration `json:"notAfter"`
  190. NotBefore TimeDuration `json:"notBefore"`
  191. }
  192. // ProvisionersResponse is the response object that returns the list of
  193. // provisioners.
  194. type ProvisionersResponse struct {
  195. Provisioners provisioner.List `json:"provisioners"`
  196. NextCursor string `json:"nextCursor"`
  197. }
  198. // ProvisionerKeyResponse is the response object that returns the encrypted key
  199. // of a provisioner.
  200. type ProvisionerKeyResponse struct {
  201. Key string `json:"key"`
  202. }
  203. // Validate checks the fields of the SignRequest and returns nil if they are ok
  204. // or an error if something is wrong.
  205. func (s *SignRequest) Validate() error {
  206. if s.CsrPEM.CertificateRequest == nil {
  207. return BadRequest(errors.New("missing csr"))
  208. }
  209. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  210. return BadRequest(errors.Wrap(err, "invalid csr"))
  211. }
  212. if s.OTT == "" {
  213. return BadRequest(errors.New("missing ott"))
  214. }
  215. return nil
  216. }
  217. // SignResponse is the response object of the certificate signature request.
  218. type SignResponse struct {
  219. ServerPEM Certificate `json:"crt"`
  220. CaPEM Certificate `json:"ca"`
  221. CertChainPEM []Certificate `json:"certChain"`
  222. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  223. TLS *tls.ConnectionState `json:"-"`
  224. }
  225. // RootsResponse is the response object of the roots request.
  226. type RootsResponse struct {
  227. Certificates []Certificate `json:"crts"`
  228. }
  229. // FederationResponse is the response object of the federation request.
  230. type FederationResponse struct {
  231. Certificates []Certificate `json:"crts"`
  232. }
  233. // caHandler is the type used to implement the different CA HTTP endpoints.
  234. type caHandler struct {
  235. Authority Authority
  236. }
  237. // New creates a new RouterHandler with the CA endpoints.
  238. func New(authority Authority) RouterHandler {
  239. return &caHandler{
  240. Authority: authority,
  241. }
  242. }
  243. func (h *caHandler) Route(r Router) {
  244. r.MethodFunc("GET", "/version", h.Version)
  245. r.MethodFunc("GET", "/health", h.Health)
  246. r.MethodFunc("GET", "/root/{sha}", h.Root)
  247. r.MethodFunc("POST", "/sign", h.Sign)
  248. r.MethodFunc("POST", "/renew", h.Renew)
  249. r.MethodFunc("POST", "/revoke", h.Revoke)
  250. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  251. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  252. r.MethodFunc("GET", "/roots", h.Roots)
  253. r.MethodFunc("GET", "/federation", h.Federation)
  254. // SSH CA
  255. r.MethodFunc("POST", "/ssh/sign", h.SSHSign)
  256. r.MethodFunc("POST", "/ssh/renew", h.SSHRenew)
  257. r.MethodFunc("POST", "/ssh/revoke", h.SSHRevoke)
  258. r.MethodFunc("POST", "/ssh/rekey", h.SSHRekey)
  259. r.MethodFunc("GET", "/ssh/roots", h.SSHRoots)
  260. r.MethodFunc("GET", "/ssh/federation", h.SSHFederation)
  261. r.MethodFunc("POST", "/ssh/config", h.SSHConfig)
  262. r.MethodFunc("POST", "/ssh/config/{type}", h.SSHConfig)
  263. r.MethodFunc("POST", "/ssh/check-host", h.SSHCheckHost)
  264. r.MethodFunc("GET", "/ssh/get-hosts", h.SSHGetHosts)
  265. r.MethodFunc("POST", "/ssh/bastion", h.SSHBastion)
  266. // For compatibility with old code:
  267. r.MethodFunc("POST", "/re-sign", h.Renew)
  268. r.MethodFunc("POST", "/sign-ssh", h.SSHSign)
  269. }
  270. // Version is an HTTP handler that returns the version of the server.
  271. func (h *caHandler) Version(w http.ResponseWriter, r *http.Request) {
  272. v := h.Authority.Version()
  273. JSON(w, VersionResponse{
  274. Version: v.Version,
  275. RequireClientAuthentication: v.RequireClientAuthentication,
  276. })
  277. }
  278. // Health is an HTTP handler that returns the status of the server.
  279. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  280. JSON(w, HealthResponse{Status: "ok"})
  281. }
  282. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  283. // certificate for the given SHA256.
  284. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  285. sha := chi.URLParam(r, "sha")
  286. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  287. // Load root certificate with the
  288. cert, err := h.Authority.Root(sum)
  289. if err != nil {
  290. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  291. return
  292. }
  293. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  294. }
  295. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  296. certChainPEM := make([]Certificate, 0, len(certChain))
  297. for _, c := range certChain {
  298. certChainPEM = append(certChainPEM, Certificate{c})
  299. }
  300. return certChainPEM
  301. }
  302. // Sign is an HTTP handler that reads a certificate request and an
  303. // one-time-token (ott) from the body and creates a new certificate with the
  304. // information in the certificate request.
  305. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  306. var body SignRequest
  307. if err := ReadJSON(r.Body, &body); err != nil {
  308. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  309. return
  310. }
  311. logOtt(w, body.OTT)
  312. if err := body.Validate(); err != nil {
  313. WriteError(w, err)
  314. return
  315. }
  316. opts := provisioner.Options{
  317. NotBefore: body.NotBefore,
  318. NotAfter: body.NotAfter,
  319. }
  320. signOpts, err := h.Authority.AuthorizeSign(body.OTT)
  321. if err != nil {
  322. WriteError(w, Unauthorized(err))
  323. return
  324. }
  325. certChain, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
  326. if err != nil {
  327. WriteError(w, Forbidden(err))
  328. return
  329. }
  330. certChainPEM := certChainToPEM(certChain)
  331. var caPEM Certificate
  332. if len(certChainPEM) > 0 {
  333. caPEM = certChainPEM[1]
  334. }
  335. logCertificate(w, certChain[0])
  336. JSONStatus(w, &SignResponse{
  337. ServerPEM: certChainPEM[0],
  338. CaPEM: caPEM,
  339. CertChainPEM: certChainPEM,
  340. TLSOptions: h.Authority.GetTLSOptions(),
  341. }, http.StatusCreated)
  342. }
  343. // Renew uses the information of certificate in the TLS connection to create a
  344. // new one.
  345. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  346. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  347. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  348. return
  349. }
  350. certChain, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  351. if err != nil {
  352. WriteError(w, Forbidden(err))
  353. return
  354. }
  355. certChainPEM := certChainToPEM(certChain)
  356. var caPEM Certificate
  357. if len(certChainPEM) > 0 {
  358. caPEM = certChainPEM[1]
  359. }
  360. logCertificate(w, certChain[0])
  361. JSONStatus(w, &SignResponse{
  362. ServerPEM: certChainPEM[0],
  363. CaPEM: caPEM,
  364. CertChainPEM: certChainPEM,
  365. TLSOptions: h.Authority.GetTLSOptions(),
  366. }, http.StatusCreated)
  367. }
  368. // Provisioners returns the list of provisioners configured in the authority.
  369. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  370. cursor, limit, err := parseCursor(r)
  371. if err != nil {
  372. WriteError(w, BadRequest(err))
  373. return
  374. }
  375. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  376. if err != nil {
  377. WriteError(w, InternalServerError(err))
  378. return
  379. }
  380. JSON(w, &ProvisionersResponse{
  381. Provisioners: p,
  382. NextCursor: next,
  383. })
  384. }
  385. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  386. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  387. kid := chi.URLParam(r, "kid")
  388. key, err := h.Authority.GetEncryptedKey(kid)
  389. if err != nil {
  390. WriteError(w, NotFound(err))
  391. return
  392. }
  393. JSON(w, &ProvisionerKeyResponse{key})
  394. }
  395. // Roots returns all the root certificates for the CA.
  396. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  397. roots, err := h.Authority.GetRoots()
  398. if err != nil {
  399. WriteError(w, Forbidden(err))
  400. return
  401. }
  402. certs := make([]Certificate, len(roots))
  403. for i := range roots {
  404. certs[i] = Certificate{roots[i]}
  405. }
  406. JSONStatus(w, &RootsResponse{
  407. Certificates: certs,
  408. }, http.StatusCreated)
  409. }
  410. // Federation returns all the public certificates in the federation.
  411. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  412. federated, err := h.Authority.GetFederation()
  413. if err != nil {
  414. WriteError(w, Forbidden(err))
  415. return
  416. }
  417. certs := make([]Certificate, len(federated))
  418. for i := range federated {
  419. certs[i] = Certificate{federated[i]}
  420. }
  421. JSONStatus(w, &FederationResponse{
  422. Certificates: certs,
  423. }, http.StatusCreated)
  424. }
  425. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  426. type stepProvisioner struct {
  427. Type int
  428. Name []byte
  429. CredentialID []byte
  430. }
  431. func logOtt(w http.ResponseWriter, token string) {
  432. if rl, ok := w.(logging.ResponseLogger); ok {
  433. rl.WithFields(map[string]interface{}{
  434. "ott": token,
  435. })
  436. }
  437. }
  438. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  439. if rl, ok := w.(logging.ResponseLogger); ok {
  440. m := map[string]interface{}{
  441. "serial": cert.SerialNumber,
  442. "subject": cert.Subject.CommonName,
  443. "issuer": cert.Issuer.CommonName,
  444. "valid-from": cert.NotBefore.Format(time.RFC3339),
  445. "valid-to": cert.NotAfter.Format(time.RFC3339),
  446. "public-key": fmtPublicKey(cert),
  447. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  448. }
  449. for _, ext := range cert.Extensions {
  450. if ext.Id.Equal(oidStepProvisioner) {
  451. val := &stepProvisioner{}
  452. rest, err := asn1.Unmarshal(ext.Value, val)
  453. if err != nil || len(rest) > 0 {
  454. break
  455. }
  456. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  457. break
  458. }
  459. }
  460. rl.WithFields(m)
  461. }
  462. }
  463. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  464. q := r.URL.Query()
  465. cursor = q.Get("cursor")
  466. if v := q.Get("limit"); len(v) > 0 {
  467. limit, err = strconv.Atoi(v)
  468. if err != nil {
  469. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  470. }
  471. }
  472. return
  473. }
  474. // TODO: add support for Ed25519 once it's supported
  475. func fmtPublicKey(cert *x509.Certificate) string {
  476. var params string
  477. switch pk := cert.PublicKey.(type) {
  478. case *ecdsa.PublicKey:
  479. params = pk.Curve.Params().Name
  480. case *rsa.PublicKey:
  481. params = strconv.Itoa(pk.Size() * 8)
  482. case *dsa.PublicKey:
  483. params = strconv.Itoa(pk.Q.BitLen() * 8)
  484. default:
  485. params = "unknown"
  486. }
  487. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  488. }