...
1
2
3
4
5 package ssh
6
7 import (
8 "bytes"
9 "crypto/rand"
10 "encoding/binary"
11 "strings"
12 "testing"
13 )
14
15 func TestReadVersion(t *testing.T) {
16 longVersion := strings.Repeat("SSH-2.0-bla", 50)[:253]
17 multiLineVersion := strings.Repeat("ignored\r\n", 20) + "SSH-2.0-bla\r\n"
18 cases := map[string]string{
19 "SSH-2.0-bla\r\n": "SSH-2.0-bla",
20 "SSH-2.0-bla\n": "SSH-2.0-bla",
21 multiLineVersion: "SSH-2.0-bla",
22 longVersion + "\r\n": longVersion,
23 }
24
25 for in, want := range cases {
26 result, err := readVersion(bytes.NewBufferString(in))
27 if err != nil {
28 t.Errorf("readVersion(%q): %s", in, err)
29 }
30 got := string(result)
31 if got != want {
32 t.Errorf("got %q, want %q", got, want)
33 }
34 }
35 }
36
37 func TestReadVersionError(t *testing.T) {
38 longVersion := strings.Repeat("SSH-2.0-bla", 50)[:253]
39 multiLineVersion := strings.Repeat("ignored\r\n", 50) + "SSH-2.0-bla\r\n"
40 cases := []string{
41 longVersion + "too-long\r\n",
42 multiLineVersion,
43 }
44 for _, in := range cases {
45 if _, err := readVersion(bytes.NewBufferString(in)); err == nil {
46 t.Errorf("readVersion(%q) should have failed", in)
47 }
48 }
49 }
50
51 func TestExchangeVersionsBasic(t *testing.T) {
52 v := "SSH-2.0-bla"
53 buf := bytes.NewBufferString(v + "\r\n")
54 them, err := exchangeVersions(buf, []byte("xyz"))
55 if err != nil {
56 t.Errorf("exchangeVersions: %v", err)
57 }
58
59 if want := "SSH-2.0-bla"; string(them) != want {
60 t.Errorf("got %q want %q for our version", them, want)
61 }
62 }
63
64 func TestExchangeVersions(t *testing.T) {
65 cases := []string{
66 "not\x000allowed",
67 "not allowed\x01\r\n",
68 }
69 for _, c := range cases {
70 buf := bytes.NewBufferString("SSH-2.0-bla\r\n")
71 if _, err := exchangeVersions(buf, []byte(c)); err == nil {
72 t.Errorf("exchangeVersions(%q): should have failed", c)
73 }
74 }
75 }
76
77 type closerBuffer struct {
78 bytes.Buffer
79 }
80
81 func (b *closerBuffer) Close() error {
82 return nil
83 }
84
85 func TestTransportMaxPacketWrite(t *testing.T) {
86 buf := &closerBuffer{}
87 tr := newTransport(buf, rand.Reader, true)
88 huge := make([]byte, maxPacket+1)
89 err := tr.writePacket(huge)
90 if err == nil {
91 t.Errorf("transport accepted write for a huge packet.")
92 }
93 }
94
95 func TestTransportMaxPacketReader(t *testing.T) {
96 var header [5]byte
97 huge := make([]byte, maxPacket+128)
98 binary.BigEndian.PutUint32(header[0:], uint32(len(huge)))
99
100 header[4] = 0
101
102 buf := &closerBuffer{}
103 buf.Write(header[:])
104 buf.Write(huge)
105
106 tr := newTransport(buf, rand.Reader, true)
107 _, err := tr.readPacket()
108 if err == nil {
109 t.Errorf("transport succeeded reading huge packet.")
110 } else if !strings.Contains(err.Error(), "large") {
111 t.Errorf("got %q, should mention %q", err.Error(), "large")
112 }
113 }
114
View as plain text