api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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(*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("GET", "/ssh/roots", h.SSHRoots)
  227. r.MethodFunc("GET", "/ssh/federation", h.SSHFederation)
  228. r.MethodFunc("POST", "/ssh/config", h.SSHConfig)
  229. r.MethodFunc("POST", "/ssh/config/{type}", h.SSHConfig)
  230. // For compatibility with old code:
  231. r.MethodFunc("POST", "/re-sign", h.Renew)
  232. r.MethodFunc("POST", "/sign-ssh", h.SSHSign)
  233. }
  234. // Health is an HTTP handler that returns the status of the server.
  235. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  236. JSON(w, HealthResponse{Status: "ok"})
  237. }
  238. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  239. // certificate for the given SHA256.
  240. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  241. sha := chi.URLParam(r, "sha")
  242. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  243. // Load root certificate with the
  244. cert, err := h.Authority.Root(sum)
  245. if err != nil {
  246. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  247. return
  248. }
  249. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  250. }
  251. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  252. certChainPEM := make([]Certificate, 0, len(certChain))
  253. for _, c := range certChain {
  254. certChainPEM = append(certChainPEM, Certificate{c})
  255. }
  256. return certChainPEM
  257. }
  258. // Sign is an HTTP handler that reads a certificate request and an
  259. // one-time-token (ott) from the body and creates a new certificate with the
  260. // information in the certificate request.
  261. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  262. var body SignRequest
  263. if err := ReadJSON(r.Body, &body); err != nil {
  264. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  265. return
  266. }
  267. logOtt(w, body.OTT)
  268. if err := body.Validate(); err != nil {
  269. WriteError(w, err)
  270. return
  271. }
  272. opts := provisioner.Options{
  273. NotBefore: body.NotBefore,
  274. NotAfter: body.NotAfter,
  275. }
  276. signOpts, err := h.Authority.AuthorizeSign(body.OTT)
  277. if err != nil {
  278. WriteError(w, Unauthorized(err))
  279. return
  280. }
  281. certChain, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
  282. if err != nil {
  283. WriteError(w, Forbidden(err))
  284. return
  285. }
  286. certChainPEM := certChainToPEM(certChain)
  287. var caPEM Certificate
  288. if len(certChainPEM) > 0 {
  289. caPEM = certChainPEM[1]
  290. }
  291. logCertificate(w, certChain[0])
  292. JSONStatus(w, &SignResponse{
  293. ServerPEM: certChainPEM[0],
  294. CaPEM: caPEM,
  295. CertChainPEM: certChainPEM,
  296. TLSOptions: h.Authority.GetTLSOptions(),
  297. }, http.StatusCreated)
  298. }
  299. // Renew uses the information of certificate in the TLS connection to create a
  300. // new one.
  301. func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
  302. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  303. WriteError(w, BadRequest(errors.New("missing peer certificate")))
  304. return
  305. }
  306. certChain, err := h.Authority.Renew(r.TLS.PeerCertificates[0])
  307. if err != nil {
  308. WriteError(w, Forbidden(err))
  309. return
  310. }
  311. certChainPEM := certChainToPEM(certChain)
  312. var caPEM Certificate
  313. if len(certChainPEM) > 0 {
  314. caPEM = certChainPEM[1]
  315. }
  316. logCertificate(w, certChain[0])
  317. JSONStatus(w, &SignResponse{
  318. ServerPEM: certChainPEM[0],
  319. CaPEM: caPEM,
  320. CertChainPEM: certChainPEM,
  321. TLSOptions: h.Authority.GetTLSOptions(),
  322. }, http.StatusCreated)
  323. }
  324. // Provisioners returns the list of provisioners configured in the authority.
  325. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  326. cursor, limit, err := parseCursor(r)
  327. if err != nil {
  328. WriteError(w, BadRequest(err))
  329. return
  330. }
  331. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  332. if err != nil {
  333. WriteError(w, InternalServerError(err))
  334. return
  335. }
  336. JSON(w, &ProvisionersResponse{
  337. Provisioners: p,
  338. NextCursor: next,
  339. })
  340. }
  341. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  342. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  343. kid := chi.URLParam(r, "kid")
  344. key, err := h.Authority.GetEncryptedKey(kid)
  345. if err != nil {
  346. WriteError(w, NotFound(err))
  347. return
  348. }
  349. JSON(w, &ProvisionerKeyResponse{key})
  350. }
  351. // Roots returns all the root certificates for the CA.
  352. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  353. roots, err := h.Authority.GetRoots()
  354. if err != nil {
  355. WriteError(w, Forbidden(err))
  356. return
  357. }
  358. certs := make([]Certificate, len(roots))
  359. for i := range roots {
  360. certs[i] = Certificate{roots[i]}
  361. }
  362. JSONStatus(w, &RootsResponse{
  363. Certificates: certs,
  364. }, http.StatusCreated)
  365. }
  366. // Federation returns all the public certificates in the federation.
  367. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  368. federated, err := h.Authority.GetFederation()
  369. if err != nil {
  370. WriteError(w, Forbidden(err))
  371. return
  372. }
  373. certs := make([]Certificate, len(federated))
  374. for i := range federated {
  375. certs[i] = Certificate{federated[i]}
  376. }
  377. JSONStatus(w, &FederationResponse{
  378. Certificates: certs,
  379. }, http.StatusCreated)
  380. }
  381. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  382. type stepProvisioner struct {
  383. Type int
  384. Name []byte
  385. CredentialID []byte
  386. }
  387. func logOtt(w http.ResponseWriter, token string) {
  388. if rl, ok := w.(logging.ResponseLogger); ok {
  389. rl.WithFields(map[string]interface{}{
  390. "ott": token,
  391. })
  392. }
  393. }
  394. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  395. if rl, ok := w.(logging.ResponseLogger); ok {
  396. m := map[string]interface{}{
  397. "serial": cert.SerialNumber,
  398. "subject": cert.Subject.CommonName,
  399. "issuer": cert.Issuer.CommonName,
  400. "valid-from": cert.NotBefore.Format(time.RFC3339),
  401. "valid-to": cert.NotAfter.Format(time.RFC3339),
  402. "public-key": fmtPublicKey(cert),
  403. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  404. }
  405. for _, ext := range cert.Extensions {
  406. if ext.Id.Equal(oidStepProvisioner) {
  407. val := &stepProvisioner{}
  408. rest, err := asn1.Unmarshal(ext.Value, val)
  409. if err != nil || len(rest) > 0 {
  410. break
  411. }
  412. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  413. break
  414. }
  415. }
  416. rl.WithFields(m)
  417. }
  418. }
  419. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  420. q := r.URL.Query()
  421. cursor = q.Get("cursor")
  422. if v := q.Get("limit"); len(v) > 0 {
  423. limit, err = strconv.Atoi(v)
  424. if err != nil {
  425. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  426. }
  427. }
  428. return
  429. }
  430. // TODO: add support for Ed25519 once it's supported
  431. func fmtPublicKey(cert *x509.Certificate) string {
  432. var params string
  433. switch pk := cert.PublicKey.(type) {
  434. case *ecdsa.PublicKey:
  435. params = pk.Curve.Params().Name
  436. case *rsa.PublicKey:
  437. params = strconv.Itoa(pk.Size() * 8)
  438. case *dsa.PublicKey:
  439. params = strconv.Itoa(pk.Q.BitLen() * 8)
  440. default:
  441. params = "unknown"
  442. }
  443. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  444. }