api.go 13 KB

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