api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. Authority Authority
  221. }
  222. // New creates a new RouterHandler with the CA endpoints.
  223. func New(auth Authority) RouterHandler {
  224. return &caHandler{
  225. Authority: auth,
  226. }
  227. }
  228. func (h *caHandler) 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", "/provisioners", Provisioners)
  237. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", ProvisionerKey)
  238. r.MethodFunc("GET", "/roots", Roots)
  239. r.MethodFunc("GET", "/roots.pem", RootsPEM)
  240. r.MethodFunc("GET", "/federation", Federation)
  241. // SSH CA
  242. r.MethodFunc("POST", "/ssh/sign", SSHSign)
  243. r.MethodFunc("POST", "/ssh/renew", SSHRenew)
  244. r.MethodFunc("POST", "/ssh/revoke", SSHRevoke)
  245. r.MethodFunc("POST", "/ssh/rekey", SSHRekey)
  246. r.MethodFunc("GET", "/ssh/roots", SSHRoots)
  247. r.MethodFunc("GET", "/ssh/federation", SSHFederation)
  248. r.MethodFunc("POST", "/ssh/config", SSHConfig)
  249. r.MethodFunc("POST", "/ssh/config/{type}", SSHConfig)
  250. r.MethodFunc("POST", "/ssh/check-host", SSHCheckHost)
  251. r.MethodFunc("GET", "/ssh/hosts", SSHGetHosts)
  252. r.MethodFunc("POST", "/ssh/bastion", SSHBastion)
  253. // For compatibility with old code:
  254. r.MethodFunc("POST", "/re-sign", Renew)
  255. r.MethodFunc("POST", "/sign-ssh", SSHSign)
  256. r.MethodFunc("GET", "/ssh/get-hosts", SSHGetHosts)
  257. }
  258. // Version is an HTTP handler that returns the version of the server.
  259. func Version(w http.ResponseWriter, r *http.Request) {
  260. v := mustAuthority(r.Context()).Version()
  261. render.JSON(w, VersionResponse{
  262. Version: v.Version,
  263. RequireClientAuthentication: v.RequireClientAuthentication,
  264. })
  265. }
  266. // Health is an HTTP handler that returns the status of the server.
  267. func Health(w http.ResponseWriter, r *http.Request) {
  268. render.JSON(w, HealthResponse{Status: "ok"})
  269. }
  270. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  271. // certificate for the given SHA256.
  272. func Root(w http.ResponseWriter, r *http.Request) {
  273. sha := chi.URLParam(r, "sha")
  274. sum := strings.ToLower(strings.ReplaceAll(sha, "-", ""))
  275. // Load root certificate with the
  276. cert, err := mustAuthority(r.Context()).Root(sum)
  277. if err != nil {
  278. render.Error(w, errs.Wrapf(http.StatusNotFound, err, "%s was not found", r.RequestURI))
  279. return
  280. }
  281. render.JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  282. }
  283. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  284. certChainPEM := make([]Certificate, 0, len(certChain))
  285. for _, c := range certChain {
  286. certChainPEM = append(certChainPEM, Certificate{c})
  287. }
  288. return certChainPEM
  289. }
  290. // Provisioners returns the list of provisioners configured in the authority.
  291. func Provisioners(w http.ResponseWriter, r *http.Request) {
  292. cursor, limit, err := ParseCursor(r)
  293. if err != nil {
  294. render.Error(w, err)
  295. return
  296. }
  297. p, next, err := mustAuthority(r.Context()).GetProvisioners(cursor, limit)
  298. if err != nil {
  299. render.Error(w, errs.InternalServerErr(err))
  300. return
  301. }
  302. render.JSON(w, &ProvisionersResponse{
  303. Provisioners: p,
  304. NextCursor: next,
  305. })
  306. }
  307. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  308. func ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  309. kid := chi.URLParam(r, "kid")
  310. key, err := mustAuthority(r.Context()).GetEncryptedKey(kid)
  311. if err != nil {
  312. render.Error(w, errs.NotFoundErr(err))
  313. return
  314. }
  315. render.JSON(w, &ProvisionerKeyResponse{key})
  316. }
  317. // Roots returns all the root certificates for the CA.
  318. func Roots(w http.ResponseWriter, r *http.Request) {
  319. roots, err := mustAuthority(r.Context()).GetRoots()
  320. if err != nil {
  321. render.Error(w, errs.ForbiddenErr(err, "error getting roots"))
  322. return
  323. }
  324. certs := make([]Certificate, len(roots))
  325. for i := range roots {
  326. certs[i] = Certificate{roots[i]}
  327. }
  328. render.JSONStatus(w, &RootsResponse{
  329. Certificates: certs,
  330. }, http.StatusCreated)
  331. }
  332. // RootsPEM returns all the root certificates for the CA in PEM format.
  333. func RootsPEM(w http.ResponseWriter, r *http.Request) {
  334. roots, err := mustAuthority(r.Context()).GetRoots()
  335. if err != nil {
  336. render.Error(w, errs.InternalServerErr(err))
  337. return
  338. }
  339. w.Header().Set("Content-Type", "application/x-pem-file")
  340. for _, root := range roots {
  341. block := pem.EncodeToMemory(&pem.Block{
  342. Type: "CERTIFICATE",
  343. Bytes: root.Raw,
  344. })
  345. if _, err := w.Write(block); err != nil {
  346. log.Error(w, err)
  347. return
  348. }
  349. }
  350. }
  351. // Federation returns all the public certificates in the federation.
  352. func Federation(w http.ResponseWriter, r *http.Request) {
  353. federated, err := mustAuthority(r.Context()).GetFederation()
  354. if err != nil {
  355. render.Error(w, errs.ForbiddenErr(err, "error getting federated roots"))
  356. return
  357. }
  358. certs := make([]Certificate, len(federated))
  359. for i := range federated {
  360. certs[i] = Certificate{federated[i]}
  361. }
  362. render.JSONStatus(w, &FederationResponse{
  363. Certificates: certs,
  364. }, http.StatusCreated)
  365. }
  366. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  367. type stepProvisioner struct {
  368. Type int
  369. Name []byte
  370. CredentialID []byte
  371. }
  372. func logOtt(w http.ResponseWriter, token string) {
  373. if rl, ok := w.(logging.ResponseLogger); ok {
  374. rl.WithFields(map[string]interface{}{
  375. "ott": token,
  376. })
  377. }
  378. }
  379. // LogCertificate add certificate fields to the log message.
  380. func LogCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  381. if rl, ok := w.(logging.ResponseLogger); ok {
  382. m := map[string]interface{}{
  383. "serial": cert.SerialNumber.String(),
  384. "subject": cert.Subject.CommonName,
  385. "issuer": cert.Issuer.CommonName,
  386. "valid-from": cert.NotBefore.Format(time.RFC3339),
  387. "valid-to": cert.NotAfter.Format(time.RFC3339),
  388. "public-key": fmtPublicKey(cert),
  389. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  390. }
  391. for _, ext := range cert.Extensions {
  392. if !ext.Id.Equal(oidStepProvisioner) {
  393. continue
  394. }
  395. val := &stepProvisioner{}
  396. rest, err := asn1.Unmarshal(ext.Value, val)
  397. if err != nil || len(rest) > 0 {
  398. break
  399. }
  400. if len(val.CredentialID) > 0 {
  401. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  402. } else {
  403. m["provisioner"] = string(val.Name)
  404. }
  405. break
  406. }
  407. rl.WithFields(m)
  408. }
  409. }
  410. // ParseCursor parses the cursor and limit from the request query params.
  411. func ParseCursor(r *http.Request) (cursor string, limit int, err error) {
  412. q := r.URL.Query()
  413. cursor = q.Get("cursor")
  414. if v := q.Get("limit"); len(v) > 0 {
  415. limit, err = strconv.Atoi(v)
  416. if err != nil {
  417. return "", 0, errs.BadRequestErr(err, "limit '%s' is not an integer", v)
  418. }
  419. }
  420. return
  421. }
  422. func fmtPublicKey(cert *x509.Certificate) string {
  423. var params string
  424. switch pk := cert.PublicKey.(type) {
  425. case *ecdsa.PublicKey:
  426. params = pk.Curve.Params().Name
  427. case *rsa.PublicKey:
  428. params = strconv.Itoa(pk.Size() * 8)
  429. case ed25519.PublicKey:
  430. return cert.PublicKeyAlgorithm.String()
  431. case *dsa.PublicKey:
  432. params = strconv.Itoa(pk.Q.BitLen() * 8)
  433. default:
  434. params = "unknown"
  435. }
  436. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  437. }