client_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. // startOpenSSHAgent executes ssh-agent, and returns an Agent interface to it.
  19. func startOpenSSHAgent(t *testing.T) (client ExtendedAgent, 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 startAgent(t *testing.T, agent Agent) (client ExtendedAgent, cleanup func()) {
  71. c1, c2, err := netPipe()
  72. if err != nil {
  73. t.Fatalf("netPipe: %v", err)
  74. }
  75. go ServeAgent(agent, c2)
  76. return NewClient(c1), func() {
  77. c1.Close()
  78. c2.Close()
  79. }
  80. }
  81. // startKeyringAgent uses Keyring to simulate a ssh-agent Server and returns a client.
  82. func startKeyringAgent(t *testing.T) (client ExtendedAgent, cleanup func()) {
  83. return startAgent(t, NewKeyring())
  84. }
  85. func testOpenSSHAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  86. agent, _, cleanup := startOpenSSHAgent(t)
  87. defer cleanup()
  88. testAgentInterface(t, agent, key, cert, lifetimeSecs)
  89. }
  90. func testKeyringAgent(t *testing.T, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  91. agent, cleanup := startKeyringAgent(t)
  92. defer cleanup()
  93. testAgentInterface(t, agent, key, cert, lifetimeSecs)
  94. }
  95. func testAgentInterface(t *testing.T, agent ExtendedAgent, key interface{}, cert *ssh.Certificate, lifetimeSecs uint32) {
  96. signer, err := ssh.NewSignerFromKey(key)
  97. if err != nil {
  98. t.Fatalf("NewSignerFromKey(%T): %v", key, err)
  99. }
  100. // The agent should start up empty.
  101. if keys, err := agent.List(); err != nil {
  102. t.Fatalf("RequestIdentities: %v", err)
  103. } else if len(keys) > 0 {
  104. t.Fatalf("got %d keys, want 0: %v", len(keys), keys)
  105. }
  106. // Attempt to insert the key, with certificate if specified.
  107. var pubKey ssh.PublicKey
  108. if cert != nil {
  109. err = agent.Add(AddedKey{
  110. PrivateKey: key,
  111. Certificate: cert,
  112. Comment: "comment",
  113. LifetimeSecs: lifetimeSecs,
  114. })
  115. pubKey = cert
  116. } else {
  117. err = agent.Add(AddedKey{PrivateKey: key, Comment: "comment", LifetimeSecs: lifetimeSecs})
  118. pubKey = signer.PublicKey()
  119. }
  120. if err != nil {
  121. t.Fatalf("insert(%T): %v", key, err)
  122. }
  123. // Did the key get inserted successfully?
  124. if keys, err := agent.List(); err != nil {
  125. t.Fatalf("List: %v", err)
  126. } else if len(keys) != 1 {
  127. t.Fatalf("got %v, want 1 key", keys)
  128. } else if keys[0].Comment != "comment" {
  129. t.Fatalf("key comment: got %v, want %v", keys[0].Comment, "comment")
  130. } else if !bytes.Equal(keys[0].Blob, pubKey.Marshal()) {
  131. t.Fatalf("key mismatch")
  132. }
  133. // Can the agent make a valid signature?
  134. data := []byte("hello")
  135. sig, err := agent.Sign(pubKey, data)
  136. if err != nil {
  137. t.Fatalf("Sign(%s): %v", pubKey.Type(), err)
  138. }
  139. if err := pubKey.Verify(data, sig); err != nil {
  140. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  141. }
  142. // For tests on RSA keys, try signing with SHA-256 and SHA-512 flags
  143. if pubKey.Type() == "ssh-rsa" {
  144. sshFlagTest := func(flag SignatureFlags, expectedSigFormat string) {
  145. sig, err = agent.SignWithFlags(pubKey, data, flag)
  146. if err != nil {
  147. t.Fatalf("SignWithFlags(%s): %v", pubKey.Type(), err)
  148. }
  149. if sig.Format != expectedSigFormat {
  150. t.Fatalf("Signature format didn't match expected value: %s != %s", sig.Format, expectedSigFormat)
  151. }
  152. if err := pubKey.Verify(data, sig); err != nil {
  153. t.Fatalf("Verify(%s): %v", pubKey.Type(), err)
  154. }
  155. }
  156. sshFlagTest(0, ssh.SigAlgoRSA)
  157. sshFlagTest(SignatureFlagRsaSha256, ssh.SigAlgoRSASHA2256)
  158. sshFlagTest(SignatureFlagRsaSha512, ssh.SigAlgoRSASHA2512)
  159. }
  160. // If the key has a lifetime, is it removed when it should be?
  161. if lifetimeSecs > 0 {
  162. time.Sleep(time.Second*time.Duration(lifetimeSecs) + 100*time.Millisecond)
  163. keys, err := agent.List()
  164. if err != nil {
  165. t.Fatalf("List: %v", err)
  166. }
  167. if len(keys) > 0 {
  168. t.Fatalf("key not expired")
  169. }
  170. }
  171. }
  172. func TestAgent(t *testing.T) {
  173. for _, keyType := range []string{"rsa", "dsa", "ecdsa", "ed25519"} {
  174. testOpenSSHAgent(t, testPrivateKeys[keyType], nil, 0)
  175. testKeyringAgent(t, testPrivateKeys[keyType], nil, 0)
  176. }
  177. }
  178. func TestCert(t *testing.T) {
  179. cert := &ssh.Certificate{
  180. Key: testPublicKeys["rsa"],
  181. ValidBefore: ssh.CertTimeInfinity,
  182. CertType: ssh.UserCert,
  183. }
  184. cert.SignCert(rand.Reader, testSigners["ecdsa"])
  185. testOpenSSHAgent(t, testPrivateKeys["rsa"], cert, 0)
  186. testKeyringAgent(t, testPrivateKeys["rsa"], cert, 0)
  187. }
  188. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  189. // therefore is buffered (net.Pipe deadlocks if both sides start with
  190. // a write.)
  191. func netPipe() (net.Conn, net.Conn, error) {
  192. listener, err := net.Listen("tcp", "127.0.0.1:0")
  193. if err != nil {
  194. listener, err = net.Listen("tcp", "[::1]:0")
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. }
  199. defer listener.Close()
  200. c1, err := net.Dial("tcp", listener.Addr().String())
  201. if err != nil {
  202. return nil, nil, err
  203. }
  204. c2, err := listener.Accept()
  205. if err != nil {
  206. c1.Close()
  207. return nil, nil, err
  208. }
  209. return c1, c2, nil
  210. }
  211. func TestAuth(t *testing.T) {
  212. agent, _, cleanup := startOpenSSHAgent(t)
  213. defer cleanup()
  214. a, b, err := netPipe()
  215. if err != nil {
  216. t.Fatalf("netPipe: %v", err)
  217. }
  218. defer a.Close()
  219. defer b.Close()
  220. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment"}); err != nil {
  221. t.Errorf("Add: %v", err)
  222. }
  223. serverConf := ssh.ServerConfig{}
  224. serverConf.AddHostKey(testSigners["rsa"])
  225. serverConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  226. if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
  227. return nil, nil
  228. }
  229. return nil, errors.New("pubkey rejected")
  230. }
  231. go func() {
  232. conn, _, _, err := ssh.NewServerConn(a, &serverConf)
  233. if err != nil {
  234. t.Fatalf("Server: %v", err)
  235. }
  236. conn.Close()
  237. }()
  238. conf := ssh.ClientConfig{
  239. HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  240. }
  241. conf.Auth = append(conf.Auth, ssh.PublicKeysCallback(agent.Signers))
  242. conn, _, _, err := ssh.NewClientConn(b, "", &conf)
  243. if err != nil {
  244. t.Fatalf("NewClientConn: %v", err)
  245. }
  246. conn.Close()
  247. }
  248. func TestLockOpenSSHAgent(t *testing.T) {
  249. agent, _, cleanup := startOpenSSHAgent(t)
  250. defer cleanup()
  251. testLockAgent(agent, t)
  252. }
  253. func TestLockKeyringAgent(t *testing.T) {
  254. agent, cleanup := startKeyringAgent(t)
  255. defer cleanup()
  256. testLockAgent(agent, t)
  257. }
  258. func testLockAgent(agent Agent, t *testing.T) {
  259. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["rsa"], Comment: "comment 1"}); err != nil {
  260. t.Errorf("Add: %v", err)
  261. }
  262. if err := agent.Add(AddedKey{PrivateKey: testPrivateKeys["dsa"], Comment: "comment dsa"}); err != nil {
  263. t.Errorf("Add: %v", err)
  264. }
  265. if keys, err := agent.List(); err != nil {
  266. t.Errorf("List: %v", err)
  267. } else if len(keys) != 2 {
  268. t.Errorf("Want 2 keys, got %v", keys)
  269. }
  270. passphrase := []byte("secret")
  271. if err := agent.Lock(passphrase); err != nil {
  272. t.Errorf("Lock: %v", err)
  273. }
  274. if keys, err := agent.List(); err != nil {
  275. t.Errorf("List: %v", err)
  276. } else if len(keys) != 0 {
  277. t.Errorf("Want 0 keys, got %v", keys)
  278. }
  279. signer, _ := ssh.NewSignerFromKey(testPrivateKeys["rsa"])
  280. if _, err := agent.Sign(signer.PublicKey(), []byte("hello")); err == nil {
  281. t.Fatalf("Sign did not fail")
  282. }
  283. if err := agent.Remove(signer.PublicKey()); err == nil {
  284. t.Fatalf("Remove did not fail")
  285. }
  286. if err := agent.RemoveAll(); err == nil {
  287. t.Fatalf("RemoveAll did not fail")
  288. }
  289. if err := agent.Unlock(nil); err == nil {
  290. t.Errorf("Unlock with wrong passphrase succeeded")
  291. }
  292. if err := agent.Unlock(passphrase); err != nil {
  293. t.Errorf("Unlock: %v", err)
  294. }
  295. if err := agent.Remove(signer.PublicKey()); err != nil {
  296. t.Fatalf("Remove: %v", err)
  297. }
  298. if keys, err := agent.List(); err != nil {
  299. t.Errorf("List: %v", err)
  300. } else if len(keys) != 1 {
  301. t.Errorf("Want 1 keys, got %v", keys)
  302. }
  303. }
  304. func testOpenSSHAgentLifetime(t *testing.T) {
  305. agent, _, cleanup := startOpenSSHAgent(t)
  306. defer cleanup()
  307. testAgentLifetime(t, agent)
  308. }
  309. func testKeyringAgentLifetime(t *testing.T) {
  310. agent, cleanup := startKeyringAgent(t)
  311. defer cleanup()
  312. testAgentLifetime(t, agent)
  313. }
  314. func testAgentLifetime(t *testing.T, agent Agent) {
  315. for _, keyType := range []string{"rsa", "dsa", "ecdsa"} {
  316. // Add private keys to the agent.
  317. err := agent.Add(AddedKey{
  318. PrivateKey: testPrivateKeys[keyType],
  319. Comment: "comment",
  320. LifetimeSecs: 1,
  321. })
  322. if err != nil {
  323. t.Fatalf("add: %v", err)
  324. }
  325. // Add certs to the agent.
  326. cert := &ssh.Certificate{
  327. Key: testPublicKeys[keyType],
  328. ValidBefore: ssh.CertTimeInfinity,
  329. CertType: ssh.UserCert,
  330. }
  331. cert.SignCert(rand.Reader, testSigners[keyType])
  332. err = agent.Add(AddedKey{
  333. PrivateKey: testPrivateKeys[keyType],
  334. Certificate: cert,
  335. Comment: "comment",
  336. LifetimeSecs: 1,
  337. })
  338. if err != nil {
  339. t.Fatalf("add: %v", err)
  340. }
  341. }
  342. time.Sleep(1100 * time.Millisecond)
  343. if keys, err := agent.List(); err != nil {
  344. t.Errorf("List: %v", err)
  345. } else if len(keys) != 0 {
  346. t.Errorf("Want 0 keys, got %v", len(keys))
  347. }
  348. }
  349. type keyringExtended struct {
  350. *keyring
  351. }
  352. func (r *keyringExtended) Extension(extensionType string, contents []byte) ([]byte, error) {
  353. if extensionType != "my-extension@example.com" {
  354. return []byte{agentExtensionFailure}, nil
  355. }
  356. return append([]byte{agentSuccess}, contents...), nil
  357. }
  358. func TestAgentExtensions(t *testing.T) {
  359. agent, _, cleanup := startOpenSSHAgent(t)
  360. defer cleanup()
  361. result, err := agent.Extension("my-extension@example.com", []byte{0x00, 0x01, 0x02})
  362. if err == nil {
  363. t.Fatal("should have gotten agent extension failure")
  364. }
  365. agent, cleanup = startAgent(t, &keyringExtended{})
  366. defer cleanup()
  367. result, err = agent.Extension("my-extension@example.com", []byte{0x00, 0x01, 0x02})
  368. if err != nil {
  369. t.Fatalf("agent extension failure: %v", err)
  370. }
  371. if len(result) != 4 || !bytes.Equal(result, []byte{agentSuccess, 0x00, 0x01, 0x02}) {
  372. t.Fatalf("agent extension result invalid: %v", result)
  373. }
  374. result, err = agent.Extension("bad-extension@example.com", []byte{0x00, 0x01, 0x02})
  375. if err == nil {
  376. t.Fatal("should have gotten agent extension failure")
  377. }
  378. }