4
0

ssh.go 15 KB

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