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.

771 lines
21 KiB

  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. "crypto/aes"
  7. "crypto/cipher"
  8. "crypto/des"
  9. "crypto/rc4"
  10. "crypto/subtle"
  11. "encoding/binary"
  12. "errors"
  13. "fmt"
  14. "hash"
  15. "io"
  16. "io/ioutil"
  17. "golang.org/x/crypto/internal/chacha20"
  18. "golang.org/x/crypto/poly1305"
  19. )
  20. const (
  21. packetSizeMultiple = 16 // TODO(huin) this should be determined by the cipher.
  22. // RFC 4253 section 6.1 defines a minimum packet size of 32768 that implementations
  23. // MUST be able to process (plus a few more kilobytes for padding and mac). The RFC
  24. // indicates implementations SHOULD be able to handle larger packet sizes, but then
  25. // waffles on about reasonable limits.
  26. //
  27. // OpenSSH caps their maxPacket at 256kB so we choose to do
  28. // the same. maxPacket is also used to ensure that uint32
  29. // length fields do not overflow, so it should remain well
  30. // below 4G.
  31. maxPacket = 256 * 1024
  32. )
  33. // noneCipher implements cipher.Stream and provides no encryption. It is used
  34. // by the transport before the first key-exchange.
  35. type noneCipher struct{}
  36. func (c noneCipher) XORKeyStream(dst, src []byte) {
  37. copy(dst, src)
  38. }
  39. func newAESCTR(key, iv []byte) (cipher.Stream, error) {
  40. c, err := aes.NewCipher(key)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return cipher.NewCTR(c, iv), nil
  45. }
  46. func newRC4(key, iv []byte) (cipher.Stream, error) {
  47. return rc4.NewCipher(key)
  48. }
  49. type cipherMode struct {
  50. keySize int
  51. ivSize int
  52. create func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error)
  53. }
  54. func streamCipherMode(skip int, createFunc func(key, iv []byte) (cipher.Stream, error)) func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  55. return func(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  56. stream, err := createFunc(key, iv)
  57. if err != nil {
  58. return nil, err
  59. }
  60. var streamDump []byte
  61. if skip > 0 {
  62. streamDump = make([]byte, 512)
  63. }
  64. for remainingToDump := skip; remainingToDump > 0; {
  65. dumpThisTime := remainingToDump
  66. if dumpThisTime > len(streamDump) {
  67. dumpThisTime = len(streamDump)
  68. }
  69. stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime])
  70. remainingToDump -= dumpThisTime
  71. }
  72. mac := macModes[algs.MAC].new(macKey)
  73. return &streamPacketCipher{
  74. mac: mac,
  75. etm: macModes[algs.MAC].etm,
  76. macResult: make([]byte, mac.Size()),
  77. cipher: stream,
  78. }, nil
  79. }
  80. }
  81. // cipherModes documents properties of supported ciphers. Ciphers not included
  82. // are not supported and will not be negotiated, even if explicitly requested in
  83. // ClientConfig.Crypto.Ciphers.
  84. var cipherModes = map[string]*cipherMode{
  85. // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms
  86. // are defined in the order specified in the RFC.
  87. "aes128-ctr": {16, aes.BlockSize, streamCipherMode(0, newAESCTR)},
  88. "aes192-ctr": {24, aes.BlockSize, streamCipherMode(0, newAESCTR)},
  89. "aes256-ctr": {32, aes.BlockSize, streamCipherMode(0, newAESCTR)},
  90. // Ciphers from RFC4345, which introduces security-improved arcfour ciphers.
  91. // They are defined in the order specified in the RFC.
  92. "arcfour128": {16, 0, streamCipherMode(1536, newRC4)},
  93. "arcfour256": {32, 0, streamCipherMode(1536, newRC4)},
  94. // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol.
  95. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and
  96. // RC4) has problems with weak keys, and should be used with caution."
  97. // RFC4345 introduces improved versions of Arcfour.
  98. "arcfour": {16, 0, streamCipherMode(0, newRC4)},
  99. // AEAD ciphers
  100. gcmCipherID: {16, 12, newGCMCipher},
  101. chacha20Poly1305ID: {64, 0, newChaCha20Cipher},
  102. // CBC mode is insecure and so is not included in the default config.
  103. // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely
  104. // needed, it's possible to specify a custom Config to enable it.
  105. // You should expect that an active attacker can recover plaintext if
  106. // you do.
  107. aes128cbcID: {16, aes.BlockSize, newAESCBCCipher},
  108. // 3des-cbc is insecure and is not included in the default
  109. // config.
  110. tripledescbcID: {24, des.BlockSize, newTripleDESCBCCipher},
  111. }
  112. // prefixLen is the length of the packet prefix that contains the packet length
  113. // and number of padding bytes.
  114. const prefixLen = 5
  115. // streamPacketCipher is a packetCipher using a stream cipher.
  116. type streamPacketCipher struct {
  117. mac hash.Hash
  118. cipher cipher.Stream
  119. etm bool
  120. // The following members are to avoid per-packet allocations.
  121. prefix [prefixLen]byte
  122. seqNumBytes [4]byte
  123. padding [2 * packetSizeMultiple]byte
  124. packetData []byte
  125. macResult []byte
  126. }
  127. // readPacket reads and decrypt a single packet from the reader argument.
  128. func (s *streamPacketCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  129. if _, err := io.ReadFull(r, s.prefix[:]); err != nil {
  130. return nil, err
  131. }
  132. var encryptedPaddingLength [1]byte
  133. if s.mac != nil && s.etm {
  134. copy(encryptedPaddingLength[:], s.prefix[4:5])
  135. s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5])
  136. } else {
  137. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  138. }
  139. length := binary.BigEndian.Uint32(s.prefix[0:4])
  140. paddingLength := uint32(s.prefix[4])
  141. var macSize uint32
  142. if s.mac != nil {
  143. s.mac.Reset()
  144. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  145. s.mac.Write(s.seqNumBytes[:])
  146. if s.etm {
  147. s.mac.Write(s.prefix[:4])
  148. s.mac.Write(encryptedPaddingLength[:])
  149. } else {
  150. s.mac.Write(s.prefix[:])
  151. }
  152. macSize = uint32(s.mac.Size())
  153. }
  154. if length <= paddingLength+1 {
  155. return nil, errors.New("ssh: invalid packet length, packet too small")
  156. }
  157. if length > maxPacket {
  158. return nil, errors.New("ssh: invalid packet length, packet too large")
  159. }
  160. // the maxPacket check above ensures that length-1+macSize
  161. // does not overflow.
  162. if uint32(cap(s.packetData)) < length-1+macSize {
  163. s.packetData = make([]byte, length-1+macSize)
  164. } else {
  165. s.packetData = s.packetData[:length-1+macSize]
  166. }
  167. if _, err := io.ReadFull(r, s.packetData); err != nil {
  168. return nil, err
  169. }
  170. mac := s.packetData[length-1:]
  171. data := s.packetData[:length-1]
  172. if s.mac != nil && s.etm {
  173. s.mac.Write(data)
  174. }
  175. s.cipher.XORKeyStream(data, data)
  176. if s.mac != nil {
  177. if !s.etm {
  178. s.mac.Write(data)
  179. }
  180. s.macResult = s.mac.Sum(s.macResult[:0])
  181. if subtle.ConstantTimeCompare(s.macResult, mac) != 1 {
  182. return nil, errors.New("ssh: MAC failure")
  183. }
  184. }
  185. return s.packetData[:length-paddingLength-1], nil
  186. }
  187. // writePacket encrypts and sends a packet of data to the writer argument
  188. func (s *streamPacketCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  189. if len(packet) > maxPacket {
  190. return errors.New("ssh: packet too large")
  191. }
  192. aadlen := 0
  193. if s.mac != nil && s.etm {
  194. // packet length is not encrypted for EtM modes
  195. aadlen = 4
  196. }
  197. paddingLength := packetSizeMultiple - (prefixLen+len(packet)-aadlen)%packetSizeMultiple
  198. if paddingLength < 4 {
  199. paddingLength += packetSizeMultiple
  200. }
  201. length := len(packet) + 1 + paddingLength
  202. binary.BigEndian.PutUint32(s.prefix[:], uint32(length))
  203. s.prefix[4] = byte(paddingLength)
  204. padding := s.padding[:paddingLength]
  205. if _, err := io.ReadFull(rand, padding); err != nil {
  206. return err
  207. }
  208. if s.mac != nil {
  209. s.mac.Reset()
  210. binary.BigEndian.PutUint32(s.seqNumBytes[:], seqNum)
  211. s.mac.Write(s.seqNumBytes[:])
  212. if s.etm {
  213. // For EtM algorithms, the packet length must stay unencrypted,
  214. // but the following data (padding length) must be encrypted
  215. s.cipher.XORKeyStream(s.prefix[4:5], s.prefix[4:5])
  216. }
  217. s.mac.Write(s.prefix[:])
  218. if !s.etm {
  219. // For non-EtM algorithms, the algorithm is applied on unencrypted data
  220. s.mac.Write(packet)
  221. s.mac.Write(padding)
  222. }
  223. }
  224. if !(s.mac != nil && s.etm) {
  225. // For EtM algorithms, the padding length has already been encrypted
  226. // and the packet length must remain unencrypted
  227. s.cipher.XORKeyStream(s.prefix[:], s.prefix[:])
  228. }
  229. s.cipher.XORKeyStream(packet, packet)
  230. s.cipher.XORKeyStream(padding, padding)
  231. if s.mac != nil && s.etm {
  232. // For EtM algorithms, packet and padding must be encrypted
  233. s.mac.Write(packet)
  234. s.mac.Write(padding)
  235. }
  236. if _, err := w.Write(s.prefix[:]); err != nil {
  237. return err
  238. }
  239. if _, err := w.Write(packet); err != nil {
  240. return err
  241. }
  242. if _, err := w.Write(padding); err != nil {
  243. return err
  244. }
  245. if s.mac != nil {
  246. s.macResult = s.mac.Sum(s.macResult[:0])
  247. if _, err := w.Write(s.macResult); err != nil {
  248. return err
  249. }
  250. }
  251. return nil
  252. }
  253. type gcmCipher struct {
  254. aead cipher.AEAD
  255. prefix [4]byte
  256. iv []byte
  257. buf []byte
  258. }
  259. func newGCMCipher(key, iv, unusedMacKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) {
  260. c, err := aes.NewCipher(key)
  261. if err != nil {
  262. return nil, err
  263. }
  264. aead, err := cipher.NewGCM(c)
  265. if err != nil {
  266. return nil, err
  267. }
  268. return &gcmCipher{
  269. aead: aead,
  270. iv: iv,
  271. }, nil
  272. }
  273. const gcmTagSize = 16
  274. func (c *gcmCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  275. // Pad out to multiple of 16 bytes. This is different from the
  276. // stream cipher because that encrypts the length too.
  277. padding := byte(packetSizeMultiple - (1+len(packet))%packetSizeMultiple)
  278. if padding < 4 {
  279. padding += packetSizeMultiple
  280. }
  281. length := uint32(len(packet) + int(padding) + 1)
  282. binary.BigEndian.PutUint32(c.prefix[:], length)
  283. if _, err := w.Write(c.prefix[:]); err != nil {
  284. return err
  285. }
  286. if cap(c.buf) < int(length) {
  287. c.buf = make([]byte, length)
  288. } else {
  289. c.buf = c.buf[:length]
  290. }
  291. c.buf[0] = padding
  292. copy(c.buf[1:], packet)
  293. if _, err := io.ReadFull(rand, c.buf[1+len(packet):]); err != nil {
  294. return err
  295. }
  296. c.buf = c.aead.Seal(c.buf[:0], c.iv, c.buf, c.prefix[:])
  297. if _, err := w.Write(c.buf); err != nil {
  298. return err
  299. }
  300. c.incIV()
  301. return nil
  302. }
  303. func (c *gcmCipher) incIV() {
  304. for i := 4 + 7; i >= 4; i-- {
  305. c.iv[i]++
  306. if c.iv[i] != 0 {
  307. break
  308. }
  309. }
  310. }
  311. func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  312. if _, err := io.ReadFull(r, c.prefix[:]); err != nil {
  313. return nil, err
  314. }
  315. length := binary.BigEndian.Uint32(c.prefix[:])
  316. if length > maxPacket {
  317. return nil, errors.New("ssh: max packet length exceeded")
  318. }
  319. if cap(c.buf) < int(length+gcmTagSize) {
  320. c.buf = make([]byte, length+gcmTagSize)
  321. } else {
  322. c.buf = c.buf[:length+gcmTagSize]
  323. }
  324. if _, err := io.ReadFull(r, c.buf); err != nil {
  325. return nil, err
  326. }
  327. plain, err := c.aead.Open(c.buf[:0], c.iv, c.buf, c.prefix[:])
  328. if err != nil {
  329. return nil, err
  330. }
  331. c.incIV()
  332. padding := plain[0]
  333. if padding < 4 {
  334. // padding is a byte, so it automatically satisfies
  335. // the maximum size, which is 255.
  336. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  337. }
  338. if int(padding+1) >= len(plain) {
  339. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  340. }
  341. plain = plain[1 : length-uint32(padding)]
  342. return plain, nil
  343. }
  344. // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1
  345. type cbcCipher struct {
  346. mac hash.Hash
  347. macSize uint32
  348. decrypter cipher.BlockMode
  349. encrypter cipher.BlockMode
  350. // The following members are to avoid per-packet allocations.
  351. seqNumBytes [4]byte
  352. packetData []byte
  353. macResult []byte
  354. // Amount of data we should still read to hide which
  355. // verification error triggered.
  356. oracleCamouflage uint32
  357. }
  358. func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  359. cbc := &cbcCipher{
  360. mac: macModes[algs.MAC].new(macKey),
  361. decrypter: cipher.NewCBCDecrypter(c, iv),
  362. encrypter: cipher.NewCBCEncrypter(c, iv),
  363. packetData: make([]byte, 1024),
  364. }
  365. if cbc.mac != nil {
  366. cbc.macSize = uint32(cbc.mac.Size())
  367. }
  368. return cbc, nil
  369. }
  370. func newAESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  371. c, err := aes.NewCipher(key)
  372. if err != nil {
  373. return nil, err
  374. }
  375. cbc, err := newCBCCipher(c, key, iv, macKey, algs)
  376. if err != nil {
  377. return nil, err
  378. }
  379. return cbc, nil
  380. }
  381. func newTripleDESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  382. c, err := des.NewTripleDESCipher(key)
  383. if err != nil {
  384. return nil, err
  385. }
  386. cbc, err := newCBCCipher(c, key, iv, macKey, algs)
  387. if err != nil {
  388. return nil, err
  389. }
  390. return cbc, nil
  391. }
  392. func maxUInt32(a, b int) uint32 {
  393. if a > b {
  394. return uint32(a)
  395. }
  396. return uint32(b)
  397. }
  398. const (
  399. cbcMinPacketSizeMultiple = 8
  400. cbcMinPacketSize = 16
  401. cbcMinPaddingSize = 4
  402. )
  403. // cbcError represents a verification error that may leak information.
  404. type cbcError string
  405. func (e cbcError) Error() string { return string(e) }
  406. func (c *cbcCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  407. p, err := c.readPacketLeaky(seqNum, r)
  408. if err != nil {
  409. if _, ok := err.(cbcError); ok {
  410. // Verification error: read a fixed amount of
  411. // data, to make distinguishing between
  412. // failing MAC and failing length check more
  413. // difficult.
  414. io.CopyN(ioutil.Discard, r, int64(c.oracleCamouflage))
  415. }
  416. }
  417. return p, err
  418. }
  419. func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) {
  420. blockSize := c.decrypter.BlockSize()
  421. // Read the header, which will include some of the subsequent data in the
  422. // case of block ciphers - this is copied back to the payload later.
  423. // How many bytes of payload/padding will be read with this first read.
  424. firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize)
  425. firstBlock := c.packetData[:firstBlockLength]
  426. if _, err := io.ReadFull(r, firstBlock); err != nil {
  427. return nil, err
  428. }
  429. c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength
  430. c.decrypter.CryptBlocks(firstBlock, firstBlock)
  431. length := binary.BigEndian.Uint32(firstBlock[:4])
  432. if length > maxPacket {
  433. return nil, cbcError("ssh: packet too large")
  434. }
  435. if length+4 < maxUInt32(cbcMinPacketSize, blockSize) {
  436. // The minimum size of a packet is 16 (or the cipher block size, whichever
  437. // is larger) bytes.
  438. return nil, cbcError("ssh: packet too small")
  439. }
  440. // The length of the packet (including the length field but not the MAC) must
  441. // be a multiple of the block size or 8, whichever is larger.
  442. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 {
  443. return nil, cbcError("ssh: invalid packet length multiple")
  444. }
  445. paddingLength := uint32(firstBlock[4])
  446. if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 {
  447. return nil, cbcError("ssh: invalid packet length")
  448. }
  449. // Positions within the c.packetData buffer:
  450. macStart := 4 + length
  451. paddingStart := macStart - paddingLength
  452. // Entire packet size, starting before length, ending at end of mac.
  453. entirePacketSize := macStart + c.macSize
  454. // Ensure c.packetData is large enough for the entire packet data.
  455. if uint32(cap(c.packetData)) < entirePacketSize {
  456. // Still need to upsize and copy, but this should be rare at runtime, only
  457. // on upsizing the packetData buffer.
  458. c.packetData = make([]byte, entirePacketSize)
  459. copy(c.packetData, firstBlock)
  460. } else {
  461. c.packetData = c.packetData[:entirePacketSize]
  462. }
  463. n, err := io.ReadFull(r, c.packetData[firstBlockLength:])
  464. if err != nil {
  465. return nil, err
  466. }
  467. c.oracleCamouflage -= uint32(n)
  468. remainingCrypted := c.packetData[firstBlockLength:macStart]
  469. c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted)
  470. mac := c.packetData[macStart:]
  471. if c.mac != nil {
  472. c.mac.Reset()
  473. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  474. c.mac.Write(c.seqNumBytes[:])
  475. c.mac.Write(c.packetData[:macStart])
  476. c.macResult = c.mac.Sum(c.macResult[:0])
  477. if subtle.ConstantTimeCompare(c.macResult, mac) != 1 {
  478. return nil, cbcError("ssh: MAC failure")
  479. }
  480. }
  481. return c.packetData[prefixLen:paddingStart], nil
  482. }
  483. func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  484. effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize())
  485. // Length of encrypted portion of the packet (header, payload, padding).
  486. // Enforce minimum padding and packet size.
  487. encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
  488. // Enforce block size.
  489. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
  490. length := encLength - 4
  491. paddingLength := int(length) - (1 + len(packet))
  492. // Overall buffer contains: header, payload, padding, mac.
  493. // Space for the MAC is reserved in the capacity but not the slice length.
  494. bufferSize := encLength + c.macSize
  495. if uint32(cap(c.packetData)) < bufferSize {
  496. c.packetData = make([]byte, encLength, bufferSize)
  497. } else {
  498. c.packetData = c.packetData[:encLength]
  499. }
  500. p := c.packetData
  501. // Packet header.
  502. binary.BigEndian.PutUint32(p, length)
  503. p = p[4:]
  504. p[0] = byte(paddingLength)
  505. // Payload.
  506. p = p[1:]
  507. copy(p, packet)
  508. // Padding.
  509. p = p[len(packet):]
  510. if _, err := io.ReadFull(rand, p); err != nil {
  511. return err
  512. }
  513. if c.mac != nil {
  514. c.mac.Reset()
  515. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  516. c.mac.Write(c.seqNumBytes[:])
  517. c.mac.Write(c.packetData)
  518. // The MAC is now appended into the capacity reserved for it earlier.
  519. c.packetData = c.mac.Sum(c.packetData)
  520. }
  521. c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength])
  522. if _, err := w.Write(c.packetData); err != nil {
  523. return err
  524. }
  525. return nil
  526. }
  527. const chacha20Poly1305ID = "chacha20-poly1305@openssh.com"
  528. // chacha20Poly1305Cipher implements the chacha20-poly1305@openssh.com
  529. // AEAD, which is described here:
  530. //
  531. // https://tools.ietf.org/html/draft-josefsson-ssh-chacha20-poly1305-openssh-00
  532. //
  533. // the methods here also implement padding, which RFC4253 Section 6
  534. // also requires of stream ciphers.
  535. type chacha20Poly1305Cipher struct {
  536. lengthKey [32]byte
  537. contentKey [32]byte
  538. buf []byte
  539. }
  540. func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) {
  541. if len(key) != 64 {
  542. panic(len(key))
  543. }
  544. c := &chacha20Poly1305Cipher{
  545. buf: make([]byte, 256),
  546. }
  547. copy(c.contentKey[:], key[:32])
  548. copy(c.lengthKey[:], key[32:])
  549. return c, nil
  550. }
  551. // The Poly1305 key is obtained by encrypting 32 0-bytes.
  552. var chacha20PolyKeyInput [32]byte
  553. func (c *chacha20Poly1305Cipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  554. var counter [16]byte
  555. binary.BigEndian.PutUint64(counter[8:], uint64(seqNum))
  556. var polyKey [32]byte
  557. chacha20.XORKeyStream(polyKey[:], chacha20PolyKeyInput[:], &counter, &c.contentKey)
  558. encryptedLength := c.buf[:4]
  559. if _, err := io.ReadFull(r, encryptedLength); err != nil {
  560. return nil, err
  561. }
  562. var lenBytes [4]byte
  563. chacha20.XORKeyStream(lenBytes[:], encryptedLength, &counter, &c.lengthKey)
  564. length := binary.BigEndian.Uint32(lenBytes[:])
  565. if length > maxPacket {
  566. return nil, errors.New("ssh: invalid packet length, packet too large")
  567. }
  568. contentEnd := 4 + length
  569. packetEnd := contentEnd + poly1305.TagSize
  570. if uint32(cap(c.buf)) < packetEnd {
  571. c.buf = make([]byte, packetEnd)
  572. copy(c.buf[:], encryptedLength)
  573. } else {
  574. c.buf = c.buf[:packetEnd]
  575. }
  576. if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil {
  577. return nil, err
  578. }
  579. var mac [poly1305.TagSize]byte
  580. copy(mac[:], c.buf[contentEnd:packetEnd])
  581. if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) {
  582. return nil, errors.New("ssh: MAC failure")
  583. }
  584. counter[0] = 1
  585. plain := c.buf[4:contentEnd]
  586. chacha20.XORKeyStream(plain, plain, &counter, &c.contentKey)
  587. padding := plain[0]
  588. if padding < 4 {
  589. // padding is a byte, so it automatically satisfies
  590. // the maximum size, which is 255.
  591. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  592. }
  593. if int(padding)+1 >= len(plain) {
  594. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  595. }
  596. plain = plain[1 : len(plain)-int(padding)]
  597. return plain, nil
  598. }
  599. func (c *chacha20Poly1305Cipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error {
  600. var counter [16]byte
  601. binary.BigEndian.PutUint64(counter[8:], uint64(seqNum))
  602. var polyKey [32]byte
  603. chacha20.XORKeyStream(polyKey[:], chacha20PolyKeyInput[:], &counter, &c.contentKey)
  604. // There is no blocksize, so fall back to multiple of 8 byte
  605. // padding, as described in RFC 4253, Sec 6.
  606. const packetSizeMultiple = 8
  607. padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple
  608. if padding < 4 {
  609. padding += packetSizeMultiple
  610. }
  611. // size (4 bytes), padding (1), payload, padding, tag.
  612. totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize
  613. if cap(c.buf) < totalLength {
  614. c.buf = make([]byte, totalLength)
  615. } else {
  616. c.buf = c.buf[:totalLength]
  617. }
  618. binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding))
  619. chacha20.XORKeyStream(c.buf, c.buf[:4], &counter, &c.lengthKey)
  620. c.buf[4] = byte(padding)
  621. copy(c.buf[5:], payload)
  622. packetEnd := 5 + len(payload) + padding
  623. if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil {
  624. return err
  625. }
  626. counter[0] = 1
  627. chacha20.XORKeyStream(c.buf[4:], c.buf[4:packetEnd], &counter, &c.contentKey)
  628. var mac [poly1305.TagSize]byte
  629. poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey)
  630. copy(c.buf[packetEnd:], mac[:])
  631. if _, err := w.Write(c.buf); err != nil {
  632. return err
  633. }
  634. return nil
  635. }