4
0

api.go 13 KB

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