4
0

api.go 14 KB

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