4
0

ssh.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package api
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/base64"
  6. "encoding/json"
  7. "net/http"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority"
  11. "github.com/smallstep/certificates/authority/config"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. "github.com/smallstep/certificates/errs"
  14. "github.com/smallstep/certificates/templates"
  15. "golang.org/x/crypto/ssh"
  16. )
  17. // SSHAuthority is the interface implemented by a SSH CA authority.
  18. type SSHAuthority interface {
  19. SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  20. RenewSSH(ctx context.Context, cert *ssh.Certificate) (*ssh.Certificate, error)
  21. RekeySSH(ctx context.Context, cert *ssh.Certificate, key ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  22. SignSSHAddUser(ctx context.Context, key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  23. GetSSHRoots(ctx context.Context) (*config.SSHKeys, error)
  24. GetSSHFederation(ctx context.Context) (*config.SSHKeys, error)
  25. GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error)
  26. CheckSSHHost(ctx context.Context, principal string, token string) (bool, error)
  27. GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error)
  28. GetSSHBastion(ctx context.Context, user string, hostname string) (*config.Bastion, error)
  29. }
  30. // SSHSignRequest is the request body of an SSH certificate request.
  31. type SSHSignRequest struct {
  32. PublicKey []byte `json:"publicKey"` // base64 encoded
  33. OTT string `json:"ott"`
  34. CertType string `json:"certType,omitempty"`
  35. KeyID string `json:"keyID,omitempty"`
  36. Principals []string `json:"principals,omitempty"`
  37. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  38. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  39. AddUserPublicKey []byte `json:"addUserPublicKey,omitempty"`
  40. IdentityCSR CertificateRequest `json:"identityCSR,omitempty"`
  41. TemplateData json.RawMessage `json:"templateData,omitempty"`
  42. }
  43. // Validate validates the SSHSignRequest.
  44. func (s *SSHSignRequest) Validate() error {
  45. switch {
  46. case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
  47. return errors.Errorf("unknown certType %s", s.CertType)
  48. case len(s.PublicKey) == 0:
  49. return errors.New("missing or empty publicKey")
  50. case len(s.OTT) == 0:
  51. return errors.New("missing or empty ott")
  52. default:
  53. // Validate identity signature if provided
  54. if s.IdentityCSR.CertificateRequest != nil {
  55. if err := s.IdentityCSR.CertificateRequest.CheckSignature(); err != nil {
  56. return errors.Wrap(err, "invalid identityCSR")
  57. }
  58. }
  59. return nil
  60. }
  61. }
  62. // SSHSignResponse is the response object that returns the SSH certificate.
  63. type SSHSignResponse struct {
  64. Certificate SSHCertificate `json:"crt"`
  65. AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
  66. IdentityCertificate []Certificate `json:"identityCrt,omitempty"`
  67. }
  68. // SSHRootsResponse represents the response object that returns the SSH user and
  69. // host keys.
  70. type SSHRootsResponse struct {
  71. UserKeys []SSHPublicKey `json:"userKey,omitempty"`
  72. HostKeys []SSHPublicKey `json:"hostKey,omitempty"`
  73. }
  74. // SSHCertificate represents the response SSH certificate.
  75. type SSHCertificate struct {
  76. *ssh.Certificate `json:"omitempty"`
  77. }
  78. // SSHGetHostsResponse is the response object that returns the list of valid
  79. // hosts for SSH.
  80. type SSHGetHostsResponse struct {
  81. Hosts []config.Host `json:"hosts"`
  82. }
  83. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  84. // base64 encoded, openssh wire format version of the certificate.
  85. func (c SSHCertificate) MarshalJSON() ([]byte, error) {
  86. if c.Certificate == nil {
  87. return []byte("null"), nil
  88. }
  89. s := base64.StdEncoding.EncodeToString(c.Certificate.Marshal())
  90. return []byte(`"` + s + `"`), nil
  91. }
  92. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  93. // expected to be a quoted, base64 encoded, openssh wire formatted block of bytes.
  94. func (c *SSHCertificate) UnmarshalJSON(data []byte) error {
  95. var s string
  96. if err := json.Unmarshal(data, &s); err != nil {
  97. return errors.Wrap(err, "error decoding certificate")
  98. }
  99. if s == "" {
  100. c.Certificate = nil
  101. return nil
  102. }
  103. certData, err := base64.StdEncoding.DecodeString(s)
  104. if err != nil {
  105. return errors.Wrap(err, "error decoding ssh certificate")
  106. }
  107. pub, err := ssh.ParsePublicKey(certData)
  108. if err != nil {
  109. return errors.Wrap(err, "error parsing ssh certificate")
  110. }
  111. cert, ok := pub.(*ssh.Certificate)
  112. if !ok {
  113. return errors.Errorf("error decoding ssh certificate: %T is not an *ssh.Certificate", pub)
  114. }
  115. c.Certificate = cert
  116. return nil
  117. }
  118. // SSHPublicKey represents a public key in a response object.
  119. type SSHPublicKey struct {
  120. ssh.PublicKey
  121. }
  122. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  123. // base64 encoded, openssh wire format version of the public key.
  124. func (p *SSHPublicKey) MarshalJSON() ([]byte, error) {
  125. if p == nil || p.PublicKey == nil {
  126. return []byte("null"), nil
  127. }
  128. s := base64.StdEncoding.EncodeToString(p.PublicKey.Marshal())
  129. return []byte(`"` + s + `"`), nil
  130. }
  131. // UnmarshalJSON implements the json.Unmarshaler interface. The public key is
  132. // expected to be a quoted, base64 encoded, openssh wire formatted block of
  133. // bytes.
  134. func (p *SSHPublicKey) UnmarshalJSON(data []byte) error {
  135. var s string
  136. if err := json.Unmarshal(data, &s); err != nil {
  137. return errors.Wrap(err, "error decoding ssh public key")
  138. }
  139. if s == "" {
  140. p.PublicKey = nil
  141. return nil
  142. }
  143. data, err := base64.StdEncoding.DecodeString(s)
  144. if err != nil {
  145. return errors.Wrap(err, "error decoding ssh public key")
  146. }
  147. pub, err := ssh.ParsePublicKey(data)
  148. if err != nil {
  149. return errors.Wrap(err, "error parsing ssh public key")
  150. }
  151. p.PublicKey = pub
  152. return nil
  153. }
  154. // Template represents the output of a template.
  155. type Template = templates.Output
  156. // SSHConfigRequest is the request body used to get the SSH configuration
  157. // templates.
  158. type SSHConfigRequest struct {
  159. Type string `json:"type"`
  160. Data map[string]string `json:"data"`
  161. }
  162. // Validate checks the values of the SSHConfigurationRequest.
  163. func (r *SSHConfigRequest) Validate() error {
  164. switch r.Type {
  165. case "":
  166. r.Type = provisioner.SSHUserCert
  167. return nil
  168. case provisioner.SSHUserCert, provisioner.SSHHostCert:
  169. return nil
  170. default:
  171. return errors.Errorf("unsupported type %s", r.Type)
  172. }
  173. }
  174. // SSHConfigResponse is the response that returns the rendered templates.
  175. type SSHConfigResponse struct {
  176. UserTemplates []Template `json:"userTemplates,omitempty"`
  177. HostTemplates []Template `json:"hostTemplates,omitempty"`
  178. }
  179. // SSHCheckPrincipalRequest is the request body used to check if a principal
  180. // certificate has been created. Right now it only supported for hosts
  181. // certificates.
  182. type SSHCheckPrincipalRequest struct {
  183. Type string `json:"type"`
  184. Principal string `json:"principal"`
  185. Token string `json:"token,omitempty"`
  186. }
  187. // Validate checks the check principal request.
  188. func (r *SSHCheckPrincipalRequest) Validate() error {
  189. switch {
  190. case r.Type != provisioner.SSHHostCert:
  191. return errors.Errorf("unsupported type %s", r.Type)
  192. case r.Principal == "":
  193. return errors.New("missing or empty principal")
  194. default:
  195. return nil
  196. }
  197. }
  198. // SSHCheckPrincipalResponse is the response body used to check if a principal
  199. // exists.
  200. type SSHCheckPrincipalResponse struct {
  201. Exists bool `json:"exists"`
  202. }
  203. // SSHBastionRequest is the request body used to get the bastion for a given
  204. // host.
  205. type SSHBastionRequest struct {
  206. User string `json:"user"`
  207. Hostname string `json:"hostname"`
  208. }
  209. // Validate checks the values of the SSHBastionRequest.
  210. func (r *SSHBastionRequest) Validate() error {
  211. if r.Hostname == "" {
  212. return errors.New("missing or empty hostname")
  213. }
  214. return nil
  215. }
  216. // SSHBastionResponse is the response body used to return the bastion for a
  217. // given host.
  218. type SSHBastionResponse struct {
  219. Hostname string `json:"hostname"`
  220. Bastion *config.Bastion `json:"bastion,omitempty"`
  221. }
  222. // SSHSign is an HTTP handler that reads an SignSSHRequest with a one-time-token
  223. // (ott) from the body and creates a new SSH certificate with the information in
  224. // the request.
  225. func (h *caHandler) SSHSign(w http.ResponseWriter, r *http.Request) {
  226. var body SSHSignRequest
  227. if err := ReadJSON(r.Body, &body); err != nil {
  228. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  229. return
  230. }
  231. logOtt(w, body.OTT)
  232. if err := body.Validate(); err != nil {
  233. WriteError(w, errs.BadRequestErr(err))
  234. return
  235. }
  236. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  237. if err != nil {
  238. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error parsing publicKey"))
  239. return
  240. }
  241. var addUserPublicKey ssh.PublicKey
  242. if body.AddUserPublicKey != nil {
  243. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  244. if err != nil {
  245. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error parsing addUserPublicKey"))
  246. return
  247. }
  248. }
  249. opts := provisioner.SignSSHOptions{
  250. CertType: body.CertType,
  251. KeyID: body.KeyID,
  252. Principals: body.Principals,
  253. ValidBefore: body.ValidBefore,
  254. ValidAfter: body.ValidAfter,
  255. TemplateData: body.TemplateData,
  256. }
  257. ctx := provisioner.NewContextWithMethod(r.Context(), provisioner.SSHSignMethod)
  258. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  259. if err != nil {
  260. WriteError(w, errs.UnauthorizedErr(err))
  261. return
  262. }
  263. cert, err := h.Authority.SignSSH(ctx, publicKey, opts, signOpts...)
  264. if err != nil {
  265. WriteError(w, errs.ForbiddenErr(err))
  266. return
  267. }
  268. var addUserCertificate *SSHCertificate
  269. if addUserPublicKey != nil && authority.IsValidForAddUser(cert) == nil {
  270. addUserCert, err := h.Authority.SignSSHAddUser(ctx, addUserPublicKey, cert)
  271. if err != nil {
  272. WriteError(w, errs.ForbiddenErr(err))
  273. return
  274. }
  275. addUserCertificate = &SSHCertificate{addUserCert}
  276. }
  277. // Sign identity certificate if available.
  278. var identityCertificate []Certificate
  279. if cr := body.IdentityCSR.CertificateRequest; cr != nil {
  280. ctx := authority.NewContextWithSkipTokenReuse(r.Context())
  281. ctx = provisioner.NewContextWithMethod(ctx, provisioner.SignMethod)
  282. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  283. if err != nil {
  284. WriteError(w, errs.UnauthorizedErr(err))
  285. return
  286. }
  287. // Enforce the same duration as ssh certificate.
  288. signOpts = append(signOpts, &identityModifier{
  289. NotBefore: time.Unix(int64(cert.ValidAfter), 0),
  290. NotAfter: time.Unix(int64(cert.ValidBefore), 0),
  291. })
  292. certChain, err := h.Authority.Sign(cr, provisioner.SignOptions{}, signOpts...)
  293. if err != nil {
  294. WriteError(w, errs.ForbiddenErr(err))
  295. return
  296. }
  297. identityCertificate = certChainToPEM(certChain)
  298. }
  299. JSONStatus(w, &SSHSignResponse{
  300. Certificate: SSHCertificate{cert},
  301. AddUserCertificate: addUserCertificate,
  302. IdentityCertificate: identityCertificate,
  303. }, http.StatusCreated)
  304. }
  305. // SSHRoots is an HTTP handler that returns the SSH public keys for user and host
  306. // certificates.
  307. func (h *caHandler) SSHRoots(w http.ResponseWriter, r *http.Request) {
  308. keys, err := h.Authority.GetSSHRoots(r.Context())
  309. if err != nil {
  310. WriteError(w, errs.InternalServerErr(err))
  311. return
  312. }
  313. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  314. WriteError(w, errs.NotFound("no keys found"))
  315. return
  316. }
  317. resp := new(SSHRootsResponse)
  318. for _, k := range keys.HostKeys {
  319. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  320. }
  321. for _, k := range keys.UserKeys {
  322. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  323. }
  324. JSON(w, resp)
  325. }
  326. // SSHFederation is an HTTP handler that returns the federated SSH public keys
  327. // for user and host certificates.
  328. func (h *caHandler) SSHFederation(w http.ResponseWriter, r *http.Request) {
  329. keys, err := h.Authority.GetSSHFederation(r.Context())
  330. if err != nil {
  331. WriteError(w, errs.InternalServerErr(err))
  332. return
  333. }
  334. if len(keys.HostKeys) == 0 && len(keys.UserKeys) == 0 {
  335. WriteError(w, errs.NotFound("no keys found"))
  336. return
  337. }
  338. resp := new(SSHRootsResponse)
  339. for _, k := range keys.HostKeys {
  340. resp.HostKeys = append(resp.HostKeys, SSHPublicKey{PublicKey: k})
  341. }
  342. for _, k := range keys.UserKeys {
  343. resp.UserKeys = append(resp.UserKeys, SSHPublicKey{PublicKey: k})
  344. }
  345. JSON(w, resp)
  346. }
  347. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  348. // and servers.
  349. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  350. var body SSHConfigRequest
  351. if err := ReadJSON(r.Body, &body); err != nil {
  352. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  353. return
  354. }
  355. if err := body.Validate(); err != nil {
  356. WriteError(w, errs.BadRequestErr(err))
  357. return
  358. }
  359. ts, err := h.Authority.GetSSHConfig(r.Context(), body.Type, body.Data)
  360. if err != nil {
  361. WriteError(w, errs.InternalServerErr(err))
  362. return
  363. }
  364. var config SSHConfigResponse
  365. switch body.Type {
  366. case provisioner.SSHUserCert:
  367. config.UserTemplates = ts
  368. case provisioner.SSHHostCert:
  369. config.HostTemplates = ts
  370. default:
  371. WriteError(w, errs.InternalServer("it should hot get here"))
  372. return
  373. }
  374. JSON(w, config)
  375. }
  376. // SSHCheckHost is the HTTP handler that returns if a hosts certificate exists or not.
  377. func (h *caHandler) SSHCheckHost(w http.ResponseWriter, r *http.Request) {
  378. var body SSHCheckPrincipalRequest
  379. if err := ReadJSON(r.Body, &body); err != nil {
  380. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  381. return
  382. }
  383. if err := body.Validate(); err != nil {
  384. WriteError(w, errs.BadRequestErr(err))
  385. return
  386. }
  387. exists, err := h.Authority.CheckSSHHost(r.Context(), body.Principal, body.Token)
  388. if err != nil {
  389. WriteError(w, errs.InternalServerErr(err))
  390. return
  391. }
  392. JSON(w, &SSHCheckPrincipalResponse{
  393. Exists: exists,
  394. })
  395. }
  396. // SSHGetHosts is the HTTP handler that returns a list of valid ssh hosts.
  397. func (h *caHandler) SSHGetHosts(w http.ResponseWriter, r *http.Request) {
  398. var cert *x509.Certificate
  399. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  400. cert = r.TLS.PeerCertificates[0]
  401. }
  402. hosts, err := h.Authority.GetSSHHosts(r.Context(), cert)
  403. if err != nil {
  404. WriteError(w, errs.InternalServerErr(err))
  405. return
  406. }
  407. JSON(w, &SSHGetHostsResponse{
  408. Hosts: hosts,
  409. })
  410. }
  411. // SSHBastion provides returns the bastion configured if any.
  412. func (h *caHandler) SSHBastion(w http.ResponseWriter, r *http.Request) {
  413. var body SSHBastionRequest
  414. if err := ReadJSON(r.Body, &body); err != nil {
  415. WriteError(w, errs.Wrap(http.StatusBadRequest, err, "error reading request body"))
  416. return
  417. }
  418. if err := body.Validate(); err != nil {
  419. WriteError(w, errs.BadRequestErr(err))
  420. return
  421. }
  422. bastion, err := h.Authority.GetSSHBastion(r.Context(), body.User, body.Hostname)
  423. if err != nil {
  424. WriteError(w, errs.InternalServerErr(err))
  425. return
  426. }
  427. JSON(w, &SSHBastionResponse{
  428. Hostname: body.Hostname,
  429. Bastion: bastion,
  430. })
  431. }
  432. // identityModifier is a custom modifier used to force a fixed duration.
  433. type identityModifier struct {
  434. NotBefore time.Time
  435. NotAfter time.Time
  436. }
  437. func (m *identityModifier) Enforce(cert *x509.Certificate) error {
  438. cert.NotBefore = m.NotBefore
  439. cert.NotAfter = m.NotAfter
  440. return nil
  441. }