cipher.go 21 KB

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