client_test.go 7.2 KB

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