transport.go 7.8 KB

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