ssh.go 14 KB

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