tailssh_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. package tailssh
  6. import (
  7. "bytes"
  8. "crypto/ed25519"
  9. "crypto/rand"
  10. "crypto/sha256"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "net/http"
  17. "net/http/httptest"
  18. "net/netip"
  19. "os"
  20. "os/exec"
  21. "os/user"
  22. "reflect"
  23. "runtime"
  24. "strings"
  25. "sync"
  26. "sync/atomic"
  27. "testing"
  28. "time"
  29. gossh "github.com/tailscale/golang-x-crypto/ssh"
  30. "tailscale.com/ipn/ipnlocal"
  31. "tailscale.com/ipn/store/mem"
  32. "tailscale.com/net/nettest"
  33. "tailscale.com/net/tsdial"
  34. "tailscale.com/tailcfg"
  35. "tailscale.com/tempfork/gliderlabs/ssh"
  36. "tailscale.com/tstest"
  37. "tailscale.com/types/logger"
  38. "tailscale.com/types/netmap"
  39. "tailscale.com/util/cibuild"
  40. "tailscale.com/util/lineread"
  41. "tailscale.com/util/must"
  42. "tailscale.com/util/strs"
  43. "tailscale.com/version/distro"
  44. "tailscale.com/wgengine"
  45. )
  46. func TestMatchRule(t *testing.T) {
  47. someAction := new(tailcfg.SSHAction)
  48. tests := []struct {
  49. name string
  50. rule *tailcfg.SSHRule
  51. ci *sshConnInfo
  52. wantErr error
  53. wantUser string
  54. }{
  55. {
  56. name: "invalid-conn",
  57. rule: &tailcfg.SSHRule{
  58. Action: someAction,
  59. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  60. SSHUsers: map[string]string{
  61. "*": "ubuntu",
  62. },
  63. },
  64. wantErr: errInvalidConn,
  65. },
  66. {
  67. name: "nil-rule",
  68. ci: &sshConnInfo{},
  69. rule: nil,
  70. wantErr: errNilRule,
  71. },
  72. {
  73. name: "nil-action",
  74. ci: &sshConnInfo{},
  75. rule: &tailcfg.SSHRule{},
  76. wantErr: errNilAction,
  77. },
  78. {
  79. name: "expired",
  80. rule: &tailcfg.SSHRule{
  81. Action: someAction,
  82. RuleExpires: timePtr(time.Unix(100, 0)),
  83. },
  84. ci: &sshConnInfo{},
  85. wantErr: errRuleExpired,
  86. },
  87. {
  88. name: "no-principal",
  89. rule: &tailcfg.SSHRule{
  90. Action: someAction,
  91. SSHUsers: map[string]string{
  92. "*": "ubuntu",
  93. }},
  94. ci: &sshConnInfo{},
  95. wantErr: errPrincipalMatch,
  96. },
  97. {
  98. name: "no-user-match",
  99. rule: &tailcfg.SSHRule{
  100. Action: someAction,
  101. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  102. },
  103. ci: &sshConnInfo{sshUser: "alice"},
  104. wantErr: errUserMatch,
  105. },
  106. {
  107. name: "ok-wildcard",
  108. rule: &tailcfg.SSHRule{
  109. Action: someAction,
  110. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  111. SSHUsers: map[string]string{
  112. "*": "ubuntu",
  113. },
  114. },
  115. ci: &sshConnInfo{sshUser: "alice"},
  116. wantUser: "ubuntu",
  117. },
  118. {
  119. name: "ok-wildcard-and-nil-principal",
  120. rule: &tailcfg.SSHRule{
  121. Action: someAction,
  122. Principals: []*tailcfg.SSHPrincipal{
  123. nil, // don't crash on this
  124. {Any: true},
  125. },
  126. SSHUsers: map[string]string{
  127. "*": "ubuntu",
  128. },
  129. },
  130. ci: &sshConnInfo{sshUser: "alice"},
  131. wantUser: "ubuntu",
  132. },
  133. {
  134. name: "ok-exact",
  135. rule: &tailcfg.SSHRule{
  136. Action: someAction,
  137. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  138. SSHUsers: map[string]string{
  139. "*": "ubuntu",
  140. "alice": "thealice",
  141. },
  142. },
  143. ci: &sshConnInfo{sshUser: "alice"},
  144. wantUser: "thealice",
  145. },
  146. {
  147. name: "no-users-for-reject",
  148. rule: &tailcfg.SSHRule{
  149. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  150. Action: &tailcfg.SSHAction{Reject: true},
  151. },
  152. ci: &sshConnInfo{sshUser: "alice"},
  153. },
  154. {
  155. name: "match-principal-node-ip",
  156. rule: &tailcfg.SSHRule{
  157. Action: someAction,
  158. Principals: []*tailcfg.SSHPrincipal{{NodeIP: "1.2.3.4"}},
  159. SSHUsers: map[string]string{"*": "ubuntu"},
  160. },
  161. ci: &sshConnInfo{src: netip.MustParseAddrPort("1.2.3.4:30343")},
  162. wantUser: "ubuntu",
  163. },
  164. {
  165. name: "match-principal-node-id",
  166. rule: &tailcfg.SSHRule{
  167. Action: someAction,
  168. Principals: []*tailcfg.SSHPrincipal{{Node: "some-node-ID"}},
  169. SSHUsers: map[string]string{"*": "ubuntu"},
  170. },
  171. ci: &sshConnInfo{node: &tailcfg.Node{StableID: "some-node-ID"}},
  172. wantUser: "ubuntu",
  173. },
  174. {
  175. name: "match-principal-userlogin",
  176. rule: &tailcfg.SSHRule{
  177. Action: someAction,
  178. Principals: []*tailcfg.SSHPrincipal{{UserLogin: "[email protected]"}},
  179. SSHUsers: map[string]string{"*": "ubuntu"},
  180. },
  181. ci: &sshConnInfo{uprof: tailcfg.UserProfile{LoginName: "[email protected]"}},
  182. wantUser: "ubuntu",
  183. },
  184. {
  185. name: "ssh-user-equal",
  186. rule: &tailcfg.SSHRule{
  187. Action: someAction,
  188. Principals: []*tailcfg.SSHPrincipal{{Any: true}},
  189. SSHUsers: map[string]string{
  190. "*": "=",
  191. },
  192. },
  193. ci: &sshConnInfo{sshUser: "alice"},
  194. wantUser: "alice",
  195. },
  196. }
  197. for _, tt := range tests {
  198. t.Run(tt.name, func(t *testing.T) {
  199. c := &conn{
  200. info: tt.ci,
  201. srv: &server{logf: t.Logf},
  202. }
  203. got, gotUser, err := c.matchRule(tt.rule, nil)
  204. if err != tt.wantErr {
  205. t.Errorf("err = %v; want %v", err, tt.wantErr)
  206. }
  207. if gotUser != tt.wantUser {
  208. t.Errorf("user = %q; want %q", gotUser, tt.wantUser)
  209. }
  210. if err == nil && got == nil {
  211. t.Errorf("expected non-nil action on success")
  212. }
  213. })
  214. }
  215. }
  216. func timePtr(t time.Time) *time.Time { return &t }
  217. // localState implements ipnLocalBackend for testing.
  218. type localState struct {
  219. sshEnabled bool
  220. matchingRule *tailcfg.SSHRule
  221. // serverActions is a map of the action name to the action.
  222. // It is served for paths like https://unused/ssh-action/<action-name>.
  223. // The action name is the last part of the action URL.
  224. serverActions map[string]*tailcfg.SSHAction
  225. }
  226. var (
  227. currentUser = os.Getenv("USER") // Use the current user for the test.
  228. testSigner gossh.Signer
  229. testSignerOnce sync.Once
  230. )
  231. func (ts *localState) GetSSH_HostKeys() ([]gossh.Signer, error) {
  232. testSignerOnce.Do(func() {
  233. _, priv, err := ed25519.GenerateKey(rand.Reader)
  234. if err != nil {
  235. panic(err)
  236. }
  237. s, err := gossh.NewSignerFromSigner(priv)
  238. if err != nil {
  239. panic(err)
  240. }
  241. testSigner = s
  242. })
  243. return []gossh.Signer{testSigner}, nil
  244. }
  245. func (ts *localState) ShouldRunSSH() bool {
  246. return ts.sshEnabled
  247. }
  248. func (ts *localState) NetMap() *netmap.NetworkMap {
  249. var policy *tailcfg.SSHPolicy
  250. if ts.matchingRule != nil {
  251. policy = &tailcfg.SSHPolicy{
  252. Rules: []*tailcfg.SSHRule{
  253. ts.matchingRule,
  254. },
  255. }
  256. }
  257. return &netmap.NetworkMap{
  258. SelfNode: &tailcfg.Node{
  259. ID: 1,
  260. },
  261. SSHPolicy: policy,
  262. }
  263. }
  264. func (ts *localState) WhoIs(ipp netip.AddrPort) (n *tailcfg.Node, u tailcfg.UserProfile, ok bool) {
  265. return &tailcfg.Node{
  266. ID: 2,
  267. StableID: "peer-id",
  268. }, tailcfg.UserProfile{
  269. LoginName: "peer",
  270. }, true
  271. }
  272. func (ts *localState) DoNoiseRequest(req *http.Request) (*http.Response, error) {
  273. rec := httptest.NewRecorder()
  274. k, ok := strs.CutPrefix(req.URL.Path, "/ssh-action/")
  275. if !ok {
  276. rec.WriteHeader(http.StatusNotFound)
  277. }
  278. a, ok := ts.serverActions[k]
  279. if !ok {
  280. rec.WriteHeader(http.StatusNotFound)
  281. return rec.Result(), nil
  282. }
  283. rec.WriteHeader(http.StatusOK)
  284. if err := json.NewEncoder(rec).Encode(a); err != nil {
  285. return nil, err
  286. }
  287. return rec.Result(), nil
  288. }
  289. func (ts *localState) TailscaleVarRoot() string {
  290. return ""
  291. }
  292. func newSSHRule(action *tailcfg.SSHAction) *tailcfg.SSHRule {
  293. return &tailcfg.SSHRule{
  294. SSHUsers: map[string]string{
  295. "*": currentUser,
  296. },
  297. Action: action,
  298. Principals: []*tailcfg.SSHPrincipal{
  299. {
  300. Any: true,
  301. },
  302. },
  303. }
  304. }
  305. func TestSSHAuthFlow(t *testing.T) {
  306. if runtime.GOOS != "linux" {
  307. t.Skip("Not running on Linux, skipping")
  308. }
  309. acceptRule := newSSHRule(&tailcfg.SSHAction{
  310. Accept: true,
  311. Message: "Welcome to Tailscale SSH!",
  312. })
  313. rejectRule := newSSHRule(&tailcfg.SSHAction{
  314. Reject: true,
  315. Message: "Go Away!",
  316. })
  317. tests := []struct {
  318. name string
  319. sshUser string // defaults to alice
  320. state *localState
  321. wantBanners []string
  322. usesPassword bool
  323. authErr bool
  324. }{
  325. {
  326. name: "no-policy",
  327. state: &localState{
  328. sshEnabled: true,
  329. },
  330. authErr: true,
  331. },
  332. {
  333. name: "accept",
  334. state: &localState{
  335. sshEnabled: true,
  336. matchingRule: acceptRule,
  337. },
  338. wantBanners: []string{"Welcome to Tailscale SSH!"},
  339. },
  340. {
  341. name: "reject",
  342. state: &localState{
  343. sshEnabled: true,
  344. matchingRule: rejectRule,
  345. },
  346. wantBanners: []string{"Go Away!"},
  347. authErr: true,
  348. },
  349. {
  350. name: "simple-check",
  351. state: &localState{
  352. sshEnabled: true,
  353. matchingRule: newSSHRule(&tailcfg.SSHAction{
  354. HoldAndDelegate: "https://unused/ssh-action/accept",
  355. }),
  356. serverActions: map[string]*tailcfg.SSHAction{
  357. "accept": acceptRule.Action,
  358. },
  359. },
  360. wantBanners: []string{"Welcome to Tailscale SSH!"},
  361. },
  362. {
  363. name: "multi-check",
  364. state: &localState{
  365. sshEnabled: true,
  366. matchingRule: newSSHRule(&tailcfg.SSHAction{
  367. Message: "First",
  368. HoldAndDelegate: "https://unused/ssh-action/check1",
  369. }),
  370. serverActions: map[string]*tailcfg.SSHAction{
  371. "check1": {
  372. Message: "url-here",
  373. HoldAndDelegate: "https://unused/ssh-action/check2",
  374. },
  375. "check2": acceptRule.Action,
  376. },
  377. },
  378. wantBanners: []string{"First", "url-here", "Welcome to Tailscale SSH!"},
  379. },
  380. {
  381. name: "check-reject",
  382. state: &localState{
  383. sshEnabled: true,
  384. matchingRule: newSSHRule(&tailcfg.SSHAction{
  385. Message: "First",
  386. HoldAndDelegate: "https://unused/ssh-action/reject",
  387. }),
  388. serverActions: map[string]*tailcfg.SSHAction{
  389. "reject": rejectRule.Action,
  390. },
  391. },
  392. wantBanners: []string{"First", "Go Away!"},
  393. authErr: true,
  394. },
  395. {
  396. name: "force-password-auth",
  397. sshUser: "alice+password",
  398. state: &localState{
  399. sshEnabled: true,
  400. matchingRule: acceptRule,
  401. },
  402. usesPassword: true,
  403. wantBanners: []string{"Welcome to Tailscale SSH!"},
  404. },
  405. }
  406. s := &server{
  407. logf: logger.Discard,
  408. }
  409. defer s.Shutdown()
  410. src, dst := must.Get(netip.ParseAddrPort("100.100.100.101:2231")), must.Get(netip.ParseAddrPort("100.100.100.102:22"))
  411. for _, tc := range tests {
  412. t.Run(tc.name, func(t *testing.T) {
  413. sc, dc := nettest.NewTCPConn(src, dst, 1024)
  414. s.lb = tc.state
  415. sshUser := "alice"
  416. if tc.sshUser != "" {
  417. sshUser = tc.sshUser
  418. }
  419. var passwordUsed atomic.Bool
  420. cfg := &gossh.ClientConfig{
  421. User: sshUser,
  422. HostKeyCallback: gossh.InsecureIgnoreHostKey(),
  423. Auth: []gossh.AuthMethod{
  424. gossh.PasswordCallback(func() (secret string, err error) {
  425. if !tc.usesPassword {
  426. t.Error("unexpected use of PasswordCallback")
  427. return "", errors.New("unexpected use of PasswordCallback")
  428. }
  429. passwordUsed.Store(true)
  430. return "any-pass", nil
  431. }),
  432. },
  433. BannerCallback: func(message string) error {
  434. if len(tc.wantBanners) == 0 {
  435. t.Errorf("unexpected banner: %q", message)
  436. } else if message != tc.wantBanners[0] {
  437. t.Errorf("banner = %q; want %q", message, tc.wantBanners[0])
  438. } else {
  439. t.Logf("banner = %q", message)
  440. tc.wantBanners = tc.wantBanners[1:]
  441. }
  442. return nil
  443. },
  444. }
  445. var wg sync.WaitGroup
  446. wg.Add(1)
  447. go func() {
  448. defer wg.Done()
  449. c, chans, reqs, err := gossh.NewClientConn(sc, sc.RemoteAddr().String(), cfg)
  450. if err != nil {
  451. if !tc.authErr {
  452. t.Errorf("client: %v", err)
  453. }
  454. return
  455. } else if tc.authErr {
  456. c.Close()
  457. t.Errorf("client: expected error, got nil")
  458. return
  459. }
  460. client := gossh.NewClient(c, chans, reqs)
  461. defer client.Close()
  462. session, err := client.NewSession()
  463. if err != nil {
  464. t.Errorf("client: %v", err)
  465. return
  466. }
  467. defer session.Close()
  468. _, err = session.CombinedOutput("echo Ran echo!")
  469. if err != nil {
  470. t.Errorf("client: %v", err)
  471. }
  472. }()
  473. if err := s.HandleSSHConn(dc); err != nil {
  474. t.Errorf("unexpected error: %v", err)
  475. }
  476. wg.Wait()
  477. if len(tc.wantBanners) > 0 {
  478. t.Errorf("missing banners: %v", tc.wantBanners)
  479. }
  480. })
  481. }
  482. }
  483. func TestSSH(t *testing.T) {
  484. var logf logger.Logf = t.Logf
  485. eng, err := wgengine.NewFakeUserspaceEngine(logf, 0)
  486. if err != nil {
  487. t.Fatal(err)
  488. }
  489. lb, err := ipnlocal.NewLocalBackend(logf, "",
  490. new(mem.Store), "",
  491. new(tsdial.Dialer),
  492. eng, 0)
  493. if err != nil {
  494. t.Fatal(err)
  495. }
  496. defer lb.Shutdown()
  497. dir := t.TempDir()
  498. lb.SetVarRoot(dir)
  499. srv := &server{
  500. lb: lb,
  501. logf: logf,
  502. }
  503. sc, err := srv.newConn()
  504. if err != nil {
  505. t.Fatal(err)
  506. }
  507. // Remove the auth checks for the test
  508. sc.insecureSkipTailscaleAuth = true
  509. u, err := user.Current()
  510. if err != nil {
  511. t.Fatal(err)
  512. }
  513. sc.localUser = u
  514. sc.info = &sshConnInfo{
  515. sshUser: "test",
  516. src: netip.MustParseAddrPort("1.2.3.4:32342"),
  517. dst: netip.MustParseAddrPort("1.2.3.5:22"),
  518. node: &tailcfg.Node{},
  519. uprof: tailcfg.UserProfile{},
  520. }
  521. sc.finalAction = &tailcfg.SSHAction{Accept: true}
  522. sc.Handler = func(s ssh.Session) {
  523. sc.newSSHSession(s).run()
  524. }
  525. ln, err := net.Listen("tcp4", "127.0.0.1:0")
  526. if err != nil {
  527. t.Fatal(err)
  528. }
  529. defer ln.Close()
  530. port := ln.Addr().(*net.TCPAddr).Port
  531. go func() {
  532. for {
  533. c, err := ln.Accept()
  534. if err != nil {
  535. if !errors.Is(err, net.ErrClosed) {
  536. t.Errorf("Accept: %v", err)
  537. }
  538. return
  539. }
  540. go sc.HandleConn(c)
  541. }
  542. }()
  543. execSSH := func(args ...string) *exec.Cmd {
  544. cmd := exec.Command("ssh",
  545. "-F",
  546. "none",
  547. "-v",
  548. "-p", fmt.Sprint(port),
  549. "-o", "StrictHostKeyChecking=no",
  550. "[email protected]")
  551. cmd.Args = append(cmd.Args, args...)
  552. return cmd
  553. }
  554. t.Run("env", func(t *testing.T) {
  555. if cibuild.On() {
  556. t.Skip("Skipping for now; see https://github.com/tailscale/tailscale/issues/4051")
  557. }
  558. cmd := execSSH("LANG=foo env")
  559. cmd.Env = append(os.Environ(), "LOCAL_ENV=bar")
  560. got, err := cmd.CombinedOutput()
  561. if err != nil {
  562. t.Fatal(err, string(got))
  563. }
  564. m := parseEnv(got)
  565. if got := m["USER"]; got == "" || got != u.Username {
  566. t.Errorf("USER = %q; want %q", got, u.Username)
  567. }
  568. if got := m["HOME"]; got == "" || got != u.HomeDir {
  569. t.Errorf("HOME = %q; want %q", got, u.HomeDir)
  570. }
  571. if got := m["PWD"]; got == "" || got != u.HomeDir {
  572. t.Errorf("PWD = %q; want %q", got, u.HomeDir)
  573. }
  574. if got := m["SHELL"]; got == "" {
  575. t.Errorf("no SHELL")
  576. }
  577. if got, want := m["LANG"], "foo"; got != want {
  578. t.Errorf("LANG = %q; want %q", got, want)
  579. }
  580. if got := m["LOCAL_ENV"]; got != "" {
  581. t.Errorf("LOCAL_ENV leaked over ssh: %v", got)
  582. }
  583. t.Logf("got: %+v", m)
  584. })
  585. t.Run("stdout_stderr", func(t *testing.T) {
  586. cmd := execSSH("sh", "-c", "echo foo; echo bar >&2")
  587. var outBuf, errBuf bytes.Buffer
  588. cmd.Stdout = &outBuf
  589. cmd.Stderr = &errBuf
  590. if err := cmd.Run(); err != nil {
  591. t.Fatal(err)
  592. }
  593. t.Logf("Got: %q and %q", outBuf.Bytes(), errBuf.Bytes())
  594. // TODO: figure out why these aren't right. should be
  595. // "foo\n" and "bar\n", not "\n" and "bar\n".
  596. })
  597. t.Run("stdin", func(t *testing.T) {
  598. if cibuild.On() {
  599. t.Skip("Skipping for now; see https://github.com/tailscale/tailscale/issues/4051")
  600. }
  601. cmd := execSSH("cat")
  602. var outBuf bytes.Buffer
  603. cmd.Stdout = &outBuf
  604. const str = "foo\nbar\n"
  605. cmd.Stdin = strings.NewReader(str)
  606. if err := cmd.Run(); err != nil {
  607. t.Fatal(err)
  608. }
  609. if got := outBuf.String(); got != str {
  610. t.Errorf("got %q; want %q", got, str)
  611. }
  612. })
  613. }
  614. func parseEnv(out []byte) map[string]string {
  615. e := map[string]string{}
  616. lineread.Reader(bytes.NewReader(out), func(line []byte) error {
  617. i := bytes.IndexByte(line, '=')
  618. if i == -1 {
  619. return nil
  620. }
  621. e[string(line[:i])] = string(line[i+1:])
  622. return nil
  623. })
  624. return e
  625. }
  626. func TestPublicKeyFetching(t *testing.T) {
  627. var reqsTotal, reqsIfNoneMatchHit, reqsIfNoneMatchMiss int32
  628. ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  629. atomic.AddInt32((&reqsTotal), 1)
  630. etag := fmt.Sprintf("W/%q", sha256.Sum256([]byte(r.URL.Path)))
  631. w.Header().Set("Etag", etag)
  632. if v := r.Header.Get("If-None-Match"); v != "" {
  633. if v == etag {
  634. atomic.AddInt32(&reqsIfNoneMatchHit, 1)
  635. w.WriteHeader(304)
  636. return
  637. }
  638. atomic.AddInt32(&reqsIfNoneMatchMiss, 1)
  639. }
  640. io.WriteString(w, "foo\nbar\n"+string(r.URL.Path)+"\n")
  641. }))
  642. ts.StartTLS()
  643. defer ts.Close()
  644. keys := ts.URL
  645. clock := &tstest.Clock{}
  646. srv := &server{
  647. pubKeyHTTPClient: ts.Client(),
  648. timeNow: clock.Now,
  649. }
  650. for i := 0; i < 2; i++ {
  651. got, err := srv.fetchPublicKeysURL(keys + "/alice.keys")
  652. if err != nil {
  653. t.Fatal(err)
  654. }
  655. if want := []string{"foo", "bar", "/alice.keys"}; !reflect.DeepEqual(got, want) {
  656. t.Errorf("got %q; want %q", got, want)
  657. }
  658. }
  659. if got, want := atomic.LoadInt32(&reqsTotal), int32(1); got != want {
  660. t.Errorf("got %d requests; want %d", got, want)
  661. }
  662. if got, want := atomic.LoadInt32(&reqsIfNoneMatchHit), int32(0); got != want {
  663. t.Errorf("got %d etag hits; want %d", got, want)
  664. }
  665. clock.Advance(5 * time.Minute)
  666. got, err := srv.fetchPublicKeysURL(keys + "/alice.keys")
  667. if err != nil {
  668. t.Fatal(err)
  669. }
  670. if want := []string{"foo", "bar", "/alice.keys"}; !reflect.DeepEqual(got, want) {
  671. t.Errorf("got %q; want %q", got, want)
  672. }
  673. if got, want := atomic.LoadInt32(&reqsTotal), int32(2); got != want {
  674. t.Errorf("got %d requests; want %d", got, want)
  675. }
  676. if got, want := atomic.LoadInt32(&reqsIfNoneMatchHit), int32(1); got != want {
  677. t.Errorf("got %d etag hits; want %d", got, want)
  678. }
  679. if got, want := atomic.LoadInt32(&reqsIfNoneMatchMiss), int32(0); got != want {
  680. t.Errorf("got %d etag misses; want %d", got, want)
  681. }
  682. }
  683. func TestExpandPublicKeyURL(t *testing.T) {
  684. c := &conn{
  685. info: &sshConnInfo{
  686. uprof: tailcfg.UserProfile{
  687. LoginName: "[email protected]",
  688. },
  689. },
  690. }
  691. if got, want := c.expandPublicKeyURL("foo"), "foo"; got != want {
  692. t.Errorf("basic: got %q; want %q", got, want)
  693. }
  694. if got, want := c.expandPublicKeyURL("https://example.com/$LOGINNAME_LOCALPART.keys"), "https://example.com/bar.keys"; got != want {
  695. t.Errorf("localpart: got %q; want %q", got, want)
  696. }
  697. if got, want := c.expandPublicKeyURL("https://example.com/keys?email=$LOGINNAME_EMAIL"), "https://example.com/[email protected]"; got != want {
  698. t.Errorf("email: got %q; want %q", got, want)
  699. }
  700. c.info = new(sshConnInfo)
  701. if got, want := c.expandPublicKeyURL("https://example.com/keys?email=$LOGINNAME_EMAIL"), "https://example.com/keys?email="; got != want {
  702. t.Errorf("on empty: got %q; want %q", got, want)
  703. }
  704. }
  705. func TestAcceptEnvPair(t *testing.T) {
  706. tests := []struct {
  707. in string
  708. want bool
  709. }{
  710. {"TERM=x", true},
  711. {"term=x", false},
  712. {"TERM", false},
  713. {"LC_FOO=x", true},
  714. {"LD_PRELOAD=naah", false},
  715. {"TERM=screen-256color", true},
  716. }
  717. for _, tt := range tests {
  718. if got := acceptEnvPair(tt.in); got != tt.want {
  719. t.Errorf("for %q, got %v; want %v", tt.in, got, tt.want)
  720. }
  721. }
  722. }
  723. func TestPathFromPAMEnvLine(t *testing.T) {
  724. u := &user.User{Username: "foo", HomeDir: "/Homes/Foo"}
  725. tests := []struct {
  726. line string
  727. u *user.User
  728. want string
  729. }{
  730. {"", &user.User{}, ""},
  731. {`PATH DEFAULT="/run/wrappers/bin:@{HOME}/.nix-profile/bin:/etc/profiles/per-user/@{PAM_USER}/bin:/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin"`,
  732. u, "/run/wrappers/bin:/Homes/Foo/.nix-profile/bin:/etc/profiles/per-user/foo/bin:/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin"},
  733. {`PATH DEFAULT="@{SOMETHING_ELSE}:nope:@{HOME}"`,
  734. u, ""},
  735. }
  736. for i, tt := range tests {
  737. got := pathFromPAMEnvLine([]byte(tt.line), tt.u)
  738. if got != tt.want {
  739. t.Errorf("%d. got %q; want %q", i, got, tt.want)
  740. }
  741. }
  742. }
  743. func TestPathFromPAMEnvLineOnNixOS(t *testing.T) {
  744. if runtime.GOOS != "linux" {
  745. t.Skip("skipping on non-linux")
  746. }
  747. if distro.Get() != distro.NixOS {
  748. t.Skip("skipping on non-NixOS")
  749. }
  750. u, err := user.Current()
  751. if err != nil {
  752. t.Fatal(err)
  753. }
  754. got := defaultPathForUserOnNixOS(u)
  755. if got == "" {
  756. x, err := os.ReadFile("/etc/pam/environment")
  757. t.Fatalf("no result. file was: err=%v, contents=%s", err, x)
  758. }
  759. t.Logf("success; got=%q", got)
  760. }