tailssh_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build linux || darwin
  5. // +build linux darwin
  6. package tailssh
  7. import (
  8. "bytes"
  9. "crypto/sha256"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "net"
  14. "net/http"
  15. "net/http/httptest"
  16. "os"
  17. "os/exec"
  18. "os/user"
  19. "reflect"
  20. "strings"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "inet.af/netaddr"
  25. "tailscale.com/ipn/ipnlocal"
  26. "tailscale.com/ipn/store/mem"
  27. "tailscale.com/net/tsdial"
  28. "tailscale.com/tailcfg"
  29. "tailscale.com/tempfork/gliderlabs/ssh"
  30. "tailscale.com/tstest"
  31. "tailscale.com/types/logger"
  32. "tailscale.com/util/cibuild"
  33. "tailscale.com/util/lineread"
  34. "tailscale.com/wgengine"
  35. )
  36. func TestMatchRule(t *testing.T) {
  37. someAction := new(tailcfg.SSHAction)
  38. tests := []struct {
  39. name string
  40. rule *tailcfg.SSHRule
  41. ci *sshConnInfo
  42. wantErr error
  43. wantUser string
  44. }{
  45. {
  46. name: "invalid-conn",
  47. rule: &tailcfg.SSHRule{
  48. Action: someAction,
  49. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  50. SSHUsers: map[string]string{
  51. "*": "ubuntu",
  52. },
  53. },
  54. wantErr: errInvalidConn,
  55. },
  56. {
  57. name: "nil-rule",
  58. ci: &sshConnInfo{},
  59. rule: nil,
  60. wantErr: errNilRule,
  61. },
  62. {
  63. name: "nil-action",
  64. ci: &sshConnInfo{},
  65. rule: &tailcfg.SSHRule{},
  66. wantErr: errNilAction,
  67. },
  68. {
  69. name: "expired",
  70. rule: &tailcfg.SSHRule{
  71. Action: someAction,
  72. RuleExpires: timePtr(time.Unix(100, 0)),
  73. },
  74. ci: &sshConnInfo{},
  75. wantErr: errRuleExpired,
  76. },
  77. {
  78. name: "no-principal",
  79. rule: &tailcfg.SSHRule{
  80. Action: someAction,
  81. SSHUsers: map[string]string{
  82. "*": "ubuntu",
  83. }},
  84. ci: &sshConnInfo{},
  85. wantErr: errPrincipalMatch,
  86. },
  87. {
  88. name: "no-user-match",
  89. rule: &tailcfg.SSHRule{
  90. Action: someAction,
  91. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  92. },
  93. ci: &sshConnInfo{sshUser: "alice"},
  94. wantErr: errUserMatch,
  95. },
  96. {
  97. name: "ok-wildcard",
  98. rule: &tailcfg.SSHRule{
  99. Action: someAction,
  100. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  101. SSHUsers: map[string]string{
  102. "*": "ubuntu",
  103. },
  104. },
  105. ci: &sshConnInfo{sshUser: "alice"},
  106. wantUser: "ubuntu",
  107. },
  108. {
  109. name: "ok-wildcard-and-nil-principal",
  110. rule: &tailcfg.SSHRule{
  111. Action: someAction,
  112. Principals: []*tailcfg.SSHPrincipal{
  113. nil, // don't crash on this
  114. {Any: true},
  115. },
  116. SSHUsers: map[string]string{
  117. "*": "ubuntu",
  118. },
  119. },
  120. ci: &sshConnInfo{sshUser: "alice"},
  121. wantUser: "ubuntu",
  122. },
  123. {
  124. name: "ok-exact",
  125. rule: &tailcfg.SSHRule{
  126. Action: someAction,
  127. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  128. SSHUsers: map[string]string{
  129. "*": "ubuntu",
  130. "alice": "thealice",
  131. },
  132. },
  133. ci: &sshConnInfo{sshUser: "alice"},
  134. wantUser: "thealice",
  135. },
  136. {
  137. name: "no-users-for-reject",
  138. rule: &tailcfg.SSHRule{
  139. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  140. Action: &tailcfg.SSHAction{Reject: true},
  141. },
  142. ci: &sshConnInfo{sshUser: "alice"},
  143. },
  144. {
  145. name: "match-principal-node-ip",
  146. rule: &tailcfg.SSHRule{
  147. Action: someAction,
  148. Principals: []*tailcfg.SSHPrincipal{{NodeIP: "1.2.3.4"}},
  149. SSHUsers: map[string]string{"*": "ubuntu"},
  150. },
  151. ci: &sshConnInfo{src: netaddr.MustParseIPPort("1.2.3.4:30343")},
  152. wantUser: "ubuntu",
  153. },
  154. {
  155. name: "match-principal-node-id",
  156. rule: &tailcfg.SSHRule{
  157. Action: someAction,
  158. Principals: []*tailcfg.SSHPrincipal{{Node: "some-node-ID"}},
  159. SSHUsers: map[string]string{"*": "ubuntu"},
  160. },
  161. ci: &sshConnInfo{node: &tailcfg.Node{StableID: "some-node-ID"}},
  162. wantUser: "ubuntu",
  163. },
  164. {
  165. name: "match-principal-userlogin",
  166. rule: &tailcfg.SSHRule{
  167. Action: someAction,
  168. Principals: []*tailcfg.SSHPrincipal{{UserLogin: "[email protected]"}},
  169. SSHUsers: map[string]string{"*": "ubuntu"},
  170. },
  171. ci: &sshConnInfo{uprof: &tailcfg.UserProfile{LoginName: "[email protected]"}},
  172. wantUser: "ubuntu",
  173. },
  174. {
  175. name: "ssh-user-equal",
  176. rule: &tailcfg.SSHRule{
  177. Action: someAction,
  178. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  179. SSHUsers: map[string]string{
  180. "*": "=",
  181. },
  182. },
  183. ci: &sshConnInfo{sshUser: "alice"},
  184. wantUser: "alice",
  185. },
  186. }
  187. for _, tt := range tests {
  188. t.Run(tt.name, func(t *testing.T) {
  189. c := &conn{
  190. info: tt.ci,
  191. srv: &server{logf: t.Logf},
  192. }
  193. got, gotUser, err := c.matchRule(tt.rule, nil)
  194. if err != tt.wantErr {
  195. t.Errorf("err = %v; want %v", err, tt.wantErr)
  196. }
  197. if gotUser != tt.wantUser {
  198. t.Errorf("user = %q; want %q", gotUser, tt.wantUser)
  199. }
  200. if err == nil && got == nil {
  201. t.Errorf("expected non-nil action on success")
  202. }
  203. })
  204. }
  205. }
  206. func timePtr(t time.Time) *time.Time { return &t }
  207. func TestSSH(t *testing.T) {
  208. var logf logger.Logf = t.Logf
  209. eng, err := wgengine.NewFakeUserspaceEngine(logf, 0)
  210. if err != nil {
  211. t.Fatal(err)
  212. }
  213. lb, err := ipnlocal.NewLocalBackend(logf, "",
  214. new(mem.Store),
  215. new(tsdial.Dialer),
  216. eng, 0)
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. defer lb.Shutdown()
  221. dir := t.TempDir()
  222. lb.SetVarRoot(dir)
  223. srv := &server{
  224. lb: lb,
  225. logf: logf,
  226. }
  227. sc, err := srv.newConn()
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. // Remove the auth checks for the test
  232. sc.insecureSkipTailscaleAuth = true
  233. u, err := user.Current()
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. sc.localUser = u
  238. sc.info = &sshConnInfo{
  239. sshUser: "test",
  240. src: netaddr.MustParseIPPort("1.2.3.4:32342"),
  241. dst: netaddr.MustParseIPPort("1.2.3.5:22"),
  242. node: &tailcfg.Node{},
  243. uprof: &tailcfg.UserProfile{},
  244. }
  245. sc.finalAction = &tailcfg.SSHAction{Accept: true}
  246. sc.Handler = func(s ssh.Session) {
  247. sc.newSSHSession(s).run()
  248. }
  249. ln, err := net.Listen("tcp4", "127.0.0.1:0")
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. defer ln.Close()
  254. port := ln.Addr().(*net.TCPAddr).Port
  255. go func() {
  256. for {
  257. c, err := ln.Accept()
  258. if err != nil {
  259. if !errors.Is(err, net.ErrClosed) {
  260. t.Errorf("Accept: %v", err)
  261. }
  262. return
  263. }
  264. go sc.HandleConn(c)
  265. }
  266. }()
  267. execSSH := func(args ...string) *exec.Cmd {
  268. cmd := exec.Command("ssh",
  269. "-F",
  270. "none",
  271. "-v",
  272. "-p", fmt.Sprint(port),
  273. "-o", "StrictHostKeyChecking=no",
  274. "[email protected]")
  275. cmd.Args = append(cmd.Args, args...)
  276. return cmd
  277. }
  278. t.Run("env", func(t *testing.T) {
  279. if cibuild.On() {
  280. t.Skip("Skipping for now; see https://github.com/tailscale/tailscale/issues/4051")
  281. }
  282. cmd := execSSH("LANG=foo env")
  283. cmd.Env = append(os.Environ(), "LOCAL_ENV=bar")
  284. got, err := cmd.CombinedOutput()
  285. if err != nil {
  286. t.Fatal(err, string(got))
  287. }
  288. m := parseEnv(got)
  289. if got := m["USER"]; got == "" || got != u.Username {
  290. t.Errorf("USER = %q; want %q", got, u.Username)
  291. }
  292. if got := m["HOME"]; got == "" || got != u.HomeDir {
  293. t.Errorf("HOME = %q; want %q", got, u.HomeDir)
  294. }
  295. if got := m["PWD"]; got == "" || got != u.HomeDir {
  296. t.Errorf("PWD = %q; want %q", got, u.HomeDir)
  297. }
  298. if got := m["SHELL"]; got == "" {
  299. t.Errorf("no SHELL")
  300. }
  301. if got, want := m["LANG"], "foo"; got != want {
  302. t.Errorf("LANG = %q; want %q", got, want)
  303. }
  304. if got := m["LOCAL_ENV"]; got != "" {
  305. t.Errorf("LOCAL_ENV leaked over ssh: %v", got)
  306. }
  307. t.Logf("got: %+v", m)
  308. })
  309. t.Run("stdout_stderr", func(t *testing.T) {
  310. cmd := execSSH("sh", "-c", "echo foo; echo bar >&2")
  311. var outBuf, errBuf bytes.Buffer
  312. cmd.Stdout = &outBuf
  313. cmd.Stderr = &errBuf
  314. if err := cmd.Run(); err != nil {
  315. t.Fatal(err)
  316. }
  317. t.Logf("Got: %q and %q", outBuf.Bytes(), errBuf.Bytes())
  318. // TODO: figure out why these aren't right. should be
  319. // "foo\n" and "bar\n", not "\n" and "bar\n".
  320. })
  321. t.Run("stdin", func(t *testing.T) {
  322. if cibuild.On() {
  323. t.Skip("Skipping for now; see https://github.com/tailscale/tailscale/issues/4051")
  324. }
  325. cmd := execSSH("cat")
  326. var outBuf bytes.Buffer
  327. cmd.Stdout = &outBuf
  328. const str = "foo\nbar\n"
  329. cmd.Stdin = strings.NewReader(str)
  330. if err := cmd.Run(); err != nil {
  331. t.Fatal(err)
  332. }
  333. if got := outBuf.String(); got != str {
  334. t.Errorf("got %q; want %q", got, str)
  335. }
  336. })
  337. }
  338. func parseEnv(out []byte) map[string]string {
  339. e := map[string]string{}
  340. lineread.Reader(bytes.NewReader(out), func(line []byte) error {
  341. i := bytes.IndexByte(line, '=')
  342. if i == -1 {
  343. return nil
  344. }
  345. e[string(line[:i])] = string(line[i+1:])
  346. return nil
  347. })
  348. return e
  349. }
  350. func TestPublicKeyFetching(t *testing.T) {
  351. var reqsTotal, reqsIfNoneMatchHit, reqsIfNoneMatchMiss int32
  352. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  353. atomic.AddInt32((&reqsTotal), 1)
  354. etag := fmt.Sprintf("W/%q", sha256.Sum256([]byte(r.URL.Path)))
  355. w.Header().Set("Etag", etag)
  356. if v := r.Header.Get("If-None-Match"); v != "" {
  357. if v == etag {
  358. atomic.AddInt32(&reqsIfNoneMatchHit, 1)
  359. w.WriteHeader(304)
  360. return
  361. }
  362. atomic.AddInt32(&reqsIfNoneMatchMiss, 1)
  363. }
  364. io.WriteString(w, "foo\nbar\n"+string(r.URL.Path)+"\n")
  365. }))
  366. ts.StartTLS()
  367. defer ts.Close()
  368. keys := ts.URL
  369. clock := &tstest.Clock{}
  370. srv := &server{
  371. pubKeyHTTPClient: ts.Client(),
  372. timeNow: clock.Now,
  373. }
  374. for i := 0; i < 2; i++ {
  375. got, err := srv.fetchPublicKeysURL(keys + "/alice.keys")
  376. if err != nil {
  377. t.Fatal(err)
  378. }
  379. if want := []string{"foo", "bar", "/alice.keys"}; !reflect.DeepEqual(got, want) {
  380. t.Errorf("got %q; want %q", got, want)
  381. }
  382. }
  383. if got, want := atomic.LoadInt32(&reqsTotal), int32(1); got != want {
  384. t.Errorf("got %d requests; want %d", got, want)
  385. }
  386. if got, want := atomic.LoadInt32(&reqsIfNoneMatchHit), int32(0); got != want {
  387. t.Errorf("got %d etag hits; want %d", got, want)
  388. }
  389. clock.Advance(5 * time.Minute)
  390. got, err := srv.fetchPublicKeysURL(keys + "/alice.keys")
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. if want := []string{"foo", "bar", "/alice.keys"}; !reflect.DeepEqual(got, want) {
  395. t.Errorf("got %q; want %q", got, want)
  396. }
  397. if got, want := atomic.LoadInt32(&reqsTotal), int32(2); got != want {
  398. t.Errorf("got %d requests; want %d", got, want)
  399. }
  400. if got, want := atomic.LoadInt32(&reqsIfNoneMatchHit), int32(1); got != want {
  401. t.Errorf("got %d etag hits; want %d", got, want)
  402. }
  403. if got, want := atomic.LoadInt32(&reqsIfNoneMatchMiss), int32(0); got != want {
  404. t.Errorf("got %d etag misses; want %d", got, want)
  405. }
  406. }
  407. func TestExpandPublicKeyURL(t *testing.T) {
  408. c := &conn{
  409. info: &sshConnInfo{
  410. uprof: &tailcfg.UserProfile{
  411. LoginName: "[email protected]",
  412. },
  413. },
  414. }
  415. if got, want := c.expandPublicKeyURL("foo"), "foo"; got != want {
  416. t.Errorf("basic: got %q; want %q", got, want)
  417. }
  418. if got, want := c.expandPublicKeyURL("https://example.com/$LOGINNAME_LOCALPART.keys"), "https://example.com/bar.keys"; got != want {
  419. t.Errorf("localpart: got %q; want %q", got, want)
  420. }
  421. if got, want := c.expandPublicKeyURL("https://example.com/keys?email=$LOGINNAME_EMAIL"), "https://example.com/[email protected]"; got != want {
  422. t.Errorf("email: got %q; want %q", got, want)
  423. }
  424. c.info = new(sshConnInfo)
  425. if got, want := c.expandPublicKeyURL("https://example.com/keys?email=$LOGINNAME_EMAIL"), "https://example.com/keys?email="; got != want {
  426. t.Errorf("on empty: got %q; want %q", got, want)
  427. }
  428. }
  429. func TestAcceptEnvPair(t *testing.T) {
  430. tests := []struct {
  431. in string
  432. want bool
  433. }{
  434. {"TERM=x", true},
  435. {"term=x", false},
  436. {"TERM", false},
  437. {"LC_FOO=x", true},
  438. {"LD_PRELOAD=naah", false},
  439. {"TERM=screen-256color", true},
  440. }
  441. for _, tt := range tests {
  442. if got := acceptEnvPair(tt.in); got != tt.want {
  443. t.Errorf("for %q, got %v; want %v", tt.in, got, tt.want)
  444. }
  445. }
  446. }