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

cipher.go 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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/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 https://www.ieee-security.org/TC/SP2013/papers/4977a526.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. // readCipherPacket reads and decrypt a single packet from the reader argument.
  128. func (s *streamPacketCipher) readCipherPacket(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. // writeCipherPacket encrypts and sends a packet of data to the writer argument
  188. func (s *streamPacketCipher) writeCipherPacket(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) writeCipherPacket(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) readCipherPacket(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) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  407. p, err := c.readCipherPacketLeaky(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) readCipherPacketLeaky(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) writeCipherPacket(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. func (c *chacha20Poly1305Cipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  552. nonce := make([]byte, 12)
  553. binary.BigEndian.PutUint32(nonce[8:], seqNum)
  554. s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce)
  555. if err != nil {
  556. return nil, err
  557. }
  558. var polyKey, discardBuf [32]byte
  559. s.XORKeyStream(polyKey[:], polyKey[:])
  560. s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes
  561. encryptedLength := c.buf[:4]
  562. if _, err := io.ReadFull(r, encryptedLength); err != nil {
  563. return nil, err
  564. }
  565. var lenBytes [4]byte
  566. ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce)
  567. if err != nil {
  568. return nil, err
  569. }
  570. ls.XORKeyStream(lenBytes[:], encryptedLength)
  571. length := binary.BigEndian.Uint32(lenBytes[:])
  572. if length > maxPacket {
  573. return nil, errors.New("ssh: invalid packet length, packet too large")
  574. }
  575. contentEnd := 4 + length
  576. packetEnd := contentEnd + poly1305.TagSize
  577. if uint32(cap(c.buf)) < packetEnd {
  578. c.buf = make([]byte, packetEnd)
  579. copy(c.buf[:], encryptedLength)
  580. } else {
  581. c.buf = c.buf[:packetEnd]
  582. }
  583. if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil {
  584. return nil, err
  585. }
  586. var mac [poly1305.TagSize]byte
  587. copy(mac[:], c.buf[contentEnd:packetEnd])
  588. if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) {
  589. return nil, errors.New("ssh: MAC failure")
  590. }
  591. plain := c.buf[4:contentEnd]
  592. s.XORKeyStream(plain, plain)
  593. padding := plain[0]
  594. if padding < 4 {
  595. // padding is a byte, so it automatically satisfies
  596. // the maximum size, which is 255.
  597. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  598. }
  599. if int(padding)+1 >= len(plain) {
  600. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  601. }
  602. plain = plain[1 : len(plain)-int(padding)]
  603. return plain, nil
  604. }
  605. func (c *chacha20Poly1305Cipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error {
  606. nonce := make([]byte, 12)
  607. binary.BigEndian.PutUint32(nonce[8:], seqNum)
  608. s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce)
  609. if err != nil {
  610. return err
  611. }
  612. var polyKey, discardBuf [32]byte
  613. s.XORKeyStream(polyKey[:], polyKey[:])
  614. s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes
  615. // There is no blocksize, so fall back to multiple of 8 byte
  616. // padding, as described in RFC 4253, Sec 6.
  617. const packetSizeMultiple = 8
  618. padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple
  619. if padding < 4 {
  620. padding += packetSizeMultiple
  621. }
  622. // size (4 bytes), padding (1), payload, padding, tag.
  623. totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize
  624. if cap(c.buf) < totalLength {
  625. c.buf = make([]byte, totalLength)
  626. } else {
  627. c.buf = c.buf[:totalLength]
  628. }
  629. binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding))
  630. ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce)
  631. if err != nil {
  632. return err
  633. }
  634. ls.XORKeyStream(c.buf, c.buf[:4])
  635. c.buf[4] = byte(padding)
  636. copy(c.buf[5:], payload)
  637. packetEnd := 5 + len(payload) + padding
  638. if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil {
  639. return err
  640. }
  641. s.XORKeyStream(c.buf[4:], c.buf[4:packetEnd])
  642. var mac [poly1305.TagSize]byte
  643. poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey)
  644. copy(c.buf[packetEnd:], mac[:])
  645. if _, err := w.Write(c.buf); err != nil {
  646. return err
  647. }
  648. return nil
  649. }