client_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. "code.google.com/p/go.crypto/ssh"
  16. )
  17. // startAgent executes ssh-agent, and returns a Agent interface to it.
  18. func startAgent(t *testing.T) (client Agent, socket string, cleanup func()) {
  19. if testing.Short() {
  20. // ssh-agent is not always available, and the key
  21. // types supported vary by platform.
  22. t.Skip("skipping test due to -short")
  23. }
  24. bin, err := exec.LookPath("ssh-agent")
  25. if err != nil {
  26. t.Skip("could not find ssh-agent")
  27. }
  28. cmd := exec.Command(bin, "-s")
  29. out, err := cmd.Output()
  30. if err != nil {
  31. t.Fatalf("cmd.Output: %v", err)
  32. }
  33. /* Output looks like:
  34. SSH_AUTH_SOCK=/tmp/ssh-P65gpcqArqvH/agent.15541; export SSH_AUTH_SOCK;
  35. SSH_AGENT_PID=15542; export SSH_AGENT_PID;
  36. echo Agent pid 15542;
  37. */
  38. fields := bytes.Split(out, []byte(";"))
  39. line := bytes.SplitN(fields[0], []byte("="), 2)
  40. line[0] = bytes.TrimLeft(line[0], "\n")
  41. if string(line[0]) != "SSH_AUTH_SOCK" {
  42. t.Fatalf("could not find key SSH_AUTH_SOCK in %q", fields[0])
  43. }
  44. socket = string(line[1])
  45. line = bytes.SplitN(fields[2], []byte("="), 2)
  46. line[0] = bytes.TrimLeft(line[0], "\n")
  47. if string(line[0]) != "SSH_AGENT_PID" {
  48. t.Fatalf("could not find key SSH_AGENT_PID in %q", fields[2])
  49. }
  50. pidStr := line[1]
  51. pid, err := strconv.Atoi(string(pidStr))
  52. if err != nil {
  53. t.Fatalf("Atoi(%q): %v", pidStr, err)
  54. }
  55. conn, err := net.Dial("unix", string(socket))
  56. if err != nil {
  57. t.Fatalf("net.Dial: %v", err)
  58. }
  59. ac := NewClient(conn)
  60. return ac, socket, func() {
  61. proc, _ := os.FindProcess(pid)
  62. if proc != nil {
  63. proc.Kill()
  64. }
  65. conn.Close()
  66. os.RemoveAll(filepath.Dir(socket))
  67. }
  68. }
  69. func testAgent(t *testing.T, key interface{}, cert *ssh.Certificate) {
  70. agent, _, cleanup := startAgent(t)
  71. defer cleanup()
  72. testAgentInterface(t, agent, key, cert)
  73. }
  74. func testAgentInterface(t *testing.T, agent Agent, key interface{}, cert *ssh.Certificate) {
  75. signer, err := ssh.NewSignerFromKey(key)
  76. if err != nil {
  77. t.Fatalf("NewSignerFromKey(%T): %v", key, err)
  78. }
  79. // The agent should start up empty.
  80. if keys, err := agent.List(); err != nil {
  81. t.Fatalf("RequestIdentities: %v", err)
  82. } else if len(keys) > 0 {
  83. t.Fatalf("got %d keys, want 0: %v", len(keys), keys)
  84. }
  85. // Attempt to insert the key, with certificate if specified.
  86. var pubKey ssh.PublicKey
  87. if cert != nil {
  88. err = agent.Add(key, cert, "comment")
  89. pubKey = cert
  90. } else {
  91. err = agent.Add(key, nil, "comment")
  92. pubKey = signer.PublicKey()
  93. }
  94. if err != nil {
  95. t.Fatalf("insert(%T): %v", key, err)
  96. }
  97. // Did the key get inserted successfully?
  98. if keys, err := agent.List(); err != nil {
  99. t.Fatalf("List: %v", err)
  100. } else if len(keys) != 1 {
  101. t.Fatalf("got %v, want 1 key", keys)
  102. } else if keys[0].Comment != "comment" {
  103. t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment")
  104. } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) {
  105. t.Fatalf("key mismatch")
  106. }
  107. // Can the agent make a valid signature?
  108. data := []byte("hello")
  109. sig, err := agent.Sign(pubKey, data)
  110. if err != nil {
  111. t.Fatalf("Sign(%s): %v", pubKey.Type(), err)
  112. }
  113. if err := pubKey.Verify(data, sig); err != nil {
  114. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  115. }
  116. }
  117. func TestAgent(t *testing.T) {
  118. for _, keyType := range []string{"rsa", "dsa", "ecdsa"} {
  119. testAgent(t, testPrivateKeys[keyType], nil)
  120. }
  121. }
  122. func TestCert(t *testing.T) {
  123. cert := &ssh.Certificate{
  124. Key: testPublicKeys["rsa"],
  125. ValidBefore: ssh.CertTimeInfinity,
  126. CertType: ssh.UserCert,
  127. }
  128. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  129. testAgent(t, testPrivateKeys["rsa"], cert)
  130. }
  131. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  132. // therefore is buffered (net.Pipe deadlocks if both sides start with
  133. // a write.)
  134. func netPipe() (net.Conn, net.Conn, error) {
  135. listener, err := net.Listen("tcp", "127.0.0.1:0")
  136. if err != nil {
  137. return nil, nil, err
  138. }
  139. defer listener.Close()
  140. c1, err := net.Dial("tcp", listener.Addr().String())
  141. if err != nil {
  142. return nil, nil, err
  143. }
  144. c2, err := listener.Accept()
  145. if err != nil {
  146. c1.Close()
  147. return nil, nil, err
  148. }
  149. return c1, c2, nil
  150. }
  151. func TestAuth(t *testing.T) {
  152. a, b, err := netPipe()
  153. if err != nil {
  154. t.Fatalf("netPipe: %v", err)
  155. }
  156. defer a.Close()
  157. defer b.Close()
  158. agent, _, cleanup := startAgent(t)
  159. defer cleanup()
  160. if err := agent.Add(testPrivateKeys["rsa"], nil, "comment"); err != nil {
  161. t.Errorf("Add: %v", err)
  162. }
  163. serverConf := ssh.ServerConfig{}
  164. serverConf.AddHostKey(testSigners["rsa"])
  165. serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  166. if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  167. return nil, nil
  168. }
  169. return nil, errors.New("pubkey rejected")
  170. }
  171. go func() {
  172. conn, _, _, err := ssh.NewServerConn(a, &serverConf)
  173. if err != nil {
  174. t.Fatalf("Server: %v", err)
  175. }
  176. conn.Close()
  177. }()
  178. conf := ssh.ClientConfig{}
  179. conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
  180. conn, _, _, err := ssh.NewClientConn(b, "", &conf)
  181. if err != nil {
  182. t.Fatalf("NewClientConn: %v", err)
  183. }
  184. conn.Close()
  185. }
  186. func TestLockClient(t *testing.T) {
  187. agent, _, cleanup := startAgent(t)
  188. defer cleanup()
  189. testLockAgent(agent, t)
  190. }
  191. func testLockAgent(agent Agent, t *testing.T) {
  192. if err := agent.Add(testPrivateKeys["rsa"], nil, "comment 1"); err != nil {
  193. t.Errorf("Add: %v", err)
  194. }
  195. if err := agent.Add(testPrivateKeys["dsa"], nil, "comment dsa"); err != nil {
  196. t.Errorf("Add: %v", err)
  197. }
  198. if keys, err := agent.List(); err != nil {
  199. t.Errorf("List: %v", err)
  200. } else if len(keys) != 2 {
  201. t.Errorf("Want 2 keys, got %v", keys)
  202. }
  203. passphrase := []byte("secret")
  204. if err := agent.Lock(passphrase); err != nil {
  205. t.Errorf("Lock: %v", err)
  206. }
  207. if keys, err := agent.List(); err != nil {
  208. t.Errorf("List: %v", err)
  209. } else if len(keys) != 0 {
  210. t.Errorf("Want 0 keys, got %v", keys)
  211. }
  212. signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"])
  213. if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil {
  214. t.Fatalf("Sign did not fail")
  215. }
  216. if err := agent.Remove(signer.PublicKey()); err == nil {
  217. t.Fatalf("Remove did not fail")
  218. }
  219. if err := agent.RemoveAll(); err == nil {
  220. t.Fatalf("RemoveAll did not fail")
  221. }
  222. if err := agent.Unlock(nil); err == nil {
  223. t.Errorf("Unlock with wrong passphrase succeeded")
  224. }
  225. if err := agent.Unlock(passphrase); err != nil {
  226. t.Errorf("Unlock: %v", err)
  227. }
  228. if err := agent.Remove(signer.PublicKey()); err != nil {
  229. t.Fatalf("Remove: %v", err)
  230. }
  231. if keys, err := agent.List(); err != nil {
  232. t.Errorf("List: %v", err)
  233. } else if len(keys) != 1 {
  234. t.Errorf("Want 1 keys, got %v", keys)
  235. }
  236. }