4
0

api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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/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. AuthorizeSign(ott string) ([]provisioner.SignOption, error)
  35. AuthorizeRenewToken(ctx context.Context, ott string) (*x509.Certificate, error)
  36. GetTLSOptions() *config.TLSOptions
  37. Root(shasum string) (*x509.Certificate, error)
  38. Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  39. Renew(peer *x509.Certificate) ([]*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. }
  50. var errAuthority = errors.New("authority is not in context")
  51. func mustAuthority(ctx context.Context) Authority {
  52. a, ok := authority.FromContext(ctx)
  53. if !ok {
  54. panic(errAuthority)
  55. }
  56. return a
  57. }
  58. // TimeDuration is an alias of provisioner.TimeDuration
  59. type TimeDuration = provisioner.TimeDuration
  60. // NewTimeDuration returns a TimeDuration with the defined time.
  61. func NewTimeDuration(t time.Time) TimeDuration {
  62. return provisioner.NewTimeDuration(t)
  63. }
  64. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  65. // time.Duration string.
  66. func ParseTimeDuration(s string) (TimeDuration, error) {
  67. return provisioner.ParseTimeDuration(s)
  68. }
  69. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  70. type Certificate struct {
  71. *x509.Certificate
  72. }
  73. // NewCertificate is a helper method that returns a Certificate from a
  74. // *x509.Certificate.
  75. func NewCertificate(cr *x509.Certificate) Certificate {
  76. return Certificate{
  77. Certificate: cr,
  78. }
  79. }
  80. // reset sets the inner x509.CertificateRequest to nil
  81. func (c *Certificate) reset() {
  82. if c != nil {
  83. c.Certificate = nil
  84. }
  85. }
  86. // MarshalJSON implements the json.Marshaler interface. The certificate is
  87. // quoted string using the PEM encoding.
  88. func (c Certificate) MarshalJSON() ([]byte, error) {
  89. if c.Certificate == nil {
  90. return []byte("null"), nil
  91. }
  92. block := pem.EncodeToMemory(&pem.Block{
  93. Type: "CERTIFICATE",
  94. Bytes: c.Raw,
  95. })
  96. return json.Marshal(string(block))
  97. }
  98. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  99. // expected to be a quoted string using the PEM encoding.
  100. func (c *Certificate) UnmarshalJSON(data []byte) error {
  101. var s string
  102. if err := json.Unmarshal(data, &s); err != nil {
  103. return errors.Wrap(err, "error decoding certificate")
  104. }
  105. // Make sure the inner x509.Certificate is nil
  106. if s == "null" || s == "" {
  107. c.reset()
  108. return nil
  109. }
  110. block, _ := pem.Decode([]byte(s))
  111. if block == nil {
  112. return errors.New("error decoding certificate")
  113. }
  114. cert, err := x509.ParseCertificate(block.Bytes)
  115. if err != nil {
  116. return errors.Wrap(err, "error decoding certificate")
  117. }
  118. c.Certificate = cert
  119. return nil
  120. }
  121. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  122. // json.Unmarshaler interface.
  123. type CertificateRequest struct {
  124. *x509.CertificateRequest
  125. }
  126. // NewCertificateRequest is a helper method that returns a CertificateRequest
  127. // from a *x509.CertificateRequest.
  128. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  129. return CertificateRequest{
  130. CertificateRequest: cr,
  131. }
  132. }
  133. // reset sets the inner x509.CertificateRequest to nil
  134. func (c *CertificateRequest) reset() {
  135. if c != nil {
  136. c.CertificateRequest = nil
  137. }
  138. }
  139. // MarshalJSON implements the json.Marshaler interface. The certificate request
  140. // is a quoted string using the PEM encoding.
  141. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  142. if c.CertificateRequest == nil {
  143. return []byte("null"), nil
  144. }
  145. block := pem.EncodeToMemory(&pem.Block{
  146. Type: "CERTIFICATE REQUEST",
  147. Bytes: c.Raw,
  148. })
  149. return json.Marshal(string(block))
  150. }
  151. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  152. // request is expected to be a quoted string using the PEM encoding.
  153. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  154. var s string
  155. if err := json.Unmarshal(data, &s); err != nil {
  156. return errors.Wrap(err, "error decoding csr")
  157. }
  158. // Make sure the inner x509.CertificateRequest is nil
  159. if s == "null" || s == "" {
  160. c.reset()
  161. return nil
  162. }
  163. block, _ := pem.Decode([]byte(s))
  164. if block == nil {
  165. return errors.New("error decoding csr")
  166. }
  167. cr, err := x509.ParseCertificateRequest(block.Bytes)
  168. if err != nil {
  169. return errors.Wrap(err, "error decoding csr")
  170. }
  171. c.CertificateRequest = cr
  172. return nil
  173. }
  174. // Router defines a common router interface.
  175. type Router interface {
  176. // MethodFunc adds routes for `pattern` that matches
  177. // the `method` HTTP method.
  178. MethodFunc(method, pattern string, h http.HandlerFunc)
  179. }
  180. // RouterHandler is the interface that a HTTP handler that manages multiple
  181. // endpoints will implement.
  182. type RouterHandler interface {
  183. Route(r Router)
  184. }
  185. // VersionResponse is the response object that returns the version of the
  186. // server.
  187. type VersionResponse struct {
  188. Version string `json:"version"`
  189. RequireClientAuthentication bool `json:"requireClientAuthentication,omitempty"`
  190. }
  191. // HealthResponse is the response object that returns the health of the server.
  192. type HealthResponse struct {
  193. Status string `json:"status"`
  194. }
  195. // RootResponse is the response object that returns the PEM of a root certificate.
  196. type RootResponse struct {
  197. RootPEM Certificate `json:"ca"`
  198. }
  199. // ProvisionersResponse is the response object that returns the list of
  200. // provisioners.
  201. type ProvisionersResponse struct {
  202. Provisioners provisioner.List `json:"provisioners"`
  203. NextCursor string `json:"nextCursor"`
  204. }
  205. // ProvisionerKeyResponse is the response object that returns the encrypted key
  206. // of a provisioner.
  207. type ProvisionerKeyResponse struct {
  208. Key string `json:"key"`
  209. }
  210. // RootsResponse is the response object of the roots request.
  211. type RootsResponse struct {
  212. Certificates []Certificate `json:"crts"`
  213. }
  214. // FederationResponse is the response object of the federation request.
  215. type FederationResponse struct {
  216. Certificates []Certificate `json:"crts"`
  217. }
  218. // caHandler is the type used to implement the different CA HTTP endpoints.
  219. type caHandler struct{}
  220. // Route configures the http request router.
  221. func (h *caHandler) Route(r Router) {
  222. Route(r)
  223. }
  224. // New creates a new RouterHandler with the CA endpoints.
  225. //
  226. // Deprecated: Use api.Route(r Router)
  227. func New(auth Authority) RouterHandler {
  228. return &caHandler{}
  229. }
  230. func Route(r Router) {
  231. r.MethodFunc("GET", "/version", Version)
  232. r.MethodFunc("GET", "/health", Health)
  233. r.MethodFunc("GET", "/root/{sha}", Root)
  234. r.MethodFunc("POST", "/sign", Sign)
  235. r.MethodFunc("POST", "/renew", Renew)
  236. r.MethodFunc("POST", "/rekey", Rekey)
  237. r.MethodFunc("POST", "/revoke", Revoke)
  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. }