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