client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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, 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. msg := decode(packet)
  226. switch msg := msg.(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 *globalRequestSuccessMsg, *globalRequestFailureMsg:
  286. c.globalRequest.response <- msg
  287. case *disconnectMsg:
  288. return
  289. default:
  290. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  291. }
  292. }
  293. }
  294. }
  295. // Handle channel open messages from the remote side.
  296. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  297. switch msg.ChanType {
  298. case "forwarded-tcpip":
  299. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  300. if !ok {
  301. // invalid request
  302. c.sendConnectionFailed(msg.PeersId)
  303. return
  304. }
  305. l, ok := c.forwardList.lookup(laddr)
  306. if !ok {
  307. fmt.Println("could not find forward list entry for", laddr)
  308. // Section 7.2, implementations MUST reject suprious incoming
  309. // connections.
  310. c.sendConnectionFailed(msg.PeersId)
  311. return
  312. }
  313. raddr, rest, ok := parseTCPAddr(rest)
  314. if !ok {
  315. // invalid request
  316. c.sendConnectionFailed(msg.PeersId)
  317. return
  318. }
  319. ch := c.newChan(c.transport)
  320. ch.remoteId = msg.PeersId
  321. ch.remoteWin.add(msg.PeersWindow)
  322. m := channelOpenConfirmMsg{
  323. PeersId: ch.remoteId,
  324. MyId: ch.localId,
  325. MyWindow: 1 << 14,
  326. MaxPacketSize: 1 << 15, // RFC 4253 6.1
  327. }
  328. c.writePacket(marshal(msgChannelOpenConfirm, m))
  329. l <- forward{ch, raddr}
  330. default:
  331. // unknown channel type
  332. m := channelOpenFailureMsg{
  333. PeersId: msg.PeersId,
  334. Reason: UnknownChannelType,
  335. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  336. Language: "en_US.UTF-8",
  337. }
  338. c.writePacket(marshal(msgChannelOpenFailure, m))
  339. }
  340. }
  341. // sendGlobalRequest sends a global request message as specified
  342. // in RFC4254 section 4. To correctly synchronise messages, a lock
  343. // is held internally until a response is returned.
  344. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  345. c.globalRequest.Lock()
  346. defer c.globalRequest.Unlock()
  347. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  348. return nil, err
  349. }
  350. r := <-c.globalRequest.response
  351. if r, ok := r.(*globalRequestSuccessMsg); ok {
  352. return r, nil
  353. }
  354. return nil, errors.New("request failed")
  355. }
  356. // sendConnectionFailed rejects an incoming channel identified
  357. // by remoteId.
  358. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  359. m := channelOpenFailureMsg{
  360. PeersId: remoteId,
  361. Reason: ConnectionFailed,
  362. Message: "invalid request",
  363. Language: "en_US.UTF-8",
  364. }
  365. return c.writePacket(marshal(msgChannelOpenFailure, m))
  366. }
  367. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  368. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  369. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  370. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  371. addr, b, ok := parseString(b)
  372. if !ok {
  373. return nil, b, false
  374. }
  375. port, b, ok := parseUint32(b)
  376. if !ok {
  377. return nil, b, false
  378. }
  379. ip := net.ParseIP(string(addr))
  380. if ip == nil {
  381. return nil, b, false
  382. }
  383. return &net.TCPAddr{ip, int(port)}, b, true
  384. }
  385. // Dial connects to the given network address using net.Dial and
  386. // then initiates a SSH handshake, returning the resulting client connection.
  387. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  388. conn, err := net.Dial(network, addr)
  389. if err != nil {
  390. return nil, err
  391. }
  392. return Client(conn, config)
  393. }
  394. // A ClientConfig structure is used to configure a ClientConn. After one has
  395. // been passed to an SSH function it must not be modified.
  396. type ClientConfig struct {
  397. // Rand provides the source of entropy for key exchange. If Rand is
  398. // nil, the cryptographic random reader in package crypto/rand will
  399. // be used.
  400. Rand io.Reader
  401. // The username to authenticate.
  402. User string
  403. // A slice of ClientAuth methods. Only the first instance
  404. // of a particular RFC 4252 method will be used during authentication.
  405. Auth []ClientAuth
  406. // Cryptographic-related configuration.
  407. Crypto CryptoConfig
  408. }
  409. func (c *ClientConfig) rand() io.Reader {
  410. if c.Rand == nil {
  411. return rand.Reader
  412. }
  413. return c.Rand
  414. }
  415. // Thread safe channel list.
  416. type chanList struct {
  417. // protects concurrent access to chans
  418. sync.Mutex
  419. // chans are indexed by the local id of the channel, clientChan.localId.
  420. // The PeersId value of messages received by ClientConn.mainLoop is
  421. // used to locate the right local clientChan in this slice.
  422. chans []*clientChan
  423. }
  424. // Allocate a new ClientChan with the next avail local id.
  425. func (c *chanList) newChan(t *transport) *clientChan {
  426. c.Lock()
  427. defer c.Unlock()
  428. for i := range c.chans {
  429. if c.chans[i] == nil {
  430. ch := newClientChan(t, uint32(i))
  431. c.chans[i] = ch
  432. return ch
  433. }
  434. }
  435. i := len(c.chans)
  436. ch := newClientChan(t, uint32(i))
  437. c.chans = append(c.chans, ch)
  438. return ch
  439. }
  440. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  441. c.Lock()
  442. defer c.Unlock()
  443. if id >= uint32(len(c.chans)) {
  444. return nil, false
  445. }
  446. return c.chans[id], true
  447. }
  448. func (c *chanList) remove(id uint32) {
  449. c.Lock()
  450. defer c.Unlock()
  451. c.chans[id] = nil
  452. }
  453. func (c *chanList) closeAll() {
  454. c.Lock()
  455. defer c.Unlock()
  456. for _, ch := range c.chans {
  457. if ch == nil {
  458. continue
  459. }
  460. ch.Close()
  461. close(ch.msg)
  462. }
  463. }