client_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. // startAgent executes ssh-agent, and returns a Agent interface to it.
  19. func startAgent(t *testing.T) (client Agent, 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 testAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  71. agent, _, cleanup := startAgent(t)
  72. defer cleanup()
  73. testAgentInterface(t, agent, key, cert, lifetimeSecs)
  74. }
  75. func testAgentInterface(t *testing.T, agent Agent, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  76. signer, err := ssh.NewSignerFromKey(key)
  77. if err != nil {
  78. t.Fatalf("NewSignerFromKey(%T): %v", key, err)
  79. }
  80. // The agent should start up empty.
  81. if keys, err := agent.List(); err != nil {
  82. t.Fatalf("RequestIdentities: %v", err)
  83. } else if len(keys) > 0 {
  84. t.Fatalf("got %d keys, want 0: %v", len(keys), keys)
  85. }
  86. // Attempt to insert the key, with certificate if specified.
  87. var pubKey ssh.PublicKey
  88. if cert != nil {
  89. err = agent.Add(AddedKey{
  90. PrivateKey: key,
  91. Certificate: cert,
  92. Comment: "comment",
  93. LifetimeSecs: lifetimeSecs,
  94. })
  95. pubKey = cert
  96. } else {
  97. err = agent.Add(AddedKey{PrivateKey: key, Comment: "comment", LifetimeSecs: lifetimeSecs})
  98. pubKey = signer.PublicKey()
  99. }
  100. if err != nil {
  101. t.Fatalf("insert(%T): %v", key, err)
  102. }
  103. // Did the key get inserted successfully?
  104. if keys, err := agent.List(); err != nil {
  105. t.Fatalf("List: %v", err)
  106. } else if len(keys) != 1 {
  107. t.Fatalf("got %v, want 1 key", keys)
  108. } else if keys[0].Comment != "comment" {
  109. t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment")
  110. } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) {
  111. t.Fatalf("key mismatch")
  112. }
  113. // Can the agent make a valid signature?
  114. data := []byte("hello")
  115. sig, err := agent.Sign(pubKey, data)
  116. if err != nil {
  117. t.Fatalf("Sign(%s): %v", pubKey.Type(), err)
  118. }
  119. if err := pubKey.Verify(data, sig); err != nil {
  120. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  121. }
  122. }
  123. func TestAgent(t *testing.T) {
  124. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  125. testAgent(t, testPrivateKeys[keyType], nil, 0)
  126. }
  127. }
  128. func TestCert(t *testing.T) {
  129. cert := &ssh.Certificate{
  130. Key: testPublicKeys["rsa"],
  131. ValidBefore: ssh.CertTimeInfinity,
  132. CertType: ssh.UserCert,
  133. }
  134. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  135. testAgent(t, testPrivateKeys["rsa"], cert, 0)
  136. }
  137. func TestConstraints(t *testing.T) {
  138. testAgent(t, testPrivateKeys["rsa"], nil, 3600 /* lifetime in seconds */)
  139. }
  140. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  141. // therefore is buffered (net.Pipe deadlocks if both sides start with
  142. // a write.)
  143. func netPipe() (net.Conn, net.Conn, error) {
  144. listener, err := net.Listen("tcp", "127.0.0.1:0")
  145. if err != nil {
  146. return nil, nil, err
  147. }
  148. defer listener.Close()
  149. c1, err := net.Dial("tcp", listener.Addr().String())
  150. if err != nil {
  151. return nil, nil, err
  152. }
  153. c2, err := listener.Accept()
  154. if err != nil {
  155. c1.Close()
  156. return nil, nil, err
  157. }
  158. return c1, c2, nil
  159. }
  160. func TestAuth(t *testing.T) {
  161. a, b, err := netPipe()
  162. if err != nil {
  163. t.Fatalf("netPipe: %v", err)
  164. }
  165. defer a.Close()
  166. defer b.Close()
  167. agent, _, cleanup := startAgent(t)
  168. defer cleanup()
  169. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
  170. t.Errorf("Add: %v", err)
  171. }
  172. serverConf := ssh.ServerConfig{}
  173. serverConf.AddHostKey(testSigners["rsa"])
  174. serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  175. if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  176. return nil, nil
  177. }
  178. return nil, errors.New("pubkey rejected")
  179. }
  180. go func() {
  181. conn, _, _, err := ssh.NewServerConn(a, &serverConf)
  182. if err != nil {
  183. t.Fatalf("Server: %v", err)
  184. }
  185. conn.Close()
  186. }()
  187. conf := ssh.ClientConfig{}
  188. conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
  189. conn, _, _, err := ssh.NewClientConn(b, "", &conf)
  190. if err != nil {
  191. t.Fatalf("NewClientConn: %v", err)
  192. }
  193. conn.Close()
  194. }
  195. func TestLockClient(t *testing.T) {
  196. agent, _, cleanup := startAgent(t)
  197. defer cleanup()
  198. testLockAgent(agent, t)
  199. }
  200. func testLockAgent(agent Agent, t *testing.T) {
  201. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil {
  202. t.Errorf("Add: %v", err)
  203. }
  204. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil {
  205. t.Errorf("Add: %v", err)
  206. }
  207. if keys, err := agent.List(); err != nil {
  208. t.Errorf("List: %v", err)
  209. } else if len(keys) != 2 {
  210. t.Errorf("Want 2 keys, got %v", keys)
  211. }
  212. passphrase := []byte("secret")
  213. if err := agent.Lock(passphrase); err != nil {
  214. t.Errorf("Lock: %v", err)
  215. }
  216. if keys, err := agent.List(); err != nil {
  217. t.Errorf("List: %v", err)
  218. } else if len(keys) != 0 {
  219. t.Errorf("Want 0 keys, got %v", keys)
  220. }
  221. signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"])
  222. if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil {
  223. t.Fatalf("Sign did not fail")
  224. }
  225. if err := agent.Remove(signer.PublicKey()); err == nil {
  226. t.Fatalf("Remove did not fail")
  227. }
  228. if err := agent.RemoveAll(); err == nil {
  229. t.Fatalf("RemoveAll did not fail")
  230. }
  231. if err := agent.Unlock(nil); err == nil {
  232. t.Errorf("Unlock with wrong passphrase succeeded")
  233. }
  234. if err := agent.Unlock(passphrase); err != nil {
  235. t.Errorf("Unlock: %v", err)
  236. }
  237. if err := agent.Remove(signer.PublicKey()); err != nil {
  238. t.Fatalf("Remove: %v", err)
  239. }
  240. if keys, err := agent.List(); err != nil {
  241. t.Errorf("List: %v", err)
  242. } else if len(keys) != 1 {
  243. t.Errorf("Want 1 keys, got %v", keys)
  244. }
  245. }
  246. func TestAgentLifetime(t *testing.T) {
  247. agent, _, cleanup := startAgent(t)
  248. defer cleanup()
  249. for _, keyType := range []string{"rsa", "dsa", "ecdsa"} {
  250. // Add private keys to the agent.
  251. err := agent.Add(AddedKey{
  252. PrivateKey: testPrivateKeys[keyType],
  253. Comment: "comment",
  254. LifetimeSecs: 1,
  255. })
  256. if err != nil {
  257. t.Fatalf("add: %v", err)
  258. }
  259. // Add certs to the agent.
  260. cert := &ssh.Certificate{
  261. Key: testPublicKeys[keyType],
  262. ValidBefore: ssh.CertTimeInfinity,
  263. CertType: ssh.UserCert,
  264. }
  265. cert.SignCert(rand.Reader, testSigners[keyType])
  266. err = agent.Add(AddedKey{
  267. PrivateKey: testPrivateKeys[keyType],
  268. Certificate: cert,
  269. Comment: "comment",
  270. LifetimeSecs: 1,
  271. })
  272. if err != nil {
  273. t.Fatalf("add: %v", err)
  274. }
  275. }
  276. time.Sleep(1100 * time.Millisecond)
  277. if keys, err := agent.List(); err != nil {
  278. t.Errorf("List: %v", err)
  279. } else if len(keys) != 0 {
  280. t.Errorf("Want 0 keys, got %v", len(keys))
  281. }
  282. }