client_test.go 12 KB

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