client_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. // Copyright 2012 The Go 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. package agent
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "errors"
  9. "io"
  10. "net"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "strconv"
  15. "sync"
  16. "testing"
  17. "time"
  18. "golang.org/x/crypto/ssh"
  19. )
  20. // startOpenSSHAgent executes ssh-agent, and returns an Agent interface to it.
  21. func startOpenSSHAgent(t *testing.T) (client ExtendedAgent, socket string, cleanup func()) {
  22. if testing.Short() {
  23. // ssh-agent is not always available, and the key
  24. // types supported vary by platform.
  25. t.Skip("skipping test due to -short")
  26. }
  27. bin, err := exec.LookPath("ssh-agent")
  28. if err != nil {
  29. t.Skip("could not find ssh-agent")
  30. }
  31. cmd := exec.Command(bin, "-s")
  32. out, err := cmd.Output()
  33. if err != nil {
  34. t.Fatalf("cmd.Output: %v", err)
  35. }
  36. /* Output looks like:
  37. SSH_AUTH_SOCK=/tmp/ssh-P65gpcqArqvH/agent.15541; export SSH_AUTH_SOCK;
  38. SSH_AGENT_PID=15542; export SSH_AGENT_PID;
  39. echo Agent pid 15542;
  40. */
  41. fields := bytes.Split(out, []byte(";"))
  42. line := bytes.SplitN(fields[0], []byte("="), 2)
  43. line[0] = bytes.TrimLeft(line[0], "\n")
  44. if string(line[0]) != "SSH_AUTH_SOCK" {
  45. t.Fatalf("could not find key SSH_AUTH_SOCK in %q", fields[0])
  46. }
  47. socket = string(line[1])
  48. line = bytes.SplitN(fields[2], []byte("="), 2)
  49. line[0] = bytes.TrimLeft(line[0], "\n")
  50. if string(line[0]) != "SSH_AGENT_PID" {
  51. t.Fatalf("could not find key SSH_AGENT_PID in %q", fields[2])
  52. }
  53. pidStr := line[1]
  54. pid, err := strconv.Atoi(string(pidStr))
  55. if err != nil {
  56. t.Fatalf("Atoi(%q): %v", pidStr, err)
  57. }
  58. conn, err := net.Dial("unix", string(socket))
  59. if err != nil {
  60. t.Fatalf("net.Dial: %v", err)
  61. }
  62. ac := NewClient(conn)
  63. return ac, socket, func() {
  64. proc, _ := os.FindProcess(pid)
  65. if proc != nil {
  66. proc.Kill()
  67. }
  68. conn.Close()
  69. os.RemoveAll(filepath.Dir(socket))
  70. }
  71. }
  72. func startAgent(t *testing.T, agent Agent) (client ExtendedAgent, cleanup func()) {
  73. c1, c2, err := netPipe()
  74. if err != nil {
  75. t.Fatalf("netPipe: %v", err)
  76. }
  77. go ServeAgent(agent, c2)
  78. return NewClient(c1), func() {
  79. c1.Close()
  80. c2.Close()
  81. }
  82. }
  83. // startKeyringAgent uses Keyring to simulate a ssh-agent Server and returns a client.
  84. func startKeyringAgent(t *testing.T) (client ExtendedAgent, cleanup func()) {
  85. return startAgent(t, NewKeyring())
  86. }
  87. func testOpenSSHAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  88. agent, _, cleanup := startOpenSSHAgent(t)
  89. defer cleanup()
  90. testAgentInterface(t, agent, key, cert, lifetimeSecs)
  91. }
  92. func testKeyringAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  93. agent, cleanup := startKeyringAgent(t)
  94. defer cleanup()
  95. testAgentInterface(t, agent, key, cert, lifetimeSecs)
  96. }
  97. func testAgentInterface(t *testing.T, agent ExtendedAgent, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  98. signer, err := ssh.NewSignerFromKey(key)
  99. if err != nil {
  100. t.Fatalf("NewSignerFromKey(%T): %v", key, err)
  101. }
  102. // The agent should start up empty.
  103. if keys, err := agent.List(); err != nil {
  104. t.Fatalf("RequestIdentities: %v", err)
  105. } else if len(keys) > 0 {
  106. t.Fatalf("got %d keys, want 0: %v", len(keys), keys)
  107. }
  108. // Attempt to insert the key, with certificate if specified.
  109. var pubKey ssh.PublicKey
  110. if cert != nil {
  111. err = agent.Add(AddedKey{
  112. PrivateKey: key,
  113. Certificate: cert,
  114. Comment: "comment",
  115. LifetimeSecs: lifetimeSecs,
  116. })
  117. pubKey = cert
  118. } else {
  119. err = agent.Add(AddedKey{PrivateKey: key, Comment: "comment", LifetimeSecs: lifetimeSecs})
  120. pubKey = signer.PublicKey()
  121. }
  122. if err != nil {
  123. t.Fatalf("insert(%T): %v", key, err)
  124. }
  125. // Did the key get inserted successfully?
  126. if keys, err := agent.List(); err != nil {
  127. t.Fatalf("List: %v", err)
  128. } else if len(keys) != 1 {
  129. t.Fatalf("got %v, want 1 key", keys)
  130. } else if keys[0].Comment != "comment" {
  131. t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment")
  132. } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) {
  133. t.Fatalf("key mismatch")
  134. }
  135. // Can the agent make a valid signature?
  136. data := []byte("hello")
  137. sig, err := agent.Sign(pubKey, data)
  138. if err != nil {
  139. t.Fatalf("Sign(%s): %v", pubKey.Type(), err)
  140. }
  141. if err := pubKey.Verify(data, sig); err != nil {
  142. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  143. }
  144. // For tests on RSA keys, try signing with SHA-256 and SHA-512 flags
  145. if pubKey.Type() == "ssh-rsa" {
  146. sshFlagTest := func(flag SignatureFlags, expectedSigFormat string) {
  147. sig, err = agent.SignWithFlags(pubKey, data, flag)
  148. if err != nil {
  149. t.Fatalf("SignWithFlags(%s): %v", pubKey.Type(), err)
  150. }
  151. if sig.Format != expectedSigFormat {
  152. t.Fatalf("Signature format didn't match expected value: %s != %s", sig.Format, expectedSigFormat)
  153. }
  154. if err := pubKey.Verify(data, sig); err != nil {
  155. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  156. }
  157. }
  158. sshFlagTest(0, ssh.SigAlgoRSA)
  159. sshFlagTest(SignatureFlagRsaSha256, ssh.SigAlgoRSASHA2256)
  160. sshFlagTest(SignatureFlagRsaSha512, ssh.SigAlgoRSASHA2512)
  161. }
  162. // If the key has a lifetime, is it removed when it should be?
  163. if lifetimeSecs > 0 {
  164. time.Sleep(time.Second*time.Duration(lifetimeSecs) + 100*time.Millisecond)
  165. keys, err := agent.List()
  166. if err != nil {
  167. t.Fatalf("List: %v", err)
  168. }
  169. if len(keys) > 0 {
  170. t.Fatalf("key not expired")
  171. }
  172. }
  173. }
  174. func TestMalformedRequests(t *testing.T) {
  175. keyringAgent := NewKeyring()
  176. listener, err := netListener()
  177. if err != nil {
  178. t.Fatalf("netListener: %v", err)
  179. }
  180. defer listener.Close()
  181. testCase := func(t *testing.T, requestBytes []byte, wantServerErr bool) {
  182. var wg sync.WaitGroup
  183. wg.Add(1)
  184. go func() {
  185. defer wg.Done()
  186. c, err := listener.Accept()
  187. if err != nil {
  188. t.Errorf("listener.Accept: %v", err)
  189. return
  190. }
  191. defer c.Close()
  192. err = ServeAgent(keyringAgent, c)
  193. if err == nil {
  194. t.Error("ServeAgent should have returned an error to malformed input")
  195. } else {
  196. if (err != io.EOF) != wantServerErr {
  197. t.Errorf("ServeAgent returned expected error: %v", err)
  198. }
  199. }
  200. }()
  201. c, err := net.Dial("tcp", listener.Addr().String())
  202. if err != nil {
  203. t.Fatalf("net.Dial: %v", err)
  204. }
  205. _, err = c.Write(requestBytes)
  206. if err != nil {
  207. t.Errorf("Unexpected error writing raw bytes on connection: %v", err)
  208. }
  209. c.Close()
  210. wg.Wait()
  211. }
  212. var testCases = []struct {
  213. name string
  214. requestBytes []byte
  215. wantServerErr bool
  216. }{
  217. {"Empty request", []byte{}, false},
  218. {"Short header", []byte{0x00}, true},
  219. {"Empty body", []byte{0x00, 0x00, 0x00, 0x00}, true},
  220. {"Short body", []byte{0x00, 0x00, 0x00, 0x01}, false},
  221. }
  222. for _, tc := range testCases {
  223. t.Run(tc.name, func(t *testing.T) { testCase(t, tc.requestBytes, tc.wantServerErr) })
  224. }
  225. }
  226. func TestAgent(t *testing.T) {
  227. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  228. testOpenSSHAgent(t, testPrivateKeys[keyType], nil, 0)
  229. testKeyringAgent(t, testPrivateKeys[keyType], nil, 0)
  230. }
  231. }
  232. func TestCert(t *testing.T) {
  233. cert := &ssh.Certificate{
  234. Key: testPublicKeys["rsa"],
  235. ValidBefore: ssh.CertTimeInfinity,
  236. CertType: ssh.UserCert,
  237. }
  238. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  239. testOpenSSHAgent(t, testPrivateKeys["rsa"], cert, 0)
  240. testKeyringAgent(t, testPrivateKeys["rsa"], cert, 0)
  241. }
  242. // netListener creates a localhost network listener.
  243. func netListener() (net.Listener, error) {
  244. listener, err := net.Listen("tcp", "127.0.0.1:0")
  245. if err != nil {
  246. listener, err = net.Listen("tcp", "[::1]:0")
  247. if err != nil {
  248. return nil, err
  249. }
  250. }
  251. return listener, nil
  252. }
  253. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  254. // therefore is buffered (net.Pipe deadlocks if both sides start with
  255. // a write.)
  256. func netPipe() (net.Conn, net.Conn, error) {
  257. listener, err := netListener()
  258. if err != nil {
  259. return nil, nil, err
  260. }
  261. defer listener.Close()
  262. c1, err := net.Dial("tcp", listener.Addr().String())
  263. if err != nil {
  264. return nil, nil, err
  265. }
  266. c2, err := listener.Accept()
  267. if err != nil {
  268. c1.Close()
  269. return nil, nil, err
  270. }
  271. return c1, c2, nil
  272. }
  273. func TestServerResponseTooLarge(t *testing.T) {
  274. a, b, err := netPipe()
  275. if err != nil {
  276. t.Fatalf("netPipe: %v", err)
  277. }
  278. defer a.Close()
  279. defer b.Close()
  280. var response identitiesAnswerAgentMsg
  281. response.NumKeys = 1
  282. response.Keys = make([]byte, maxAgentResponseBytes+1)
  283. agent := NewClient(a)
  284. go func() {
  285. n, _ := b.Write(ssh.Marshal(response))
  286. if n < 4 {
  287. t.Fatalf("At least 4 bytes (the response size) should have been successfully written: %d < 4", n)
  288. }
  289. }()
  290. _, err = agent.List()
  291. if err == nil {
  292. t.Fatal("Did not get error result")
  293. }
  294. if err.Error() != "agent: client error: response too large" {
  295. t.Fatal("Did not get expected error result")
  296. }
  297. }
  298. func TestAuth(t *testing.T) {
  299. agent, _, cleanup := startOpenSSHAgent(t)
  300. defer cleanup()
  301. a, b, err := netPipe()
  302. if err != nil {
  303. t.Fatalf("netPipe: %v", err)
  304. }
  305. defer a.Close()
  306. defer b.Close()
  307. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
  308. t.Errorf("Add: %v", err)
  309. }
  310. serverConf := ssh.ServerConfig{}
  311. serverConf.AddHostKey(testSigners["rsa"])
  312. serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  313. if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  314. return nil, nil
  315. }
  316. return nil, errors.New("pubkey rejected")
  317. }
  318. go func() {
  319. conn, _, _, err := ssh.NewServerConn(a, &serverConf)
  320. if err != nil {
  321. t.Fatalf("Server: %v", err)
  322. }
  323. conn.Close()
  324. }()
  325. conf := ssh.ClientConfig{
  326. HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  327. }
  328. conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
  329. conn, _, _, err := ssh.NewClientConn(b, "", &conf)
  330. if err != nil {
  331. t.Fatalf("NewClientConn: %v", err)
  332. }
  333. conn.Close()
  334. }
  335. func TestLockOpenSSHAgent(t *testing.T) {
  336. agent, _, cleanup := startOpenSSHAgent(t)
  337. defer cleanup()
  338. testLockAgent(agent, t)
  339. }
  340. func TestLockKeyringAgent(t *testing.T) {
  341. agent, cleanup := startKeyringAgent(t)
  342. defer cleanup()
  343. testLockAgent(agent, t)
  344. }
  345. func testLockAgent(agent Agent, t *testing.T) {
  346. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil {
  347. t.Errorf("Add: %v", err)
  348. }
  349. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil {
  350. t.Errorf("Add: %v", err)
  351. }
  352. if keys, err := agent.List(); err != nil {
  353. t.Errorf("List: %v", err)
  354. } else if len(keys) != 2 {
  355. t.Errorf("Want 2 keys, got %v", keys)
  356. }
  357. passphrase := []byte("secret")
  358. if err := agent.Lock(passphrase); err != nil {
  359. t.Errorf("Lock: %v", err)
  360. }
  361. if keys, err := agent.List(); err != nil {
  362. t.Errorf("List: %v", err)
  363. } else if len(keys) != 0 {
  364. t.Errorf("Want 0 keys, got %v", keys)
  365. }
  366. signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"])
  367. if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil {
  368. t.Fatalf("Sign did not fail")
  369. }
  370. if err := agent.Remove(signer.PublicKey()); err == nil {
  371. t.Fatalf("Remove did not fail")
  372. }
  373. if err := agent.RemoveAll(); err == nil {
  374. t.Fatalf("RemoveAll did not fail")
  375. }
  376. if err := agent.Unlock(nil); err == nil {
  377. t.Errorf("Unlock with wrong passphrase succeeded")
  378. }
  379. if err := agent.Unlock(passphrase); err != nil {
  380. t.Errorf("Unlock: %v", err)
  381. }
  382. if err := agent.Remove(signer.PublicKey()); err != nil {
  383. t.Fatalf("Remove: %v", err)
  384. }
  385. if keys, err := agent.List(); err != nil {
  386. t.Errorf("List: %v", err)
  387. } else if len(keys) != 1 {
  388. t.Errorf("Want 1 keys, got %v", keys)
  389. }
  390. }
  391. func testOpenSSHAgentLifetime(t *testing.T) {
  392. agent, _, cleanup := startOpenSSHAgent(t)
  393. defer cleanup()
  394. testAgentLifetime(t, agent)
  395. }
  396. func testKeyringAgentLifetime(t *testing.T) {
  397. agent, cleanup := startKeyringAgent(t)
  398. defer cleanup()
  399. testAgentLifetime(t, agent)
  400. }
  401. func testAgentLifetime(t *testing.T, agent Agent) {
  402. for _, keyType := range []string{"rsa", "dsa", "ecdsa"} {
  403. // Add private keys to the agent.
  404. err := agent.Add(AddedKey{
  405. PrivateKey: testPrivateKeys[keyType],
  406. Comment: "comment",
  407. LifetimeSecs: 1,
  408. })
  409. if err != nil {
  410. t.Fatalf("add: %v", err)
  411. }
  412. // Add certs to the agent.
  413. cert := &ssh.Certificate{
  414. Key: testPublicKeys[keyType],
  415. ValidBefore: ssh.CertTimeInfinity,
  416. CertType: ssh.UserCert,
  417. }
  418. cert.SignCert(rand.Reader, testSigners[keyType])
  419. err = agent.Add(AddedKey{
  420. PrivateKey: testPrivateKeys[keyType],
  421. Certificate: cert,
  422. Comment: "comment",
  423. LifetimeSecs: 1,
  424. })
  425. if err != nil {
  426. t.Fatalf("add: %v", err)
  427. }
  428. }
  429. time.Sleep(1100 * time.Millisecond)
  430. if keys, err := agent.List(); err != nil {
  431. t.Errorf("List: %v", err)
  432. } else if len(keys) != 0 {
  433. t.Errorf("Want 0 keys, got %v", len(keys))
  434. }
  435. }
  436. type keyringExtended struct {
  437. *keyring
  438. }
  439. func (r *keyringExtended) Extension(extensionType string, contents []byte) ([]byte, error) {
  440. if extensionType != "my-extension@example.com" {
  441. return []byte{agentExtensionFailure}, nil
  442. }
  443. return append([]byte{agentSuccess}, contents...), nil
  444. }
  445. func TestAgentExtensions(t *testing.T) {
  446. agent, _, cleanup := startOpenSSHAgent(t)
  447. defer cleanup()
  448. _, err := agent.Extension("my-extension@example.com", []byte{0x00, 0x01, 0x02})
  449. if err == nil {
  450. t.Fatal("should have gotten agent extension failure")
  451. }
  452. agent, cleanup = startAgent(t, &keyringExtended{})
  453. defer cleanup()
  454. result, err := agent.Extension("my-extension@example.com", []byte{0x00, 0x01, 0x02})
  455. if err != nil {
  456. t.Fatalf("agent extension failure: %v", err)
  457. }
  458. if len(result) != 4 || !bytes.Equal(result, []byte{agentSuccess, 0x00, 0x01, 0x02}) {
  459. t.Fatalf("agent extension result invalid: %v", result)
  460. }
  461. _, err = agent.Extension("bad-extension@example.com", []byte{0x00, 0x01, 0x02})
  462. if err == nil {
  463. t.Fatal("should have gotten agent extension failure")
  464. }
  465. }