4
0

api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package api
  2. import (
  3. "context"
  4. "crypto/dsa"
  5. "crypto/ecdsa"
  6. "crypto/rsa"
  7. "crypto/tls"
  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/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. }
  43. // TimeDuration is an alias of provisioner.TimeDuration
  44. type TimeDuration = provisioner.TimeDuration
  45. // NewTimeDuration returns a TimeDuration with the defined time.
  46. func NewTimeDuration(t time.Time) TimeDuration {
  47. return provisioner.NewTimeDuration(t)
  48. }
  49. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  50. // time.Duration string.
  51. func ParseTimeDuration(s string) (TimeDuration, error) {
  52. return provisioner.ParseTimeDuration(s)
  53. }
  54. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  55. type Certificate struct {
  56. *x509.Certificate
  57. }
  58. // NewCertificate is a helper method that returns a Certificate from a
  59. // *x509.Certificate.
  60. func NewCertificate(cr *x509.Certificate) Certificate {
  61. return Certificate{
  62. Certificate: cr,
  63. }
  64. }
  65. // MarshalJSON implements the json.Marshaler interface. The certificate is
  66. // quoted string using the PEM encoding.
  67. func (c Certificate) MarshalJSON() ([]byte, error) {
  68. if c.Certificate == nil {
  69. return []byte("null"), nil
  70. }
  71. block := pem.EncodeToMemory(&pem.Block{
  72. Type: "CERTIFICATE",
  73. Bytes: c.Raw,
  74. })
  75. return json.Marshal(string(block))
  76. }
  77. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  78. // expected to be a quoted string using the PEM encoding.
  79. func (c *Certificate) UnmarshalJSON(data []byte) error {
  80. var s string
  81. if err := json.Unmarshal(data, &s); err != nil {
  82. return errors.Wrap(err, "error decoding certificate")
  83. }
  84. block, _ := pem.Decode([]byte(s))
  85. if block == nil {
  86. return errors.New("error decoding certificate")
  87. }
  88. cert, err := x509.ParseCertificate(block.Bytes)
  89. if err != nil {
  90. return errors.Wrap(err, "error decoding certificate")
  91. }
  92. c.Certificate = cert
  93. return nil
  94. }
  95. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  96. // json.Unmarshaler interface.
  97. type CertificateRequest struct {
  98. *x509.CertificateRequest
  99. }
  100. // NewCertificateRequest is a helper method that returns a CertificateRequest
  101. // from a *x509.CertificateRequest.
  102. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  103. return CertificateRequest{
  104. CertificateRequest: cr,
  105. }
  106. }
  107. // MarshalJSON implements the json.Marshaler interface. The certificate request
  108. // is a quoted string using the PEM encoding.
  109. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  110. if c.CertificateRequest == nil {
  111. return []byte("null"), nil
  112. }
  113. block := pem.EncodeToMemory(&pem.Block{
  114. Type: "CERTIFICATE REQUEST",
  115. Bytes: c.Raw,
  116. })
  117. return json.Marshal(string(block))
  118. }
  119. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  120. // request is expected to be a quoted string using the PEM encoding.
  121. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  122. var s string
  123. if err := json.Unmarshal(data, &s); err != nil {
  124. return errors.Wrap(err, "error decoding csr")
  125. }
  126. block, _ := pem.Decode([]byte(s))
  127. if block == nil {
  128. return errors.New("error decoding csr")
  129. }
  130. cr, err := x509.ParseCertificateRequest(block.Bytes)
  131. if err != nil {
  132. return errors.Wrap(err, "error decoding csr")
  133. }
  134. c.CertificateRequest = cr
  135. return nil
  136. }
  137. // Router defines a common router interface.
  138. type Router interface {
  139. // MethodFunc adds routes for `pattern` that matches
  140. // the `method` HTTP method.
  141. MethodFunc(method, pattern string, h http.HandlerFunc)
  142. }
  143. // RouterHandler is the interface that a HTTP handler that manages multiple
  144. // endpoints will implement.
  145. type RouterHandler interface {
  146. Route(r Router)
  147. }
  148. // HealthResponse is the response object that returns the health of the server.
  149. type HealthResponse struct {
  150. Status string `json:"status"`
  151. }
  152. // RootResponse is the response object that returns the PEM of a root certificate.
  153. type RootResponse struct {
  154. RootPEM Certificate `json:"ca"`
  155. }
  156. // SignRequest is the request body for a certificate signature request.
  157. type SignRequest struct {
  158. CsrPEM CertificateRequest `json:"csr"`
  159. OTT string `json:"ott"`
  160. NotAfter TimeDuration `json:"notAfter"`
  161. NotBefore TimeDuration `json:"notBefore"`
  162. }
  163. // ProvisionersResponse is the response object that returns the list of
  164. // provisioners.
  165. type ProvisionersResponse struct {
  166. Provisioners provisioner.List `json:"provisioners"`
  167. NextCursor string `json:"nextCursor"`
  168. }
  169. // ProvisionerKeyResponse is the response object that returns the encrypted key
  170. // of a provisioner.
  171. type ProvisionerKeyResponse struct {
  172. Key string `json:"key"`
  173. }
  174. // Validate checks the fields of the SignRequest and returns nil if they are ok
  175. // or an error if something is wrong.
  176. func (s *SignRequest) Validate() error {
  177. if s.CsrPEM.CertificateRequest == nil {
  178. return BadRequest(errors.New("missing csr"))
  179. }
  180. if err := s.CsrPEM.CertificateRequest.CheckSignature(); err != nil {
  181. return BadRequest(errors.Wrap(err, "invalid csr"))
  182. }
  183. if s.OTT == "" {
  184. return BadRequest(errors.New("missing ott"))
  185. }
  186. return nil
  187. }
  188. // SignResponse is the response object of the certificate signature request.
  189. type SignResponse struct {
  190. ServerPEM Certificate `json:"crt"`
  191. CaPEM Certificate `json:"ca"`
  192. CertChainPEM []Certificate `json:"certChain"`
  193. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  194. TLS *tls.ConnectionState `json:"-"`
  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", "/health", h.Health)
  216. r.MethodFunc("GET", "/root/{sha}", h.Root)
  217. r.MethodFunc("POST", "/sign", h.Sign)
  218. r.MethodFunc("POST", "/renew", h.Renew)
  219. r.MethodFunc("POST", "/revoke", h.Revoke)
  220. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  221. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  222. r.MethodFunc("GET", "/roots", h.Roots)
  223. r.MethodFunc("GET", "/federation", h.Federation)
  224. // SSH CA
  225. r.MethodFunc("POST", "/ssh/sign", h.SSHSign)
  226. r.MethodFunc("POST", "/ssh/renew", h.SSHRenew)
  227. r.MethodFunc("POST", "/ssh/revoke", h.SSHRevoke)
  228. r.MethodFunc("POST", "/ssh/rekey", h.SSHRekey)
  229. r.MethodFunc("GET", "/ssh/roots", h.SSHRoots)
  230. r.MethodFunc("GET", "/ssh/federation", h.SSHFederation)
  231. r.MethodFunc("POST", "/ssh/config", h.SSHConfig)
  232. r.MethodFunc("POST", "/ssh/config/{type}", h.SSHConfig)
  233. r.MethodFunc("POST", "/ssh/check-host", h.SSHCheckHost)
  234. r.MethodFunc("GET", "/ssh/get-hosts", h.SSHGetHosts)
  235. // For compatibility with old code:
  236. r.MethodFunc("POST", "/re-sign", h.Renew)
  237. r.MethodFunc("POST", "/sign-ssh", h.SSHSign)
  238. }
  239. // Health is an HTTP handler that returns the status of the server.
  240. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  241. JSON(w, HealthResponse{Status: "ok"})
  242. }
  243. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  244. // certificate for the given SHA256.
  245. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  246. sha := chi.URLParam(r, "sha")
  247. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  248. // Load root certificate with the
  249. cert, err := h.Authority.Root(sum)
  250. if err != nil {
  251. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  252. return
  253. }
  254. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  255. }
  256. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  257. certChainPEM := make([]Certificate, 0, len(certChain))
  258. for _, c := range certChain {
  259. certChainPEM = append(certChainPEM, Certificate{c})
  260. }
  261. return certChainPEM
  262. }
  263. // Sign is an HTTP handler that reads a certificate request and an
  264. // one-time-token (ott) from the body and creates a new certificate with the
  265. // information in the certificate request.
  266. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  267. var body SignRequest
  268. if err := ReadJSON(r.Body, &body); err != nil {
  269. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  270. return
  271. }
  272. logOtt(w, body.OTT)
  273. if err := body.Validate(); err != nil {
  274. WriteError(w, err)
  275. return
  276. }
  277. opts := provisioner.Options{
  278. NotBefore: body.NotBefore,
  279. NotAfter: body.NotAfter,
  280. }
  281. signOpts, err := h.Authority.AuthorizeSign(body.OTT)
  282. if err != nil {
  283. WriteError(w, Unauthorized(err))
  284. return
  285. }
  286. certChain, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
  287. if err != nil {
  288. WriteError(w, Forbidden(err))
  289. return
  290. }
  291. certChainPEM := certChainToPEM(certChain)
  292. var caPEM Certificate
  293. if len(certChainPEM) > 0 {
  294. caPEM = certChainPEM[1]
  295. }
  296. logCertificate(w, certChain[0])
  297. JSONStatus(w, &SignResponse{
  298. ServerPEM: certChainPEM[0],
  299. CaPEM: caPEM,
  300. CertChainPEM: certChainPEM,
  301. TLSOptions: h.Authority.GetTLSOptions(),
  302. }, http.StatusCreated)
  303. }
  304. // Renew uses the information of certificate in the TLS connection to create a
  305. // new one.
  306. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  307. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  308. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  309. return
  310. }
  311. certChain, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  312. if err != nil {
  313. WriteError(w, Forbidden(err))
  314. return
  315. }
  316. certChainPEM := certChainToPEM(certChain)
  317. var caPEM Certificate
  318. if len(certChainPEM) > 0 {
  319. caPEM = certChainPEM[1]
  320. }
  321. logCertificate(w, certChain[0])
  322. JSONStatus(w, &SignResponse{
  323. ServerPEM: certChainPEM[0],
  324. CaPEM: caPEM,
  325. CertChainPEM: certChainPEM,
  326. TLSOptions: h.Authority.GetTLSOptions(),
  327. }, http.StatusCreated)
  328. }
  329. // Provisioners returns the list of provisioners configured in the authority.
  330. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  331. cursor, limit, err := parseCursor(r)
  332. if err != nil {
  333. WriteError(w, BadRequest(err))
  334. return
  335. }
  336. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  337. if err != nil {
  338. WriteError(w, InternalServerError(err))
  339. return
  340. }
  341. JSON(w, &ProvisionersResponse{
  342. Provisioners: p,
  343. NextCursor: next,
  344. })
  345. }
  346. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  347. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  348. kid := chi.URLParam(r, "kid")
  349. key, err := h.Authority.GetEncryptedKey(kid)
  350. if err != nil {
  351. WriteError(w, NotFound(err))
  352. return
  353. }
  354. JSON(w, &ProvisionerKeyResponse{key})
  355. }
  356. // Roots returns all the root certificates for the CA.
  357. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  358. roots, err := h.Authority.GetRoots()
  359. if err != nil {
  360. WriteError(w, Forbidden(err))
  361. return
  362. }
  363. certs := make([]Certificate, len(roots))
  364. for i := range roots {
  365. certs[i] = Certificate{roots[i]}
  366. }
  367. JSONStatus(w, &RootsResponse{
  368. Certificates: certs,
  369. }, http.StatusCreated)
  370. }
  371. // Federation returns all the public certificates in the federation.
  372. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  373. federated, err := h.Authority.GetFederation()
  374. if err != nil {
  375. WriteError(w, Forbidden(err))
  376. return
  377. }
  378. certs := make([]Certificate, len(federated))
  379. for i := range federated {
  380. certs[i] = Certificate{federated[i]}
  381. }
  382. JSONStatus(w, &FederationResponse{
  383. Certificates: certs,
  384. }, http.StatusCreated)
  385. }
  386. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  387. type stepProvisioner struct {
  388. Type int
  389. Name []byte
  390. CredentialID []byte
  391. }
  392. func logOtt(w http.ResponseWriter, token string) {
  393. if rl, ok := w.(logging.ResponseLogger); ok {
  394. rl.WithFields(map[string]interface{}{
  395. "ott": token,
  396. })
  397. }
  398. }
  399. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  400. if rl, ok := w.(logging.ResponseLogger); ok {
  401. m := map[string]interface{}{
  402. "serial": cert.SerialNumber,
  403. "subject": cert.Subject.CommonName,
  404. "issuer": cert.Issuer.CommonName,
  405. "valid-from": cert.NotBefore.Format(time.RFC3339),
  406. "valid-to": cert.NotAfter.Format(time.RFC3339),
  407. "public-key": fmtPublicKey(cert),
  408. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  409. }
  410. for _, ext := range cert.Extensions {
  411. if ext.Id.Equal(oidStepProvisioner) {
  412. val := &stepProvisioner{}
  413. rest, err := asn1.Unmarshal(ext.Value, val)
  414. if err != nil || len(rest) > 0 {
  415. break
  416. }
  417. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  418. break
  419. }
  420. }
  421. rl.WithFields(m)
  422. }
  423. }
  424. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  425. q := r.URL.Query()
  426. cursor = q.Get("cursor")
  427. if v := q.Get("limit"); len(v) > 0 {
  428. limit, err = strconv.Atoi(v)
  429. if err != nil {
  430. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  431. }
  432. }
  433. return
  434. }
  435. // TODO: add support for Ed25519 once it's supported
  436. func fmtPublicKey(cert *x509.Certificate) string {
  437. var params string
  438. switch pk := cert.PublicKey.(type) {
  439. case *ecdsa.PublicKey:
  440. params = pk.Curve.Params().Name
  441. case *rsa.PublicKey:
  442. params = strconv.Itoa(pk.Size() * 8)
  443. case *dsa.PublicKey:
  444. params = strconv.Itoa(pk.Q.BitLen() * 8)
  445. default:
  446. params = "unknown"
  447. }
  448. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  449. }