4
0

api.go 13 KB

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