Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

344 рядки
8.5 KiB

  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", ":0")
  159. if err != nil {
  160. return nil, nil, err
  161. }
  162. defer listener.Close()
  163. c1, err := net.Dial("tcp", listener.Addr().String())
  164. if err != nil {
  165. return nil, nil, err
  166. }
  167. c2, err := listener.Accept()
  168. if err != nil {
  169. c1.Close()
  170. return nil, nil, err
  171. }
  172. return c1, c2, nil
  173. }
  174. func TestAuth(t *testing.T) {
  175. a, b, err := netPipe()
  176. if err != nil {
  177. t.Fatalf("netPipe: %v", err)
  178. }
  179. defer a.Close()
  180. defer b.Close()
  181. agent, _, cleanup := startAgent(t)
  182. defer cleanup()
  183. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
  184. t.Errorf("Add: %v", err)
  185. }
  186. serverConf := ssh.ServerConfig{}
  187. serverConf.AddHostKey(testSigners["rsa"])
  188. serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  189. if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  190. return nil, nil
  191. }
  192. return nil, errors.New("pubkey rejected")
  193. }
  194. go func() {
  195. conn, _, _, err := ssh.NewServerConn(a, &serverConf)
  196. if err != nil {
  197. t.Fatalf("Server: %v", err)
  198. }
  199. conn.Close()
  200. }()
  201. conf := ssh.ClientConfig{}
  202. conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
  203. conn, _, _, err := ssh.NewClientConn(b, "", &conf)
  204. if err != nil {
  205. t.Fatalf("NewClientConn: %v", err)
  206. }
  207. conn.Close()
  208. }
  209. func TestLockClient(t *testing.T) {
  210. agent, _, cleanup := startAgent(t)
  211. defer cleanup()
  212. testLockAgent(agent, t)
  213. }
  214. func testLockAgent(agent Agent, t *testing.T) {
  215. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil {
  216. t.Errorf("Add: %v", err)
  217. }
  218. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil {
  219. t.Errorf("Add: %v", err)
  220. }
  221. if keys, err := agent.List(); err != nil {
  222. t.Errorf("List: %v", err)
  223. } else if len(keys) != 2 {
  224. t.Errorf("Want 2 keys, got %v", keys)
  225. }
  226. passphrase := []byte("secret")
  227. if err := agent.Lock(passphrase); err != nil {
  228. t.Errorf("Lock: %v", err)
  229. }
  230. if keys, err := agent.List(); err != nil {
  231. t.Errorf("List: %v", err)
  232. } else if len(keys) != 0 {
  233. t.Errorf("Want 0 keys, got %v", keys)
  234. }
  235. signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"])
  236. if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil {
  237. t.Fatalf("Sign did not fail")
  238. }
  239. if err := agent.Remove(signer.PublicKey()); err == nil {
  240. t.Fatalf("Remove did not fail")
  241. }
  242. if err := agent.RemoveAll(); err == nil {
  243. t.Fatalf("RemoveAll did not fail")
  244. }
  245. if err := agent.Unlock(nil); err == nil {
  246. t.Errorf("Unlock with wrong passphrase succeeded")
  247. }
  248. if err := agent.Unlock(passphrase); err != nil {
  249. t.Errorf("Unlock: %v", err)
  250. }
  251. if err := agent.Remove(signer.PublicKey()); err != nil {
  252. t.Fatalf("Remove: %v", err)
  253. }
  254. if keys, err := agent.List(); err != nil {
  255. t.Errorf("List: %v", err)
  256. } else if len(keys) != 1 {
  257. t.Errorf("Want 1 keys, got %v", keys)
  258. }
  259. }
  260. func TestAgentLifetime(t *testing.T) {
  261. agent, _, cleanup := startAgent(t)
  262. defer cleanup()
  263. for _, keyType := range []string{"rsa", "dsa", "ecdsa"} {
  264. // Add private keys to the agent.
  265. err := agent.Add(AddedKey{
  266. PrivateKey: testPrivateKeys[keyType],
  267. Comment: "comment",
  268. LifetimeSecs: 1,
  269. })
  270. if err != nil {
  271. t.Fatalf("add: %v", err)
  272. }
  273. // Add certs to the agent.
  274. cert := &ssh.Certificate{
  275. Key: testPublicKeys[keyType],
  276. ValidBefore: ssh.CertTimeInfinity,
  277. CertType: ssh.UserCert,
  278. }
  279. cert.SignCert(rand.Reader, testSigners[keyType])
  280. err = agent.Add(AddedKey{
  281. PrivateKey: testPrivateKeys[keyType],
  282. Certificate: cert,
  283. Comment: "comment",
  284. LifetimeSecs: 1,
  285. })
  286. if err != nil {
  287. t.Fatalf("add: %v", err)
  288. }
  289. }
  290. time.Sleep(1100 * time.Millisecond)
  291. if keys, err := agent.List(); err != nil {
  292. t.Errorf("List: %v", err)
  293. } else if len(keys) != 0 {
  294. t.Errorf("Want 0 keys, got %v", len(keys))
  295. }
  296. }