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