api.go 16 KB

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