api.go 13 KB

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