client.go 13 KB

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