sshd_reload_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package nebula
  2. import (
  3. "crypto"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "encoding/pem"
  8. "errors"
  9. "fmt"
  10. "net"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/slackhq/nebula/commands"
  17. "github.com/slackhq/nebula/config"
  18. "github.com/slackhq/nebula/sshd"
  19. "github.com/slackhq/nebula/test"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/stretchr/testify/require"
  22. "golang.org/x/crypto/ssh"
  23. )
  24. type sshdReloadHarness struct {
  25. c *config.C
  26. reg *commands.Registry
  27. server *sshd.SSHServer
  28. keyFile string
  29. signer ssh.Signer
  30. listen string
  31. users []string
  32. extra string
  33. }
  34. func newSSHDReloadHarness(t *testing.T) *sshdReloadHarness {
  35. t.Helper()
  36. l := test.NewLogger()
  37. h := &sshdReloadHarness{keyFile: filepath.Join(t.TempDir(), "host_key"), listen: "127.0.0.1:0", users: []string{"test"}}
  38. h.writeHostKey(t, newEd25519Key(t))
  39. _, userKey, err := ed25519.GenerateKey(rand.Reader)
  40. require.NoError(t, err)
  41. h.signer, err = ssh.NewSignerFromKey(userKey)
  42. require.NoError(t, err)
  43. h.c = config.NewC(l)
  44. require.NoError(t, h.c.LoadString(h.config()))
  45. h.reg = commands.New()
  46. h.server, err = sshd.NewSSHServer(t.Context(), l, h.reg)
  47. require.NoError(t, err)
  48. wireSSHReload(l, h.server, h.c)
  49. run, err := configSSH(l, h.server, h.c, nil)
  50. require.NoError(t, err)
  51. go run()
  52. t.Cleanup(h.server.Stop)
  53. require.Eventually(t, h.server.Running, 5*time.Second, 10*time.Millisecond)
  54. return h
  55. }
  56. func newEd25519Key(t *testing.T) crypto.Signer {
  57. _, key, err := ed25519.GenerateKey(rand.Reader)
  58. require.NoError(t, err)
  59. return key
  60. }
  61. // writeHostKey replaces the host key file and returns the public key a client should now see
  62. func (h *sshdReloadHarness) writeHostKey(t *testing.T, key crypto.Signer) ssh.PublicKey {
  63. t.Helper()
  64. block, err := ssh.MarshalPrivateKey(key, "")
  65. require.NoError(t, err)
  66. require.NoError(t, os.WriteFile(h.keyFile, pem.EncodeToMemory(block), 0o600))
  67. pub, err := ssh.NewPublicKey(key.Public())
  68. require.NoError(t, err)
  69. return pub
  70. }
  71. func (h *sshdReloadHarness) config() string {
  72. users := ""
  73. for _, u := range h.users {
  74. users += fmt.Sprintf(" - user: %s\n keys: [%q]\n", u, string(ssh.MarshalAuthorizedKey(h.signer.PublicKey())))
  75. }
  76. return fmt.Sprintf("sshd:\n enabled: true\n listen: %s\n host_key: %s\n authorized_users:\n%s%s",
  77. h.listen, h.keyFile, users, h.extra)
  78. }
  79. // dial connects to wherever the server listens now, a restart on :0 moves it. hostKeyAlgorithms limits which host keys
  80. // the client accepts, none means any
  81. func (h *sshdReloadHarness) dial(hostKeyAlgorithms ...string) (*ssh.Client, ssh.PublicKey, error) {
  82. addr := h.server.Addr()
  83. if addr == nil {
  84. return nil, nil, fmt.Errorf("not listening")
  85. }
  86. var hostKey ssh.PublicKey
  87. c, err := ssh.Dial("tcp", addr.String(), &ssh.ClientConfig{
  88. User: "test",
  89. Auth: []ssh.AuthMethod{ssh.PublicKeys(h.signer)},
  90. HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
  91. hostKey = key
  92. return nil
  93. },
  94. HostKeyAlgorithms: hostKeyAlgorithms,
  95. Timeout: time.Second,
  96. })
  97. return c, hostKey, err
  98. }
  99. func (h *sshdReloadHarness) connect(t *testing.T) (*ssh.Client, ssh.PublicKey) {
  100. t.Helper()
  101. var client *ssh.Client
  102. var hostKey ssh.PublicKey
  103. require.Eventually(t, func() bool {
  104. var err error
  105. client, hostKey, err = h.dial()
  106. return err == nil
  107. }, 5*time.Second, 20*time.Millisecond)
  108. t.Cleanup(func() { _ = client.Close() })
  109. return client, hostKey
  110. }
  111. // dropped is true when the server closed the client's connection within wait
  112. func dropped(client *ssh.Client, wait time.Duration) bool {
  113. done := make(chan struct{})
  114. go func() {
  115. _ = client.Wait()
  116. close(done)
  117. }()
  118. select {
  119. case <-done:
  120. return true
  121. case <-time.After(wait):
  122. return false
  123. }
  124. }
  125. // Restarting sshd drops every open session, the one that asked for the reload included. A reload that touches nothing
  126. // sshd reads leaves it alone
  127. func TestSSHDReload_UnchangedKeepsSessions(t *testing.T) {
  128. h := newSSHDReloadHarness(t)
  129. client, _ := h.connect(t)
  130. require.NoError(t, h.c.ReloadConfigString(h.config()+"punchy:\n punch: true\n").Err)
  131. assert.False(t, dropped(client, 500*time.Millisecond), "an unchanged sshd was restarted")
  132. }
  133. // Every key the server reads restarts it when it changes
  134. func TestSSHDReload_ChangedConfigRestarts(t *testing.T) {
  135. cases := map[string]func(t *testing.T, h *sshdReloadHarness){
  136. "listen": func(t *testing.T, h *sshdReloadHarness) { h.listen = "localhost:0" },
  137. "authorized_users": func(t *testing.T, h *sshdReloadHarness) { h.users = append(h.users, "other") },
  138. "trusted_cas": func(t *testing.T, h *sshdReloadHarness) { h.extra = " trusted_cas: []\n" },
  139. "host_key": func(t *testing.T, h *sshdReloadHarness) {
  140. h.keyFile = filepath.Join(t.TempDir(), "other_host_key")
  141. h.writeHostKey(t, newEd25519Key(t))
  142. },
  143. }
  144. for name, change := range cases {
  145. t.Run(name, func(t *testing.T) {
  146. h := newSSHDReloadHarness(t)
  147. client, _ := h.connect(t)
  148. change(t, h)
  149. require.NoError(t, h.c.ReloadConfigString(h.config()).Err)
  150. assert.True(t, dropped(client, 5*time.Second), "a changed sshd config was not applied")
  151. require.Eventually(t, h.server.Running, 5*time.Second, 10*time.Millisecond)
  152. h.connect(t)
  153. })
  154. }
  155. }
  156. // The config can stay the same while the host key file it names changes. New connections get the new key, open
  157. // sessions are left alone
  158. func TestSSHDReload_ChangedHostKeyFile(t *testing.T) {
  159. h := newSSHDReloadHarness(t)
  160. client, _ := h.connect(t)
  161. want := h.writeHostKey(t, newEd25519Key(t))
  162. require.NoError(t, h.c.ReloadConfigString(h.config()).Err)
  163. _, got := h.connect(t)
  164. assert.Equal(t, want.Marshal(), got.Marshal(), "a new host key was not applied")
  165. assert.False(t, dropped(client, 500*time.Millisecond), "a new host key restarted sshd")
  166. }
  167. // A host key of another algorithm replaces the old one rather than being offered next to it
  168. func TestSSHDReload_HostKeyAlgorithmChange(t *testing.T) {
  169. h := newSSHDReloadHarness(t)
  170. h.connect(t)
  171. rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
  172. require.NoError(t, err)
  173. want := h.writeHostKey(t, rsaKey)
  174. require.NoError(t, h.c.ReloadConfigString(h.config()).Err)
  175. _, got := h.connect(t)
  176. assert.Equal(t, want.Marshal(), got.Marshal())
  177. _, _, err = h.dial(ssh.KeyAlgoED25519)
  178. assert.Error(t, err, "the old ed25519 host key is still offered")
  179. }
  180. // A server that isn't running, say its port was busy, is tried again on every reload as before
  181. func TestSSHDReload_NotRunningRestarts(t *testing.T) {
  182. h := newSSHDReloadHarness(t)
  183. h.server.Stop()
  184. require.Eventually(t, func() bool { return !h.server.Running() }, 5*time.Second, 10*time.Millisecond)
  185. require.NoError(t, h.c.ReloadConfigString(h.config()).Err)
  186. require.Eventually(t, h.server.Running, 5*time.Second, 10*time.Millisecond)
  187. h.connect(t)
  188. }
  189. // A host key that no longer loads stops sshd, the same as a config that doesn't
  190. func TestSSHDReload_BadHostKeyFileStops(t *testing.T) {
  191. h := newSSHDReloadHarness(t)
  192. h.connect(t)
  193. require.NoError(t, os.WriteFile(h.keyFile, []byte("not a key"), 0o600))
  194. assert.True(t, h.c.ReloadConfigString(h.config()).Failed)
  195. require.Eventually(t, func() bool { return !h.server.Running() }, 5*time.Second, 10*time.Millisecond)
  196. }
  197. // A trusted CA or authorized user that is skipped with a warning fails the reload, the valid ones are still used
  198. func TestSSHDReload_SkippedEntriesFail(t *testing.T) {
  199. cases := map[string]string{
  200. "bad trusted ca": " trusted_cas: [nope]\n",
  201. "user entry not a map": " - nope\n",
  202. "user missing": " - keys: [nope]\n",
  203. "bad key": " - user: other\n keys: nope\n",
  204. "key in a list not a string": " - user: other\n keys: [5]\n",
  205. "bad key in a list": " - user: other\n keys: [nope]\n",
  206. "keys missing": " - user: other\n",
  207. }
  208. for name, extra := range cases {
  209. t.Run(name, func(t *testing.T) {
  210. h := newSSHDReloadHarness(t)
  211. h.extra = extra
  212. res := h.c.ReloadConfigString(h.config())
  213. require.NoError(t, res.Err)
  214. assert.True(t, res.Failed)
  215. require.Eventually(t, h.server.Running, 5*time.Second, 10*time.Millisecond)
  216. h.connect(t)
  217. })
  218. }
  219. }
  220. // TestSSHExecExitStatusReflectsTheCommand: an exec request exits 1 when the command
  221. // returned an error and 0 otherwise, with the command's output either way.
  222. func TestSSHExecExitStatusReflectsTheCommand(t *testing.T) {
  223. h := newSSHDReloadHarness(t)
  224. h.reg.Register(&commands.Command{
  225. Name: "fails",
  226. Callback: func(fs any, a []string, w commands.StringWriter) error {
  227. _ = w.WriteLine("nope")
  228. return errors.New("failed")
  229. },
  230. })
  231. client, _ := h.connect(t)
  232. sess, err := client.NewSession()
  233. require.NoError(t, err)
  234. out, err := sess.CombinedOutput("fails")
  235. var exit *ssh.ExitError
  236. require.ErrorAs(t, err, &exit)
  237. assert.Equal(t, 1, exit.ExitStatus())
  238. assert.Equal(t, "nope\n", string(out))
  239. sess, err = client.NewSession()
  240. require.NoError(t, err)
  241. out, err = sess.CombinedOutput("help fails")
  242. require.NoError(t, err)
  243. assert.Equal(t, "fails - \n", string(out))
  244. // A word that is not a command is a failure too, with the command list as before.
  245. sess, err = client.NewSession()
  246. require.NoError(t, err)
  247. out, err = sess.CombinedOutput("nope")
  248. require.ErrorAs(t, err, &exit)
  249. assert.Equal(t, 1, exit.ExitStatus())
  250. assert.True(t, strings.HasPrefix(string(out), "did not understand: nope\nAvailable commands:\n"), string(out))
  251. }