api.go 14 KB

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