transport.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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("ssh: invalid packet length")
  91. }
  92. if length > maxPacketSize {
  93. return nil, errors.New("ssh: 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 len(packet) == 0 {
  118. return nil, errors.New("ssh: zero length packet")
  119. }
  120. if packet[0] != msgIgnore && packet[0] != msgDebug {
  121. return packet, nil
  122. }
  123. }
  124. panic("unreachable")
  125. }
  126. // Encrypt and send a packet of data to the remote peer.
  127. func (w *writer) writePacket(packet []byte) error {
  128. w.Mutex.Lock()
  129. defer w.Mutex.Unlock()
  130. paddingLength := packetSizeMultiple - (5+len(packet))%packetSizeMultiple
  131. if paddingLength < 4 {
  132. paddingLength += packetSizeMultiple
  133. }
  134. length := len(packet) + 1 + paddingLength
  135. lengthBytes := []byte{
  136. byte(length >> 24),
  137. byte(length >> 16),
  138. byte(length >> 8),
  139. byte(length),
  140. byte(paddingLength),
  141. }
  142. padding := make([]byte, paddingLength)
  143. _, err := io.ReadFull(w.rand, padding)
  144. if err != nil {
  145. return err
  146. }
  147. if w.mac != nil {
  148. w.mac.Reset()
  149. seqNumBytes := []byte{
  150. byte(w.seqNum >> 24),
  151. byte(w.seqNum >> 16),
  152. byte(w.seqNum >> 8),
  153. byte(w.seqNum),
  154. }
  155. w.mac.Write(seqNumBytes)
  156. w.mac.Write(lengthBytes)
  157. w.mac.Write(packet)
  158. w.mac.Write(padding)
  159. }
  160. // TODO(dfc) lengthBytes, packet and padding should be
  161. // subslices of a single buffer
  162. w.cipher.XORKeyStream(lengthBytes, lengthBytes)
  163. w.cipher.XORKeyStream(packet, packet)
  164. w.cipher.XORKeyStream(padding, padding)
  165. if _, err := w.Write(lengthBytes); err != nil {
  166. return err
  167. }
  168. if _, err := w.Write(packet); err != nil {
  169. return err
  170. }
  171. if _, err := w.Write(padding); err != nil {
  172. return err
  173. }
  174. if w.mac != nil {
  175. if _, err := w.Write(w.mac.Sum(nil)); err != nil {
  176. return err
  177. }
  178. }
  179. if err := w.Flush(); err != nil {
  180. return err
  181. }
  182. w.seqNum++
  183. return err
  184. }
  185. // Send a message to the remote peer
  186. func (t *transport) sendMessage(typ uint8, msg interface{}) error {
  187. packet := marshal(typ, msg)
  188. return t.writePacket(packet)
  189. }
  190. func newTransport(conn net.Conn, rand io.Reader) *transport {
  191. return &transport{
  192. reader: reader{
  193. Reader: bufio.NewReader(conn),
  194. common: common{
  195. cipher: noneCipher{},
  196. },
  197. },
  198. writer: writer{
  199. Writer: bufio.NewWriter(conn),
  200. rand: rand,
  201. Mutex: new(sync.Mutex),
  202. common: common{
  203. cipher: noneCipher{},
  204. },
  205. },
  206. filteredConn: conn,
  207. }
  208. }
  209. type direction struct {
  210. ivTag []byte
  211. keyTag []byte
  212. macKeyTag []byte
  213. }
  214. // TODO(dfc) can this be made a constant ?
  215. var (
  216. serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}}
  217. clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}}
  218. )
  219. // setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
  220. // described in RFC 4253, section 6.4. direction should either be serverKeys
  221. // (to setup server->client keys) or clientKeys (for client->server keys).
  222. func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error {
  223. cipherMode := cipherModes[c.cipherAlgo]
  224. macMode := macModes[c.macAlgo]
  225. iv := make([]byte, cipherMode.ivSize)
  226. key := make([]byte, cipherMode.keySize)
  227. macKey := make([]byte, macMode.keySize)
  228. h := hashFunc.New()
  229. generateKeyMaterial(iv, d.ivTag, K, H, sessionId, h)
  230. generateKeyMaterial(key, d.keyTag, K, H, sessionId, h)
  231. generateKeyMaterial(macKey, d.macKeyTag, K, H, sessionId, h)
  232. c.mac = macMode.new(macKey)
  233. var err error
  234. c.cipher, err = cipherMode.createCipher(key, iv)
  235. return err
  236. }
  237. // generateKeyMaterial fills out with key material generated from tag, K, H
  238. // and sessionId, as specified in RFC 4253, section 7.2.
  239. func generateKeyMaterial(out, tag []byte, K, H, sessionId []byte, h hash.Hash) {
  240. var digestsSoFar []byte
  241. for len(out) > 0 {
  242. h.Reset()
  243. h.Write(K)
  244. h.Write(H)
  245. if len(digestsSoFar) == 0 {
  246. h.Write(tag)
  247. h.Write(sessionId)
  248. } else {
  249. h.Write(digestsSoFar)
  250. }
  251. digest := h.Sum(nil)
  252. n := copy(out, digest)
  253. out = out[n:]
  254. if len(out) > 0 {
  255. digestsSoFar = append(digestsSoFar, digest...)
  256. }
  257. }
  258. }
  259. // maxVersionStringBytes is the maximum number of bytes that we'll accept as a
  260. // version string. In the event that the client is talking a different protocol
  261. // we need to set a limit otherwise we will keep using more and more memory
  262. // while searching for the end of the version handshake.
  263. const maxVersionStringBytes = 1024
  264. // Read version string as specified by RFC 4253, section 4.2.
  265. func readVersion(r io.Reader) ([]byte, error) {
  266. versionString := make([]byte, 0, 64)
  267. var ok bool
  268. var buf [1]byte
  269. forEachByte:
  270. for len(versionString) < maxVersionStringBytes {
  271. _, err := io.ReadFull(r, buf[:])
  272. if err != nil {
  273. return nil, err
  274. }
  275. // The RFC says that the version should be terminated with \r\n
  276. // but several SSH servers actually only send a \n.
  277. if buf[0] == '\n' {
  278. ok = true
  279. break forEachByte
  280. }
  281. versionString = append(versionString, buf[0])
  282. }
  283. if !ok {
  284. return nil, errors.New("ssh: failed to read version string")
  285. }
  286. // There might be a '\r' on the end which we should remove.
  287. if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' {
  288. versionString = versionString[:len(versionString)-1]
  289. }
  290. return versionString, nil
  291. }