transport.go 7.7 KB

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