4
0

api.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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, *x509.Certificate, error)
  34. Renew(peer *x509.Certificate) (*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. TLSOptions *tlsutil.TLSOptions `json:"tlsOptions,omitempty"`
  193. TLS *tls.ConnectionState `json:"-"`
  194. }
  195. // RootsResponse is the response object of the roots request.
  196. type RootsResponse struct {
  197. Certificates []Certificate `json:"crts"`
  198. }
  199. // FederationResponse is the response object of the federation request.
  200. type FederationResponse struct {
  201. Certificates []Certificate `json:"crts"`
  202. }
  203. // caHandler is the type used to implement the different CA HTTP endpoints.
  204. type caHandler struct {
  205. Authority Authority
  206. }
  207. // New creates a new RouterHandler with the CA endpoints.
  208. func New(authority Authority) RouterHandler {
  209. return &caHandler{
  210. Authority: authority,
  211. }
  212. }
  213. func (h *caHandler) Route(r Router) {
  214. r.MethodFunc("GET", "/health", h.Health)
  215. r.MethodFunc("GET", "/root/{sha}", h.Root)
  216. r.MethodFunc("POST", "/sign", h.Sign)
  217. r.MethodFunc("POST", "/renew", h.Renew)
  218. r.MethodFunc("POST", "/revoke", h.Revoke)
  219. r.MethodFunc("GET", "/provisioners", h.Provisioners)
  220. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
  221. r.MethodFunc("GET", "/roots", h.Roots)
  222. r.MethodFunc("GET", "/federation", h.Federation)
  223. // For compatibility with old code:
  224. r.MethodFunc("POST", "/re-sign", h.Renew)
  225. // SSH CA
  226. r.MethodFunc("POST", "/sign-ssh", h.SignSSH)
  227. }
  228. // Health is an HTTP handler that returns the status of the server.
  229. func (h *caHandler) Health(w http.ResponseWriter, r *http.Request) {
  230. JSON(w, HealthResponse{Status: "ok"})
  231. }
  232. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  233. // certificate for the given SHA256.
  234. func (h *caHandler) Root(w http.ResponseWriter, r *http.Request) {
  235. sha := chi.URLParam(r, "sha")
  236. sum := strings.ToLower(strings.Replace(sha, "-", "", -1))
  237. // Load root certificate with the
  238. cert, err := h.Authority.Root(sum)
  239. if err != nil {
  240. WriteError(w, NotFound(errors.Wrapf(err, "%s was not found", r.RequestURI)))
  241. return
  242. }
  243. JSON(w, &RootResponse{RootPEM: Certificate{cert}})
  244. }
  245. // Sign is an HTTP handler that reads a certificate request and an
  246. // one-time-token (ott) from the body and creates a new certificate with the
  247. // information in the certificate request.
  248. func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
  249. var body SignRequest
  250. if err := ReadJSON(r.Body, &body); err != nil {
  251. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  252. return
  253. }
  254. logOtt(w, body.OTT)
  255. if err := body.Validate(); err != nil {
  256. WriteError(w, err)
  257. return
  258. }
  259. opts := provisioner.Options{
  260. NotBefore: body.NotBefore,
  261. NotAfter: body.NotAfter,
  262. }
  263. signOpts, err := h.Authority.AuthorizeSign(body.OTT)
  264. if err != nil {
  265. WriteError(w, Unauthorized(err))
  266. return
  267. }
  268. cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
  269. if err != nil {
  270. WriteError(w, Forbidden(err))
  271. return
  272. }
  273. logCertificate(w, cert)
  274. JSONStatus(w, &SignResponse{
  275. ServerPEM: Certificate{cert},
  276. CaPEM: Certificate{root},
  277. TLSOptions: h.Authority.GetTLSOptions(),
  278. }, http.StatusCreated)
  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. logCertificate(w, cert)
  293. JSONStatus(w, &SignResponse{
  294. ServerPEM: Certificate{cert},
  295. CaPEM: Certificate{root},
  296. TLSOptions: h.Authority.GetTLSOptions(),
  297. }, http.StatusCreated)
  298. }
  299. // Provisioners returns the list of provisioners configured in the authority.
  300. func (h *caHandler) Provisioners(w http.ResponseWriter, r *http.Request) {
  301. cursor, limit, err := parseCursor(r)
  302. if err != nil {
  303. WriteError(w, BadRequest(err))
  304. return
  305. }
  306. p, next, err := h.Authority.GetProvisioners(cursor, limit)
  307. if err != nil {
  308. WriteError(w, InternalServerError(err))
  309. return
  310. }
  311. JSON(w, &ProvisionersResponse{
  312. Provisioners: p,
  313. NextCursor: next,
  314. })
  315. }
  316. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  317. func (h *caHandler) ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  318. kid := chi.URLParam(r, "kid")
  319. key, err := h.Authority.GetEncryptedKey(kid)
  320. if err != nil {
  321. WriteError(w, NotFound(err))
  322. return
  323. }
  324. JSON(w, &ProvisionerKeyResponse{key})
  325. }
  326. // Roots returns all the root certificates for the CA.
  327. func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
  328. roots, err := h.Authority.GetRoots()
  329. if err != nil {
  330. WriteError(w, Forbidden(err))
  331. return
  332. }
  333. certs := make([]Certificate, len(roots))
  334. for i := range roots {
  335. certs[i] = Certificate{roots[i]}
  336. }
  337. JSONStatus(w, &RootsResponse{
  338. Certificates: certs,
  339. }, http.StatusCreated)
  340. }
  341. // Federation returns all the public certificates in the federation.
  342. func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
  343. federated, err := h.Authority.GetFederation()
  344. if err != nil {
  345. WriteError(w, Forbidden(err))
  346. return
  347. }
  348. certs := make([]Certificate, len(federated))
  349. for i := range federated {
  350. certs[i] = Certificate{federated[i]}
  351. }
  352. JSONStatus(w, &FederationResponse{
  353. Certificates: certs,
  354. }, http.StatusCreated)
  355. }
  356. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  357. type stepProvisioner struct {
  358. Type int
  359. Name []byte
  360. CredentialID []byte
  361. }
  362. func logOtt(w http.ResponseWriter, token string) {
  363. if rl, ok := w.(logging.ResponseLogger); ok {
  364. rl.WithFields(map[string]interface{}{
  365. "ott": token,
  366. })
  367. }
  368. }
  369. func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  370. if rl, ok := w.(logging.ResponseLogger); ok {
  371. m := map[string]interface{}{
  372. "serial": cert.SerialNumber,
  373. "subject": cert.Subject.CommonName,
  374. "issuer": cert.Issuer.CommonName,
  375. "valid-from": cert.NotBefore.Format(time.RFC3339),
  376. "valid-to": cert.NotAfter.Format(time.RFC3339),
  377. "public-key": fmtPublicKey(cert),
  378. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  379. }
  380. for _, ext := range cert.Extensions {
  381. if ext.Id.Equal(oidStepProvisioner) {
  382. val := &stepProvisioner{}
  383. rest, err := asn1.Unmarshal(ext.Value, val)
  384. if err != nil || len(rest) > 0 {
  385. break
  386. }
  387. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  388. break
  389. }
  390. }
  391. rl.WithFields(m)
  392. }
  393. }
  394. func parseCursor(r *http.Request) (cursor string, limit int, err error) {
  395. q := r.URL.Query()
  396. cursor = q.Get("cursor")
  397. if v := q.Get("limit"); len(v) > 0 {
  398. limit, err = strconv.Atoi(v)
  399. if err != nil {
  400. return "", 0, errors.Wrapf(err, "error converting %s to integer", v)
  401. }
  402. }
  403. return
  404. }
  405. // TODO: add support for Ed25519 once it's supported
  406. func fmtPublicKey(cert *x509.Certificate) string {
  407. var params string
  408. switch pk := cert.PublicKey.(type) {
  409. case *ecdsa.PublicKey:
  410. params = pk.Curve.Params().Name
  411. case *rsa.PublicKey:
  412. params = strconv.Itoa(pk.Size() * 8)
  413. case *dsa.PublicKey:
  414. params = strconv.Itoa(pk.Q.BitLen() * 8)
  415. default:
  416. params = "unknown"
  417. }
  418. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  419. }