api.go 13 KB

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