handshake_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // Copyright 2013 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. "bytes"
  7. "crypto/rand"
  8. "errors"
  9. "fmt"
  10. "net"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "testing"
  15. )
  16. type testChecker struct {
  17. calls []string
  18. }
  19. func (t *testChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error {
  20. if dialAddr == "bad" {
  21. return fmt.Errorf("dialAddr is bad")
  22. }
  23. if tcpAddr, ok := addr.(*net.TCPAddr); !ok || tcpAddr == nil {
  24. return fmt.Errorf("testChecker: got %T want *net.TCPAddr", addr)
  25. }
  26. t.calls = append(t.calls, fmt.Sprintf("%s %v %s %x", dialAddr, addr, key.Type(), key.Marshal()))
  27. return nil
  28. }
  29. // netPipe is analogous to net.Pipe, but it uses a real net.Conn, and
  30. // therefore is buffered (net.Pipe deadlocks if both sides start with
  31. // a write.)
  32. func netPipe() (net.Conn, net.Conn, error) {
  33. listener, err := net.Listen("tcp", "127.0.0.1:0")
  34. if err != nil {
  35. return nil, nil, err
  36. }
  37. defer listener.Close()
  38. c1, err := net.Dial("tcp", listener.Addr().String())
  39. if err != nil {
  40. return nil, nil, err
  41. }
  42. c2, err := listener.Accept()
  43. if err != nil {
  44. c1.Close()
  45. return nil, nil, err
  46. }
  47. return c1, c2, nil
  48. }
  49. func handshakePair(clientConf *ClientConfig, addr string) (client *handshakeTransport, server *handshakeTransport, err error) {
  50. a, b, err := netPipe()
  51. if err != nil {
  52. return nil, nil, err
  53. }
  54. trC := newTransport(a, rand.Reader, true)
  55. trS := newTransport(b, rand.Reader, false)
  56. clientConf.SetDefaults()
  57. v := []byte("version")
  58. client = newClientTransport(trC, v, v, clientConf, addr, a.RemoteAddr())
  59. serverConf := &ServerConfig{}
  60. serverConf.AddHostKey(testSigners["ecdsa"])
  61. serverConf.AddHostKey(testSigners["rsa"])
  62. serverConf.SetDefaults()
  63. server = newServerTransport(trS, v, v, serverConf)
  64. return client, server, nil
  65. }
  66. func TestHandshakeBasic(t *testing.T) {
  67. if runtime.GOOS == "plan9" {
  68. t.Skip("see golang.org/issue/7237")
  69. }
  70. checker := &testChecker{}
  71. trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr")
  72. if err != nil {
  73. t.Fatalf("handshakePair: %v", err)
  74. }
  75. defer trC.Close()
  76. defer trS.Close()
  77. go func() {
  78. // Client writes a bunch of stuff, and does a key
  79. // change in the middle. This should not confuse the
  80. // handshake in progress
  81. for i := 0; i < 10; i++ {
  82. p := []byte{msgRequestSuccess, byte(i)}
  83. if err := trC.writePacket(p); err != nil {
  84. t.Fatalf("sendPacket: %v", err)
  85. }
  86. if i == 5 {
  87. // halfway through, we request a key change.
  88. _, _, err := trC.sendKexInit()
  89. if err != nil {
  90. t.Fatalf("sendKexInit: %v", err)
  91. }
  92. }
  93. }
  94. trC.Close()
  95. }()
  96. // Server checks that client messages come in cleanly
  97. i := 0
  98. for {
  99. p, err := trS.readPacket()
  100. if err != nil {
  101. break
  102. }
  103. if p[0] == msgNewKeys {
  104. continue
  105. }
  106. want := []byte{msgRequestSuccess, byte(i)}
  107. if bytes.Compare(p, want) != 0 {
  108. t.Errorf("message %d: got %q, want %q", i, p, want)
  109. }
  110. i++
  111. }
  112. if i != 10 {
  113. t.Errorf("received %d messages, want 10.", i)
  114. }
  115. // If all went well, we registered exactly 1 key change.
  116. if len(checker.calls) != 1 {
  117. t.Fatalf("got %d host key checks, want 1", len(checker.calls))
  118. }
  119. pub := testSigners["ecdsa"].PublicKey()
  120. want := fmt.Sprintf("%s %v %s %x", "addr", trC.remoteAddr, pub.Type(), pub.Marshal())
  121. if want != checker.calls[0] {
  122. t.Errorf("got %q want %q for host key check", checker.calls[0], want)
  123. }
  124. }
  125. func TestHandshakeError(t *testing.T) {
  126. checker := &testChecker{}
  127. trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "bad")
  128. if err != nil {
  129. t.Fatalf("handshakePair: %v", err)
  130. }
  131. defer trC.Close()
  132. defer trS.Close()
  133. // send a packet
  134. packet := []byte{msgRequestSuccess, 42}
  135. if err := trC.writePacket(packet); err != nil {
  136. t.Errorf("writePacket: %v", err)
  137. }
  138. // Now request a key change.
  139. _, _, err = trC.sendKexInit()
  140. if err != nil {
  141. t.Errorf("sendKexInit: %v", err)
  142. }
  143. // the key change will fail, and afterwards we can't write.
  144. if err := trC.writePacket([]byte{msgRequestSuccess, 43}); err == nil {
  145. t.Errorf("writePacket after botched rekey succeeded.")
  146. }
  147. readback, err := trS.readPacket()
  148. if err != nil {
  149. t.Fatalf("server closed too soon: %v", err)
  150. }
  151. if bytes.Compare(readback, packet) != 0 {
  152. t.Errorf("got %q want %q", readback, packet)
  153. }
  154. readback, err = trS.readPacket()
  155. if err == nil {
  156. t.Errorf("got a message %q after failed key change", readback)
  157. }
  158. }
  159. func TestHandshakeTwice(t *testing.T) {
  160. checker := &testChecker{}
  161. trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr")
  162. if err != nil {
  163. t.Fatalf("handshakePair: %v", err)
  164. }
  165. defer trC.Close()
  166. defer trS.Close()
  167. // send a packet
  168. packet := make([]byte, 5)
  169. packet[0] = msgRequestSuccess
  170. if err := trC.writePacket(packet); err != nil {
  171. t.Errorf("writePacket: %v", err)
  172. }
  173. // Now request a key change.
  174. _, _, err = trC.sendKexInit()
  175. if err != nil {
  176. t.Errorf("sendKexInit: %v", err)
  177. }
  178. // Send another packet. Use a fresh one, since writePacket destroys.
  179. packet = make([]byte, 5)
  180. packet[0] = msgRequestSuccess
  181. if err := trC.writePacket(packet); err != nil {
  182. t.Errorf("writePacket: %v", err)
  183. }
  184. // 2nd key change.
  185. _, _, err = trC.sendKexInit()
  186. if err != nil {
  187. t.Errorf("sendKexInit: %v", err)
  188. }
  189. packet = make([]byte, 5)
  190. packet[0] = msgRequestSuccess
  191. if err := trC.writePacket(packet); err != nil {
  192. t.Errorf("writePacket: %v", err)
  193. }
  194. packet = make([]byte, 5)
  195. packet[0] = msgRequestSuccess
  196. for i := 0; i < 5; i++ {
  197. msg, err := trS.readPacket()
  198. if err != nil {
  199. t.Fatalf("server closed too soon: %v", err)
  200. }
  201. if msg[0] == msgNewKeys {
  202. continue
  203. }
  204. if bytes.Compare(msg, packet) != 0 {
  205. t.Errorf("packet %d: got %q want %q", i, msg, packet)
  206. }
  207. }
  208. if len(checker.calls) != 2 {
  209. t.Errorf("got %d key changes, want 2", len(checker.calls))
  210. }
  211. }
  212. func TestHandshakeAutoRekeyWrite(t *testing.T) {
  213. checker := &testChecker{}
  214. clientConf := &ClientConfig{HostKeyCallback: checker.Check}
  215. clientConf.RekeyThreshold = 500
  216. trC, trS, err := handshakePair(clientConf, "addr")
  217. if err != nil {
  218. t.Fatalf("handshakePair: %v", err)
  219. }
  220. defer trC.Close()
  221. defer trS.Close()
  222. for i := 0; i < 5; i++ {
  223. packet := make([]byte, 251)
  224. packet[0] = msgRequestSuccess
  225. if err := trC.writePacket(packet); err != nil {
  226. t.Errorf("writePacket: %v", err)
  227. }
  228. }
  229. j := 0
  230. for ; j < 5; j++ {
  231. _, err := trS.readPacket()
  232. if err != nil {
  233. break
  234. }
  235. }
  236. if j != 5 {
  237. t.Errorf("got %d, want 5 messages", j)
  238. }
  239. if len(checker.calls) != 2 {
  240. t.Errorf("got %d key changes, wanted 2", len(checker.calls))
  241. }
  242. }
  243. type syncChecker struct {
  244. called chan int
  245. }
  246. func (t *syncChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error {
  247. t.called <- 1
  248. return nil
  249. }
  250. func TestHandshakeAutoRekeyRead(t *testing.T) {
  251. sync := &syncChecker{make(chan int, 2)}
  252. clientConf := &ClientConfig{
  253. HostKeyCallback: sync.Check,
  254. }
  255. clientConf.RekeyThreshold = 500
  256. trC, trS, err := handshakePair(clientConf, "addr")
  257. if err != nil {
  258. t.Fatalf("handshakePair: %v", err)
  259. }
  260. defer trC.Close()
  261. defer trS.Close()
  262. packet := make([]byte, 501)
  263. packet[0] = msgRequestSuccess
  264. if err := trS.writePacket(packet); err != nil {
  265. t.Fatalf("writePacket: %v", err)
  266. }
  267. // While we read out the packet, a key change will be
  268. // initiated.
  269. if _, err := trC.readPacket(); err != nil {
  270. t.Fatalf("readPacket(client): %v", err)
  271. }
  272. <-sync.called
  273. }
  274. // errorKeyingTransport generates errors after a given number of
  275. // read/write operations.
  276. type errorKeyingTransport struct {
  277. packetConn
  278. readLeft, writeLeft int
  279. }
  280. func (n *errorKeyingTransport) prepareKeyChange(*algorithms, *kexResult) error {
  281. return nil
  282. }
  283. func (n *errorKeyingTransport) getSessionID() []byte {
  284. return nil
  285. }
  286. func (n *errorKeyingTransport) writePacket(packet []byte) error {
  287. if n.writeLeft == 0 {
  288. n.Close()
  289. return errors.New("barf")
  290. }
  291. n.writeLeft--
  292. return n.packetConn.writePacket(packet)
  293. }
  294. func (n *errorKeyingTransport) readPacket() ([]byte, error) {
  295. if n.readLeft == 0 {
  296. n.Close()
  297. return nil, errors.New("barf")
  298. }
  299. n.readLeft--
  300. return n.packetConn.readPacket()
  301. }
  302. func TestHandshakeErrorHandlingRead(t *testing.T) {
  303. for i := 0; i < 20; i++ {
  304. testHandshakeErrorHandlingN(t, i, -1)
  305. }
  306. }
  307. func TestHandshakeErrorHandlingWrite(t *testing.T) {
  308. for i := 0; i < 20; i++ {
  309. testHandshakeErrorHandlingN(t, -1, i)
  310. }
  311. }
  312. // testHandshakeErrorHandlingN runs handshakes, injecting errors. If
  313. // handshakeTransport deadlocks, the go runtime will detect it and
  314. // panic.
  315. func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int) {
  316. msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)})
  317. a, b := memPipe()
  318. defer a.Close()
  319. defer b.Close()
  320. key := testSigners["ecdsa"]
  321. serverConf := Config{RekeyThreshold: minRekeyThreshold}
  322. serverConf.SetDefaults()
  323. serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'})
  324. serverConn.hostKeys = []Signer{key}
  325. go serverConn.readLoop()
  326. clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold}
  327. clientConf.SetDefaults()
  328. clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'})
  329. clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()}
  330. go clientConn.readLoop()
  331. var wg sync.WaitGroup
  332. wg.Add(4)
  333. for _, hs := range []packetConn{serverConn, clientConn} {
  334. go func(c packetConn) {
  335. for {
  336. err := c.writePacket(msg)
  337. if err != nil {
  338. break
  339. }
  340. }
  341. wg.Done()
  342. }(hs)
  343. go func(c packetConn) {
  344. for {
  345. _, err := c.readPacket()
  346. if err != nil {
  347. break
  348. }
  349. }
  350. wg.Done()
  351. }(hs)
  352. }
  353. wg.Wait()
  354. }