sshd_reload_test.go 7.4 KB

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