4
0

api.go 14 KB

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