client_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2014 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 ssh
  5. import (
  6. "net"
  7. "strings"
  8. "testing"
  9. )
  10. func testClientVersion(t *testing.T, config *ClientConfig, expected string) {
  11. clientConn, serverConn := net.Pipe()
  12. defer clientConn.Close()
  13. receivedVersion := make(chan string, 1)
  14. config.HostKeyCallback = InsecureIgnoreHostKey()
  15. go func() {
  16. version, err := readVersion(serverConn)
  17. if err != nil {
  18. receivedVersion <- ""
  19. } else {
  20. receivedVersion <- string(version)
  21. }
  22. serverConn.Close()
  23. }()
  24. NewClientConn(clientConn, "", config)
  25. actual := <-receivedVersion
  26. if actual != expected {
  27. t.Fatalf("got %s; want %s", actual, expected)
  28. }
  29. }
  30. func TestCustomClientVersion(t *testing.T) {
  31. version := "Test-Client-Version-0.0"
  32. testClientVersion(t, &ClientConfig{ClientVersion: version}, version)
  33. }
  34. func TestDefaultClientVersion(t *testing.T) {
  35. testClientVersion(t, &ClientConfig{}, packageVersion)
  36. }
  37. func TestHostKeyCheck(t *testing.T) {
  38. for _, tt := range []struct {
  39. name string
  40. wantError string
  41. key PublicKey
  42. }{
  43. {"no callback", "must specify HostKeyCallback", nil},
  44. {"correct key", "", testSigners["rsa"].PublicKey()},
  45. {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()},
  46. } {
  47. c1, c2, err := netPipe()
  48. if err != nil {
  49. t.Fatalf("netPipe: %v", err)
  50. }
  51. defer c1.Close()
  52. defer c2.Close()
  53. serverConf := &ServerConfig{
  54. NoClientAuth: true,
  55. }
  56. serverConf.AddHostKey(testSigners["rsa"])
  57. go NewServerConn(c1, serverConf)
  58. clientConf := ClientConfig{
  59. User: "user",
  60. }
  61. if tt.key != nil {
  62. clientConf.HostKeyCallback = FixedHostKey(tt.key)
  63. }
  64. _, _, _, err = NewClientConn(c2, "", &clientConf)
  65. if err != nil {
  66. if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) {
  67. t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError)
  68. }
  69. } else if tt.wantError != "" {
  70. t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError)
  71. }
  72. }
  73. }