transport.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. "bufio"
  7. "crypto"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "errors"
  11. "hash"
  12. "io"
  13. "net"
  14. "sync"
  15. )
  16. const (
  17. packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher.
  18. minPacketSize = 16
  19. maxPacketSize = 36000
  20. minPaddingSize = 4 // TODO(huin) should this be configurable?
  21. )
  22. // filteredConn reduces the set of methods exposed when embeddeding
  23. // a net.Conn inside ssh.transport.
  24. // TODO(dfc) suggestions for a better name will be warmly received.
  25. type filteredConn interface {
  26. // Close closes the connection.
  27. Close() error
  28. // LocalAddr returns the local network address.
  29. LocalAddr() net.Addr
  30. // RemoteAddr returns the remote network address.
  31. RemoteAddr() net.Addr
  32. }
  33. // Types implementing packetWriter provide the ability to send packets to
  34. // an SSH peer.
  35. type packetWriter interface {
  36. // Encrypt and send a packet of data to the remote peer.
  37. writePacket(packet []byte) error
  38. }
  39. // transport represents the SSH connection to the remote peer.
  40. type transport struct {
  41. reader
  42. writer
  43. filteredConn
  44. }
  45. // reader represents the incoming connection state.
  46. type reader struct {
  47. io.Reader
  48. common
  49. }
  50. // writer represnts the outgoing connection state.
  51. type writer struct {
  52. *sync.Mutex // protects writer.Writer from concurrent writes
  53. *bufio.Writer
  54. rand io.Reader
  55. common
  56. }
  57. // common represents the cipher state needed to process messages in a single
  58. // direction.
  59. type common struct {
  60. seqNum uint32
  61. mac hash.Hash
  62. cipher cipher.Stream
  63. cipherAlgo string
  64. macAlgo string
  65. compressionAlgo string
  66. }
  67. // Read and decrypt a single packet from the remote peer.
  68. func (r *reader) readOnePacket() ([]byte, error) {
  69. var lengthBytes = make([]byte, 5)
  70. var macSize uint32
  71. if _, err := io.ReadFull(r, lengthBytes); err != nil {
  72. return nil, err
  73. }
  74. r.cipher.XORKeyStream(lengthBytes, lengthBytes)
  75. if r.mac != nil {
  76. r.mac.Reset()
  77. seqNumBytes := []byte{
  78. byte(r.seqNum >> 24),
  79. byte(r.seqNum >> 16),
  80. byte(r.seqNum >> 8),
  81. byte(r.seqNum),
  82. }
  83. r.mac.Write(seqNumBytes)
  84. r.mac.Write(lengthBytes)
  85. macSize = uint32(r.mac.Size())
  86. }
  87. length := uint32(lengthBytes[0])<<24 | uint32(lengthBytes[1])<<16 | uint32(lengthBytes[2])<<8 | uint32(lengthBytes[3])
  88. paddingLength := uint32(lengthBytes[4])
  89. if length <= paddingLength+1 {
  90. return nil, errors.New("invalid packet length")
  91. }
  92. if length > maxPacketSize {
  93. return nil, errors.New("packet too large")
  94. }
  95. packet := make([]byte, length-1+macSize)
  96. if _, err := io.ReadFull(r, packet); err != nil {
  97. return nil, err
  98. }
  99. mac := packet[length-1:]
  100. r.cipher.XORKeyStream(packet, packet[:length-1])
  101. if r.mac != nil {
  102. r.mac.Write(packet[:length-1])
  103. if subtle.ConstantTimeCompare(r.mac.Sum(nil), mac) != 1 {
  104. return nil, errors.New("ssh: MAC failure")
  105. }
  106. }
  107. r.seqNum++
  108. return packet[:length-paddingLength-1], nil
  109. }
  110. // Read and decrypt next packet discarding debug and noop messages.
  111. func (t *transport) readPacket() ([]byte, error) {
  112. for {
  113. packet, err := t.readOnePacket()
  114. if err != nil {
  115. return nil, err
  116. }
  117. if packet[0] != msgIgnore && packet[0] != msgDebug {
  118. return packet, nil
  119. }
  120. }
  121. panic("unreachable")
  122. }
  123. // Encrypt and send a packet of data to the remote peer.
  124. func (w *writer) writePacket(packet []byte) error {
  125. w.Mutex.Lock()
  126. defer w.Mutex.Unlock()
  127. paddingLength := packetSizeMultiple - (5+len(packet))%packetSizeMultiple
  128. if paddingLength < 4 {
  129. paddingLength += packetSizeMultiple
  130. }
  131. length := len(packet) + 1 + paddingLength
  132. lengthBytes := []byte{
  133. byte(length >> 24),
  134. byte(length >> 16),
  135. byte(length >> 8),
  136. byte(length),
  137. byte(paddingLength),
  138. }
  139. padding := make([]byte, paddingLength)
  140. _, err := io.ReadFull(w.rand, padding)
  141. if err != nil {
  142. return err
  143. }
  144. if w.mac != nil {
  145. w.mac.Reset()
  146. seqNumBytes := []byte{
  147. byte(w.seqNum >> 24),
  148. byte(w.seqNum >> 16),
  149. byte(w.seqNum >> 8),
  150. byte(w.seqNum),
  151. }
  152. w.mac.Write(seqNumBytes)
  153. w.mac.Write(lengthBytes)
  154. w.mac.Write(packet)
  155. w.mac.Write(padding)
  156. }
  157. // TODO(dfc) lengthBytes, packet and padding should be
  158. // subslices of a single buffer
  159. w.cipher.XORKeyStream(lengthBytes, lengthBytes)
  160. w.cipher.XORKeyStream(packet, packet)
  161. w.cipher.XORKeyStream(padding, padding)
  162. if _, err := w.Write(lengthBytes); err != nil {
  163. return err
  164. }
  165. if _, err := w.Write(packet); err != nil {
  166. return err
  167. }
  168. if _, err := w.Write(padding); err != nil {
  169. return err
  170. }
  171. if w.mac != nil {
  172. if _, err := w.Write(w.mac.Sum(nil)); err != nil {
  173. return err
  174. }
  175. }
  176. if err := w.Flush(); err != nil {
  177. return err
  178. }
  179. w.seqNum++
  180. return err
  181. }
  182. // Send a message to the remote peer
  183. func (t *transport) sendMessage(typ uint8, msg interface{}) error {
  184. packet := marshal(typ, msg)
  185. return t.writePacket(packet)
  186. }
  187. func newTransport(conn net.Conn, rand io.Reader) *transport {
  188. return &transport{
  189. reader: reader{
  190. Reader: bufio.NewReader(conn),
  191. common: common{
  192. cipher: noneCipher{},
  193. },
  194. },
  195. writer: writer{
  196. Writer: bufio.NewWriter(conn),
  197. rand: rand,
  198. Mutex: new(sync.Mutex),
  199. common: common{
  200. cipher: noneCipher{},
  201. },
  202. },
  203. filteredConn: conn,
  204. }
  205. }
  206. type direction struct {
  207. ivTag []byte
  208. keyTag []byte
  209. macKeyTag []byte
  210. }
  211. // TODO(dfc) can this be made a constant ?
  212. var (
  213. serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}}
  214. clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}}
  215. )
  216. // setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
  217. // described in RFC 4253, section 6.4. direction should either be serverKeys
  218. // (to setup server->client keys) or clientKeys (for client->server keys).
  219. func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error {
  220. cipherMode := cipherModes[c.cipherAlgo]
  221. macMode := macModes[c.macAlgo]
  222. iv := make([]byte, cipherMode.ivSize)
  223. key := make([]byte, cipherMode.keySize)
  224. macKey := make([]byte, macMode.keySize)
  225. h := hashFunc.New()
  226. generateKeyMaterial(iv, d.ivTag, K, H, sessionId, h)
  227. generateKeyMaterial(key, d.keyTag, K, H, sessionId, h)
  228. generateKeyMaterial(macKey, d.macKeyTag, K, H, sessionId, h)
  229. c.mac = macMode.new(macKey)
  230. var err error
  231. c.cipher, err = cipherMode.createCipher(key, iv)
  232. return err
  233. }
  234. // generateKeyMaterial fills out with key material generated from tag, K, H
  235. // and sessionId, as specified in RFC 4253, section 7.2.
  236. func generateKeyMaterial(out, tag []byte, K, H, sessionId []byte, h hash.Hash) {
  237. var digestsSoFar []byte
  238. for len(out) > 0 {
  239. h.Reset()
  240. h.Write(K)
  241. h.Write(H)
  242. if len(digestsSoFar) == 0 {
  243. h.Write(tag)
  244. h.Write(sessionId)
  245. } else {
  246. h.Write(digestsSoFar)
  247. }
  248. digest := h.Sum(nil)
  249. n := copy(out, digest)
  250. out = out[n:]
  251. if len(out) > 0 {
  252. digestsSoFar = append(digestsSoFar, digest...)
  253. }
  254. }
  255. }
  256. // maxVersionStringBytes is the maximum number of bytes that we'll accept as a
  257. // version string. In the event that the client is talking a different protocol
  258. // we need to set a limit otherwise we will keep using more and more memory
  259. // while searching for the end of the version handshake.
  260. const maxVersionStringBytes = 1024
  261. // Read version string as specified by RFC 4253, section 4.2.
  262. func readVersion(r io.Reader) ([]byte, error) {
  263. versionString := make([]byte, 0, 64)
  264. var ok bool
  265. var buf [1]byte
  266. forEachByte:
  267. for len(versionString) < maxVersionStringBytes {
  268. _, err := io.ReadFull(r, buf[:])
  269. if err != nil {
  270. return nil, err
  271. }
  272. // The RFC says that the version should be terminated with \r\n
  273. // but several SSH servers actually only send a \n.
  274. if buf[0] == '\n' {
  275. ok = true
  276. break forEachByte
  277. }
  278. versionString = append(versionString, buf[0])
  279. }
  280. if !ok {
  281. return nil, errors.New("ssh: failed to read version string")
  282. }
  283. // There might be a '\r' on the end which we should remove.
  284. if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' {
  285. versionString = versionString[:len(versionString)-1]
  286. }
  287. return versionString, nil
  288. }