api.go 13 KB

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