api.go 15 KB

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