client.go 13 KB

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