client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. // Copyright 2011 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. "crypto/rand"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "sync"
  13. )
  14. // clientVersion is the default identification string that the client will use.
  15. var clientVersion = []byte("SSH-2.0-Go")
  16. // ClientConn represents the client side of an SSH connection.
  17. type ClientConn struct {
  18. *transport
  19. config *ClientConfig
  20. chanList // channels associated with this connection
  21. forwardList // forwarded tcpip connections from the remote side
  22. globalRequest
  23. // Address as passed to the Dial function.
  24. dialAddress string
  25. serverVersion string
  26. }
  27. type globalRequest struct {
  28. sync.Mutex
  29. response chan interface{}
  30. }
  31. // Client returns a new SSH client connection using c as the underlying transport.
  32. func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) {
  33. return clientWithAddress(c, "", config)
  34. }
  35. func clientWithAddress(c net.Conn, addr string, config *ClientConfig) (*ClientConn, error) {
  36. conn := &ClientConn{
  37. transport: newTransport(c, config.rand()),
  38. config: config,
  39. globalRequest: globalRequest{response: make(chan interface{}, 1)},
  40. dialAddress: addr,
  41. }
  42. if err := conn.handshake(); err != nil {
  43. conn.Close()
  44. return nil, fmt.Errorf("handshake failed: %v", err)
  45. }
  46. go conn.mainLoop()
  47. return conn, nil
  48. }
  49. // handshake performs the client side key exchange. See RFC 4253 Section 7.
  50. func (c *ClientConn) handshake() error {
  51. var myVersion []byte
  52. if len(c.config.ClientVersion) > 0 {
  53. myVersion = []byte(c.config.ClientVersion)
  54. } else {
  55. myVersion = clientVersion
  56. }
  57. if _, err := c.Write(append(myVersion, '\r', '\n')); err != nil {
  58. return err
  59. }
  60. if err := c.Flush(); err != nil {
  61. return err
  62. }
  63. // read remote server version
  64. serverVersion, err := readVersion(c)
  65. if err != nil {
  66. return err
  67. }
  68. c.serverVersion = string(serverVersion)
  69. clientKexInit := kexInitMsg{
  70. KexAlgos: c.config.Crypto.kexes(),
  71. ServerHostKeyAlgos: supportedHostKeyAlgos,
  72. CiphersClientServer: c.config.Crypto.ciphers(),
  73. CiphersServerClient: c.config.Crypto.ciphers(),
  74. MACsClientServer: c.config.Crypto.macs(),
  75. MACsServerClient: c.config.Crypto.macs(),
  76. CompressionClientServer: supportedCompressions,
  77. CompressionServerClient: supportedCompressions,
  78. }
  79. kexInitPacket := marshal(msgKexInit, clientKexInit)
  80. if err := c.writePacket(kexInitPacket); err != nil {
  81. return err
  82. }
  83. packet, err := c.readPacket()
  84. if err != nil {
  85. return err
  86. }
  87. var serverKexInit kexInitMsg
  88. if err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {
  89. return err
  90. }
  91. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)
  92. if !ok {
  93. return errors.New("ssh: no common algorithms")
  94. }
  95. if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {
  96. // The server sent a Kex message for the wrong algorithm,
  97. // which we have to ignore.
  98. if _, err := c.readPacket(); err != nil {
  99. return err
  100. }
  101. }
  102. kex, ok := kexAlgoMap[kexAlgo]
  103. if !ok {
  104. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", kexAlgo)
  105. }
  106. magics := handshakeMagics{
  107. clientVersion: myVersion,
  108. serverVersion: serverVersion,
  109. clientKexInit: kexInitPacket,
  110. serverKexInit: packet,
  111. }
  112. result, err := kex.Client(c, c.config.rand(), &magics)
  113. if err != nil {
  114. return err
  115. }
  116. err = verifyHostKeySignature(hostKeyAlgo, result.HostKey, result.H, result.Signature)
  117. if err != nil {
  118. return err
  119. }
  120. if checker := c.config.HostKeyChecker; checker != nil {
  121. err = checker.Check(c.dialAddress, c.RemoteAddr(), hostKeyAlgo, result.HostKey)
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. if err = c.writePacket([]byte{msgNewKeys}); err != nil {
  127. return err
  128. }
  129. if err = c.transport.writer.setupKeys(clientKeys, result.K, result.H, result.H, kex.Hash()); err != nil {
  130. return err
  131. }
  132. if packet, err = c.readPacket(); err != nil {
  133. return err
  134. }
  135. if packet[0] != msgNewKeys {
  136. return UnexpectedMessageError{msgNewKeys, packet[0]}
  137. }
  138. if err := c.transport.reader.setupKeys(serverKeys, result.K, result.H, result.H, kex.Hash()); err != nil {
  139. return err
  140. }
  141. return c.authenticate(result.H)
  142. }
  143. // Verify the host key obtained in the key exchange.
  144. func verifyHostKeySignature(hostKeyAlgo string, hostKeyBytes []byte, data []byte, signature []byte) error {
  145. hostKey, rest, ok := ParsePublicKey(hostKeyBytes)
  146. if len(rest) > 0 || !ok {
  147. return errors.New("ssh: could not parse hostkey")
  148. }
  149. sig, rest, ok := parseSignatureBody(signature)
  150. if len(rest) > 0 || !ok {
  151. return errors.New("ssh: signature parse error")
  152. }
  153. if sig.Format != hostKeyAlgo {
  154. return fmt.Errorf("ssh: unexpected signature type %q", sig.Format)
  155. }
  156. if !hostKey.Verify(data, sig.Blob) {
  157. return errors.New("ssh: host key signature error")
  158. }
  159. return nil
  160. }
  161. // mainLoop reads incoming messages and routes channel messages
  162. // to their respective ClientChans.
  163. func (c *ClientConn) mainLoop() {
  164. defer func() {
  165. c.Close()
  166. c.chanList.closeAll()
  167. c.forwardList.closeAll()
  168. }()
  169. for {
  170. packet, err := c.readPacket()
  171. if err != nil {
  172. break
  173. }
  174. // TODO(dfc) A note on blocking channel use.
  175. // The msg, data and dataExt channels of a clientChan can
  176. // cause this loop to block indefinately if the consumer does
  177. // not service them.
  178. switch packet[0] {
  179. case msgChannelData:
  180. if len(packet) < 9 {
  181. // malformed data packet
  182. return
  183. }
  184. remoteId := binary.BigEndian.Uint32(packet[1:5])
  185. length := binary.BigEndian.Uint32(packet[5:9])
  186. packet = packet[9:]
  187. if length != uint32(len(packet)) {
  188. return
  189. }
  190. ch, ok := c.getChan(remoteId)
  191. if !ok {
  192. return
  193. }
  194. ch.stdout.write(packet)
  195. case msgChannelExtendedData:
  196. if len(packet) < 13 {
  197. // malformed data packet
  198. return
  199. }
  200. remoteId := binary.BigEndian.Uint32(packet[1:5])
  201. datatype := binary.BigEndian.Uint32(packet[5:9])
  202. length := binary.BigEndian.Uint32(packet[9:13])
  203. packet = packet[13:]
  204. if length != uint32(len(packet)) {
  205. return
  206. }
  207. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  208. // for stderr on interactive sessions. Other data types are
  209. // silently discarded.
  210. if datatype == 1 {
  211. ch, ok := c.getChan(remoteId)
  212. if !ok {
  213. return
  214. }
  215. ch.stderr.write(packet)
  216. }
  217. default:
  218. decoded, err := decode(packet)
  219. if err != nil {
  220. if _, ok := err.(UnexpectedMessageError); ok {
  221. fmt.Printf("mainLoop: unexpected message: %v\n", err)
  222. continue
  223. }
  224. return
  225. }
  226. switch msg := decoded.(type) {
  227. case *channelOpenMsg:
  228. c.handleChanOpen(msg)
  229. case *channelOpenConfirmMsg:
  230. ch, ok := c.getChan(msg.PeersId)
  231. if !ok {
  232. return
  233. }
  234. ch.msg <- msg
  235. case *channelOpenFailureMsg:
  236. ch, ok := c.getChan(msg.PeersId)
  237. if !ok {
  238. return
  239. }
  240. ch.msg <- msg
  241. case *channelCloseMsg:
  242. ch, ok := c.getChan(msg.PeersId)
  243. if !ok {
  244. return
  245. }
  246. ch.Close()
  247. close(ch.msg)
  248. c.chanList.remove(msg.PeersId)
  249. case *channelEOFMsg:
  250. ch, ok := c.getChan(msg.PeersId)
  251. if !ok {
  252. return
  253. }
  254. ch.stdout.eof()
  255. // RFC 4254 is mute on how EOF affects dataExt messages but
  256. // it is logical to signal EOF at the same time.
  257. ch.stderr.eof()
  258. case *channelRequestSuccessMsg:
  259. ch, ok := c.getChan(msg.PeersId)
  260. if !ok {
  261. return
  262. }
  263. ch.msg <- msg
  264. case *channelRequestFailureMsg:
  265. ch, ok := c.getChan(msg.PeersId)
  266. if !ok {
  267. return
  268. }
  269. ch.msg <- msg
  270. case *channelRequestMsg:
  271. ch, ok := c.getChan(msg.PeersId)
  272. if !ok {
  273. return
  274. }
  275. ch.msg <- msg
  276. case *windowAdjustMsg:
  277. ch, ok := c.getChan(msg.PeersId)
  278. if !ok {
  279. return
  280. }
  281. if !ch.remoteWin.add(msg.AdditionalBytes) {
  282. // invalid window update
  283. return
  284. }
  285. case *globalRequestMsg:
  286. // This handles keepalive messages and matches
  287. // the behaviour of OpenSSH.
  288. if msg.WantReply {
  289. c.writePacket(marshal(msgRequestFailure, globalRequestFailureMsg{}))
  290. }
  291. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  292. c.globalRequest.response <- msg
  293. case *disconnectMsg:
  294. return
  295. default:
  296. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  297. }
  298. }
  299. }
  300. }
  301. // Handle channel open messages from the remote side.
  302. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  303. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  304. c.sendConnectionFailed(msg.PeersId)
  305. }
  306. switch msg.ChanType {
  307. case "forwarded-tcpip":
  308. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  309. if !ok {
  310. // invalid request
  311. c.sendConnectionFailed(msg.PeersId)
  312. return
  313. }
  314. l, ok := c.forwardList.lookup(*laddr)
  315. if !ok {
  316. // TODO: print on a more structured log.
  317. fmt.Println("could not find forward list entry for", laddr)
  318. // Section 7.2, implementations MUST reject suprious incoming
  319. // connections.
  320. c.sendConnectionFailed(msg.PeersId)
  321. return
  322. }
  323. raddr, rest, ok := parseTCPAddr(rest)
  324. if !ok {
  325. // invalid request
  326. c.sendConnectionFailed(msg.PeersId)
  327. return
  328. }
  329. ch := c.newChan(c.transport)
  330. ch.remoteId = msg.PeersId
  331. ch.remoteWin.add(msg.PeersWindow)
  332. ch.maxPacket = msg.MaxPacketSize
  333. m := channelOpenConfirmMsg{
  334. PeersId: ch.remoteId,
  335. MyId: ch.localId,
  336. MyWindow: 1 << 14,
  337. // As per RFC 4253 6.1, 32k is also the minimum.
  338. MaxPacketSize: 1 << 15,
  339. }
  340. c.writePacket(marshal(msgChannelOpenConfirm, m))
  341. l <- forward{ch, raddr}
  342. default:
  343. // unknown channel type
  344. m := channelOpenFailureMsg{
  345. PeersId: msg.PeersId,
  346. Reason: UnknownChannelType,
  347. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  348. Language: "en_US.UTF-8",
  349. }
  350. c.writePacket(marshal(msgChannelOpenFailure, m))
  351. }
  352. }
  353. // sendGlobalRequest sends a global request message as specified
  354. // in RFC4254 section 4. To correctly synchronise messages, a lock
  355. // is held internally until a response is returned.
  356. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  357. c.globalRequest.Lock()
  358. defer c.globalRequest.Unlock()
  359. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  360. return nil, err
  361. }
  362. r := <-c.globalRequest.response
  363. if r, ok := r.(*globalRequestSuccessMsg); ok {
  364. return r, nil
  365. }
  366. return nil, errors.New("request failed")
  367. }
  368. // sendConnectionFailed rejects an incoming channel identified
  369. // by remoteId.
  370. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  371. m := channelOpenFailureMsg{
  372. PeersId: remoteId,
  373. Reason: ConnectionFailed,
  374. Message: "invalid request",
  375. Language: "en_US.UTF-8",
  376. }
  377. return c.writePacket(marshal(msgChannelOpenFailure, m))
  378. }
  379. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  380. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  381. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  382. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  383. addr, b, ok := parseString(b)
  384. if !ok {
  385. return nil, b, false
  386. }
  387. port, b, ok := parseUint32(b)
  388. if !ok {
  389. return nil, b, false
  390. }
  391. ip := net.ParseIP(string(addr))
  392. if ip == nil {
  393. return nil, b, false
  394. }
  395. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  396. }
  397. // Dial connects to the given network address using net.Dial and
  398. // then initiates a SSH handshake, returning the resulting client connection.
  399. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  400. conn, err := net.Dial(network, addr)
  401. if err != nil {
  402. return nil, err
  403. }
  404. return clientWithAddress(conn, addr, config)
  405. }
  406. // A ClientConfig structure is used to configure a ClientConn. After one has
  407. // been passed to an SSH function it must not be modified.
  408. type ClientConfig struct {
  409. // Rand provides the source of entropy for key exchange. If Rand is
  410. // nil, the cryptographic random reader in package crypto/rand will
  411. // be used.
  412. Rand io.Reader
  413. // The username to authenticate.
  414. User string
  415. // A slice of ClientAuth methods. Only the first instance
  416. // of a particular RFC 4252 method will be used during authentication.
  417. Auth []ClientAuth
  418. // HostKeyChecker, if not nil, is called during the cryptographic
  419. // handshake to validate the server's host key. A nil HostKeyChecker
  420. // implies that all host keys are accepted.
  421. HostKeyChecker HostKeyChecker
  422. // Cryptographic-related configuration.
  423. Crypto CryptoConfig
  424. // The identification string that will be used for the connection.
  425. // If empty, a reasonable default is used.
  426. ClientVersion string
  427. }
  428. func (c *ClientConfig) rand() io.Reader {
  429. if c.Rand == nil {
  430. return rand.Reader
  431. }
  432. return c.Rand
  433. }
  434. // Thread safe channel list.
  435. type chanList struct {
  436. // protects concurrent access to chans
  437. sync.Mutex
  438. // chans are indexed by the local id of the channel, clientChan.localId.
  439. // The PeersId value of messages received by ClientConn.mainLoop is
  440. // used to locate the right local clientChan in this slice.
  441. chans []*clientChan
  442. }
  443. // Allocate a new ClientChan with the next avail local id.
  444. func (c *chanList) newChan(p packetConn) *clientChan {
  445. c.Lock()
  446. defer c.Unlock()
  447. for i := range c.chans {
  448. if c.chans[i] == nil {
  449. ch := newClientChan(p, uint32(i))
  450. c.chans[i] = ch
  451. return ch
  452. }
  453. }
  454. i := len(c.chans)
  455. ch := newClientChan(p, uint32(i))
  456. c.chans = append(c.chans, ch)
  457. return ch
  458. }
  459. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  460. c.Lock()
  461. defer c.Unlock()
  462. if id >= uint32(len(c.chans)) {
  463. return nil, false
  464. }
  465. return c.chans[id], true
  466. }
  467. func (c *chanList) remove(id uint32) {
  468. c.Lock()
  469. defer c.Unlock()
  470. c.chans[id] = nil
  471. }
  472. func (c *chanList) closeAll() {
  473. c.Lock()
  474. defer c.Unlock()
  475. for _, ch := range c.chans {
  476. if ch == nil {
  477. continue
  478. }
  479. ch.Close()
  480. close(ch.msg)
  481. }
  482. }