api.go 14 KB

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