client_test.go 8.7 KB

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