4
0

api.go 14 KB

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