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