api.go 14 KB

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