ssh.go 14 KB

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