本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

354 lines
9.1KB

  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. "bytes"
  8. "errors"
  9. "io"
  10. "log"
  11. )
  12. // debugTransport if set, will print packet types as they go over the
  13. // wire. No message decoding is done, to minimize the impact on timing.
  14. const debugTransport = false
  15. const (
  16. gcmCipherID = "aes128-gcm@openssh.com"
  17. aes128cbcID = "aes128-cbc"
  18. tripledescbcID = "3des-cbc"
  19. )
  20. // packetConn represents a transport that implements packet based
  21. // operations.
  22. type packetConn interface {
  23. // Encrypt and send a packet of data to the remote peer.
  24. writePacket(packet []byte) error
  25. // Read a packet from the connection. The read is blocking,
  26. // i.e. if error is nil, then the returned byte slice is
  27. // always non-empty.
  28. readPacket() ([]byte, error)
  29. // Close closes the write-side of the connection.
  30. Close() error
  31. }
  32. // transport is the keyingTransport that implements the SSH packet
  33. // protocol.
  34. type transport struct {
  35. reader connectionState
  36. writer connectionState
  37. bufReader *bufio.Reader
  38. bufWriter *bufio.Writer
  39. rand io.Reader
  40. isClient bool
  41. io.Closer
  42. }
  43. // packetCipher represents a combination of SSH encryption/MAC
  44. // protocol. A single instance should be used for one direction only.
  45. type packetCipher interface {
  46. // writeCipherPacket encrypts the packet and writes it to w. The
  47. // contents of the packet are generally scrambled.
  48. writeCipherPacket(seqnum uint32, w io.Writer, rand io.Reader, packet []byte) error
  49. // readCipherPacket reads and decrypts a packet of data. The
  50. // returned packet may be overwritten by future calls of
  51. // readPacket.
  52. readCipherPacket(seqnum uint32, r io.Reader) ([]byte, error)
  53. }
  54. // connectionState represents one side (read or write) of the
  55. // connection. This is necessary because each direction has its own
  56. // keys, and can even have its own algorithms
  57. type connectionState struct {
  58. packetCipher
  59. seqNum uint32
  60. dir direction
  61. pendingKeyChange chan packetCipher
  62. }
  63. // prepareKeyChange sets up key material for a keychange. The key changes in
  64. // both directions are triggered by reading and writing a msgNewKey packet
  65. // respectively.
  66. func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error {
  67. ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult)
  68. if err != nil {
  69. return err
  70. }
  71. t.reader.pendingKeyChange <- ciph
  72. ciph, err = newPacketCipher(t.writer.dir, algs.w, kexResult)
  73. if err != nil {
  74. return err
  75. }
  76. t.writer.pendingKeyChange <- ciph
  77. return nil
  78. }
  79. func (t *transport) printPacket(p []byte, write bool) {
  80. if len(p) == 0 {
  81. return
  82. }
  83. who := "server"
  84. if t.isClient {
  85. who = "client"
  86. }
  87. what := "read"
  88. if write {
  89. what = "write"
  90. }
  91. log.Println(what, who, p[0])
  92. }
  93. // Read and decrypt next packet.
  94. func (t *transport) readPacket() (p []byte, err error) {
  95. for {
  96. p, err = t.reader.readPacket(t.bufReader)
  97. if err != nil {
  98. break
  99. }
  100. if len(p) == 0 || (p[0] != msgIgnore && p[0] != msgDebug) {
  101. break
  102. }
  103. }
  104. if debugTransport {
  105. t.printPacket(p, false)
  106. }
  107. return p, err
  108. }
  109. func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) {
  110. packet, err := s.packetCipher.readCipherPacket(s.seqNum, r)
  111. s.seqNum++
  112. if err == nil && len(packet) == 0 {
  113. err = errors.New("ssh: zero length packet")
  114. }
  115. if len(packet) > 0 {
  116. switch packet[0] {
  117. case msgNewKeys:
  118. select {
  119. case cipher := <-s.pendingKeyChange:
  120. s.packetCipher = cipher
  121. default:
  122. return nil, errors.New("ssh: got bogus newkeys message")
  123. }
  124. case msgDisconnect:
  125. // Transform a disconnect message into an
  126. // error. Since this is lowest level at which
  127. // we interpret message types, doing it here
  128. // ensures that we don't have to handle it
  129. // elsewhere.
  130. var msg disconnectMsg
  131. if err := Unmarshal(packet, &msg); err != nil {
  132. return nil, err
  133. }
  134. return nil, &msg
  135. }
  136. }
  137. // The packet may point to an internal buffer, so copy the
  138. // packet out here.
  139. fresh := make([]byte, len(packet))
  140. copy(fresh, packet)
  141. return fresh, err
  142. }
  143. func (t *transport) writePacket(packet []byte) error {
  144. if debugTransport {
  145. t.printPacket(packet, true)
  146. }
  147. return t.writer.writePacket(t.bufWriter, t.rand, packet)
  148. }
  149. func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error {
  150. changeKeys := len(packet) > 0 && packet[0] == msgNewKeys
  151. err := s.packetCipher.writeCipherPacket(s.seqNum, w, rand, packet)
  152. if err != nil {
  153. return err
  154. }
  155. if err = w.Flush(); err != nil {
  156. return err
  157. }
  158. s.seqNum++
  159. if changeKeys {
  160. select {
  161. case cipher := <-s.pendingKeyChange:
  162. s.packetCipher = cipher
  163. default:
  164. panic("ssh: no key material for msgNewKeys")
  165. }
  166. }
  167. return err
  168. }
  169. func newTransport(rwc io.ReadWriteCloser, rand io.Reader, isClient bool) *transport {
  170. t := &transport{
  171. bufReader: bufio.NewReader(rwc),
  172. bufWriter: bufio.NewWriter(rwc),
  173. rand: rand,
  174. reader: connectionState{
  175. packetCipher: &streamPacketCipher{cipher: noneCipher{}},
  176. pendingKeyChange: make(chan packetCipher, 1),
  177. },
  178. writer: connectionState{
  179. packetCipher: &streamPacketCipher{cipher: noneCipher{}},
  180. pendingKeyChange: make(chan packetCipher, 1),
  181. },
  182. Closer: rwc,
  183. }
  184. t.isClient = isClient
  185. if isClient {
  186. t.reader.dir = serverKeys
  187. t.writer.dir = clientKeys
  188. } else {
  189. t.reader.dir = clientKeys
  190. t.writer.dir = serverKeys
  191. }
  192. return t
  193. }
  194. type direction struct {
  195. ivTag []byte
  196. keyTag []byte
  197. macKeyTag []byte
  198. }
  199. var (
  200. serverKeys = direction{[]byte{'B'}, []byte{'D'}, []byte{'F'}}
  201. clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}}
  202. )
  203. // setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as
  204. // described in RFC 4253, section 6.4. direction should either be serverKeys
  205. // (to setup server->client keys) or clientKeys (for client->server keys).
  206. func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) {
  207. cipherMode := cipherModes[algs.Cipher]
  208. macMode := macModes[algs.MAC]
  209. iv := make([]byte, cipherMode.ivSize)
  210. key := make([]byte, cipherMode.keySize)
  211. macKey := make([]byte, macMode.keySize)
  212. generateKeyMaterial(iv, d.ivTag, kex)
  213. generateKeyMaterial(key, d.keyTag, kex)
  214. generateKeyMaterial(macKey, d.macKeyTag, kex)
  215. return cipherModes[algs.Cipher].create(key, iv, macKey, algs)
  216. }
  217. // generateKeyMaterial fills out with key material generated from tag, K, H
  218. // and sessionId, as specified in RFC 4253, section 7.2.
  219. func generateKeyMaterial(out, tag []byte, r *kexResult) {
  220. var digestsSoFar []byte
  221. h := r.Hash.New()
  222. for len(out) > 0 {
  223. h.Reset()
  224. h.Write(r.K)
  225. h.Write(r.H)
  226. if len(digestsSoFar) == 0 {
  227. h.Write(tag)
  228. h.Write(r.SessionID)
  229. } else {
  230. h.Write(digestsSoFar)
  231. }
  232. digest := h.Sum(nil)
  233. n := copy(out, digest)
  234. out = out[n:]
  235. if len(out) > 0 {
  236. digestsSoFar = append(digestsSoFar, digest...)
  237. }
  238. }
  239. }
  240. const packageVersion = "SSH-2.0-Go"
  241. // Sends and receives a version line. The versionLine string should
  242. // be US ASCII, start with "SSH-2.0-", and should not include a
  243. // newline. exchangeVersions returns the other side's version line.
  244. func exchangeVersions(rw io.ReadWriter, versionLine []byte) (them []byte, err error) {
  245. // Contrary to the RFC, we do not ignore lines that don't
  246. // start with "SSH-2.0-" to make the library usable with
  247. // nonconforming servers.
  248. for _, c := range versionLine {
  249. // The spec disallows non US-ASCII chars, and
  250. // specifically forbids null chars.
  251. if c < 32 {
  252. return nil, errors.New("ssh: junk character in version line")
  253. }
  254. }
  255. if _, err = rw.Write(append(versionLine, '\r', '\n')); err != nil {
  256. return
  257. }
  258. them, err = readVersion(rw)
  259. return them, err
  260. }
  261. // maxVersionStringBytes is the maximum number of bytes that we'll
  262. // accept as a version string. RFC 4253 section 4.2 limits this at 255
  263. // chars
  264. const maxVersionStringBytes = 255
  265. // Read version string as specified by RFC 4253, section 4.2.
  266. func readVersion(r io.Reader) ([]byte, error) {
  267. versionString := make([]byte, 0, 64)
  268. var ok bool
  269. var buf [1]byte
  270. for length := 0; length < maxVersionStringBytes; length++ {
  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. if !bytes.HasPrefix(versionString, []byte("SSH-")) {
  279. // RFC 4253 says we need to ignore all version string lines
  280. // except the one containing the SSH version (provided that
  281. // all the lines do not exceed 255 bytes in total).
  282. versionString = versionString[:0]
  283. continue
  284. }
  285. ok = true
  286. break
  287. }
  288. // non ASCII chars are disallowed, but we are lenient,
  289. // since Go doesn't use null-terminated strings.
  290. // The RFC allows a comment after a space, however,
  291. // all of it (version and comments) goes into the
  292. // session hash.
  293. versionString = append(versionString, buf[0])
  294. }
  295. if !ok {
  296. return nil, errors.New("ssh: overflow reading version string")
  297. }
  298. // There might be a '\r' on the end which we should remove.
  299. if len(versionString) > 0 && versionString[len(versionString)-1] == '\r' {
  300. versionString = versionString[:len(versionString)-1]
  301. }
  302. return versionString, nil
  303. }
上海开阖软件有限公司 沪ICP备12045867号-1