1
0

sshd_reload_test.go 9.2 KB

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