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. gcm128CipherID: {16, 12, newGCMCipher},
  100. gcm256CipherID: {32, 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. if len(plain) == 0 {
  333. return nil, errors.New("ssh: empty packet")
  334. }
  335. padding := plain[0]
  336. if padding < 4 {
  337. // padding is a byte, so it automatically satisfies
  338. // the maximum size, which is 255.
  339. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  340. }
  341. if int(padding+1) >= len(plain) {
  342. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  343. }
  344. plain = plain[1 : length-uint32(padding)]
  345. return plain, nil
  346. }
  347. // cbcCipher implements aes128-cbc cipher defined in RFC 4253 section 6.1
  348. type cbcCipher struct {
  349. mac hash.Hash
  350. macSize uint32
  351. decrypter cipher.BlockMode
  352. encrypter cipher.BlockMode
  353. // The following members are to avoid per-packet allocations.
  354. seqNumBytes [4]byte
  355. packetData []byte
  356. macResult []byte
  357. // Amount of data we should still read to hide which
  358. // verification error triggered.
  359. oracleCamouflage uint32
  360. }
  361. func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  362. cbc := &cbcCipher{
  363. mac: macModes[algs.MAC].new(macKey),
  364. decrypter: cipher.NewCBCDecrypter(c, iv),
  365. encrypter: cipher.NewCBCEncrypter(c, iv),
  366. packetData: make([]byte, 1024),
  367. }
  368. if cbc.mac != nil {
  369. cbc.macSize = uint32(cbc.mac.Size())
  370. }
  371. return cbc, nil
  372. }
  373. func newAESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  374. c, err := aes.NewCipher(key)
  375. if err != nil {
  376. return nil, err
  377. }
  378. cbc, err := newCBCCipher(c, key, iv, macKey, algs)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return cbc, nil
  383. }
  384. func newTripleDESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) {
  385. c, err := des.NewTripleDESCipher(key)
  386. if err != nil {
  387. return nil, err
  388. }
  389. cbc, err := newCBCCipher(c, key, iv, macKey, algs)
  390. if err != nil {
  391. return nil, err
  392. }
  393. return cbc, nil
  394. }
  395. func maxUInt32(a, b int) uint32 {
  396. if a > b {
  397. return uint32(a)
  398. }
  399. return uint32(b)
  400. }
  401. const (
  402. cbcMinPacketSizeMultiple = 8
  403. cbcMinPacketSize = 16
  404. cbcMinPaddingSize = 4
  405. )
  406. // cbcError represents a verification error that may leak information.
  407. type cbcError string
  408. func (e cbcError) Error() string { return string(e) }
  409. func (c *cbcCipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  410. p, err := c.readCipherPacketLeaky(seqNum, r)
  411. if err != nil {
  412. if _, ok := err.(cbcError); ok {
  413. // Verification error: read a fixed amount of
  414. // data, to make distinguishing between
  415. // failing MAC and failing length check more
  416. // difficult.
  417. io.CopyN(io.Discard, r, int64(c.oracleCamouflage))
  418. }
  419. }
  420. return p, err
  421. }
  422. func (c *cbcCipher) readCipherPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) {
  423. blockSize := c.decrypter.BlockSize()
  424. // Read the header, which will include some of the subsequent data in the
  425. // case of block ciphers - this is copied back to the payload later.
  426. // How many bytes of payload/padding will be read with this first read.
  427. firstBlockLength := uint32((prefixLen + blockSize - 1) / blockSize * blockSize)
  428. firstBlock := c.packetData[:firstBlockLength]
  429. if _, err := io.ReadFull(r, firstBlock); err != nil {
  430. return nil, err
  431. }
  432. c.oracleCamouflage = maxPacket + 4 + c.macSize - firstBlockLength
  433. c.decrypter.CryptBlocks(firstBlock, firstBlock)
  434. length := binary.BigEndian.Uint32(firstBlock[:4])
  435. if length > maxPacket {
  436. return nil, cbcError("ssh: packet too large")
  437. }
  438. if length+4 < maxUInt32(cbcMinPacketSize, blockSize) {
  439. // The minimum size of a packet is 16 (or the cipher block size, whichever
  440. // is larger) bytes.
  441. return nil, cbcError("ssh: packet too small")
  442. }
  443. // The length of the packet (including the length field but not the MAC) must
  444. // be a multiple of the block size or 8, whichever is larger.
  445. if (length+4)%maxUInt32(cbcMinPacketSizeMultiple, blockSize) != 0 {
  446. return nil, cbcError("ssh: invalid packet length multiple")
  447. }
  448. paddingLength := uint32(firstBlock[4])
  449. if paddingLength < cbcMinPaddingSize || length <= paddingLength+1 {
  450. return nil, cbcError("ssh: invalid packet length")
  451. }
  452. // Positions within the c.packetData buffer:
  453. macStart := 4 + length
  454. paddingStart := macStart - paddingLength
  455. // Entire packet size, starting before length, ending at end of mac.
  456. entirePacketSize := macStart + c.macSize
  457. // Ensure c.packetData is large enough for the entire packet data.
  458. if uint32(cap(c.packetData)) < entirePacketSize {
  459. // Still need to upsize and copy, but this should be rare at runtime, only
  460. // on upsizing the packetData buffer.
  461. c.packetData = make([]byte, entirePacketSize)
  462. copy(c.packetData, firstBlock)
  463. } else {
  464. c.packetData = c.packetData[:entirePacketSize]
  465. }
  466. n, err := io.ReadFull(r, c.packetData[firstBlockLength:])
  467. if err != nil {
  468. return nil, err
  469. }
  470. c.oracleCamouflage -= uint32(n)
  471. remainingCrypted := c.packetData[firstBlockLength:macStart]
  472. c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted)
  473. mac := c.packetData[macStart:]
  474. if c.mac != nil {
  475. c.mac.Reset()
  476. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  477. c.mac.Write(c.seqNumBytes[:])
  478. c.mac.Write(c.packetData[:macStart])
  479. c.macResult = c.mac.Sum(c.macResult[:0])
  480. if subtle.ConstantTimeCompare(c.macResult, mac) != 1 {
  481. return nil, cbcError("ssh: MAC failure")
  482. }
  483. }
  484. return c.packetData[prefixLen:paddingStart], nil
  485. }
  486. func (c *cbcCipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, packet []byte) error {
  487. effectiveBlockSize := maxUInt32(cbcMinPacketSizeMultiple, c.encrypter.BlockSize())
  488. // Length of encrypted portion of the packet (header, payload, padding).
  489. // Enforce minimum padding and packet size.
  490. encLength := maxUInt32(prefixLen+len(packet)+cbcMinPaddingSize, cbcMinPaddingSize)
  491. // Enforce block size.
  492. encLength = (encLength + effectiveBlockSize - 1) / effectiveBlockSize * effectiveBlockSize
  493. length := encLength - 4
  494. paddingLength := int(length) - (1 + len(packet))
  495. // Overall buffer contains: header, payload, padding, mac.
  496. // Space for the MAC is reserved in the capacity but not the slice length.
  497. bufferSize := encLength + c.macSize
  498. if uint32(cap(c.packetData)) < bufferSize {
  499. c.packetData = make([]byte, encLength, bufferSize)
  500. } else {
  501. c.packetData = c.packetData[:encLength]
  502. }
  503. p := c.packetData
  504. // Packet header.
  505. binary.BigEndian.PutUint32(p, length)
  506. p = p[4:]
  507. p[0] = byte(paddingLength)
  508. // Payload.
  509. p = p[1:]
  510. copy(p, packet)
  511. // Padding.
  512. p = p[len(packet):]
  513. if _, err := io.ReadFull(rand, p); err != nil {
  514. return err
  515. }
  516. if c.mac != nil {
  517. c.mac.Reset()
  518. binary.BigEndian.PutUint32(c.seqNumBytes[:], seqNum)
  519. c.mac.Write(c.seqNumBytes[:])
  520. c.mac.Write(c.packetData)
  521. // The MAC is now appended into the capacity reserved for it earlier.
  522. c.packetData = c.mac.Sum(c.packetData)
  523. }
  524. c.encrypter.CryptBlocks(c.packetData[:encLength], c.packetData[:encLength])
  525. if _, err := w.Write(c.packetData); err != nil {
  526. return err
  527. }
  528. return nil
  529. }
  530. const chacha20Poly1305ID = "chacha20-poly1305@openssh.com"
  531. // chacha20Poly1305Cipher implements the chacha20-poly1305@openssh.com
  532. // AEAD, which is described here:
  533. //
  534. // https://tools.ietf.org/html/draft-josefsson-ssh-chacha20-poly1305-openssh-00
  535. //
  536. // the methods here also implement padding, which RFC 4253 Section 6
  537. // also requires of stream ciphers.
  538. type chacha20Poly1305Cipher struct {
  539. lengthKey [32]byte
  540. contentKey [32]byte
  541. buf []byte
  542. }
  543. func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) {
  544. if len(key) != 64 {
  545. panic(len(key))
  546. }
  547. c := &chacha20Poly1305Cipher{
  548. buf: make([]byte, 256),
  549. }
  550. copy(c.contentKey[:], key[:32])
  551. copy(c.lengthKey[:], key[32:])
  552. return c, nil
  553. }
  554. func (c *chacha20Poly1305Cipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) {
  555. nonce := make([]byte, 12)
  556. binary.BigEndian.PutUint32(nonce[8:], seqNum)
  557. s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce)
  558. if err != nil {
  559. return nil, err
  560. }
  561. var polyKey, discardBuf [32]byte
  562. s.XORKeyStream(polyKey[:], polyKey[:])
  563. s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes
  564. encryptedLength := c.buf[:4]
  565. if _, err := io.ReadFull(r, encryptedLength); err != nil {
  566. return nil, err
  567. }
  568. var lenBytes [4]byte
  569. ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce)
  570. if err != nil {
  571. return nil, err
  572. }
  573. ls.XORKeyStream(lenBytes[:], encryptedLength)
  574. length := binary.BigEndian.Uint32(lenBytes[:])
  575. if length > maxPacket {
  576. return nil, errors.New("ssh: invalid packet length, packet too large")
  577. }
  578. contentEnd := 4 + length
  579. packetEnd := contentEnd + poly1305.TagSize
  580. if uint32(cap(c.buf)) < packetEnd {
  581. c.buf = make([]byte, packetEnd)
  582. copy(c.buf[:], encryptedLength)
  583. } else {
  584. c.buf = c.buf[:packetEnd]
  585. }
  586. if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil {
  587. return nil, err
  588. }
  589. var mac [poly1305.TagSize]byte
  590. copy(mac[:], c.buf[contentEnd:packetEnd])
  591. if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) {
  592. return nil, errors.New("ssh: MAC failure")
  593. }
  594. plain := c.buf[4:contentEnd]
  595. s.XORKeyStream(plain, plain)
  596. if len(plain) == 0 {
  597. return nil, errors.New("ssh: empty packet")
  598. }
  599. padding := plain[0]
  600. if padding < 4 {
  601. // padding is a byte, so it automatically satisfies
  602. // the maximum size, which is 255.
  603. return nil, fmt.Errorf("ssh: illegal padding %d", padding)
  604. }
  605. if int(padding)+1 >= len(plain) {
  606. return nil, fmt.Errorf("ssh: padding %d too large", padding)
  607. }
  608. plain = plain[1 : len(plain)-int(padding)]
  609. return plain, nil
  610. }
  611. func (c *chacha20Poly1305Cipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error {
  612. nonce := make([]byte, 12)
  613. binary.BigEndian.PutUint32(nonce[8:], seqNum)
  614. s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce)
  615. if err != nil {
  616. return err
  617. }
  618. var polyKey, discardBuf [32]byte
  619. s.XORKeyStream(polyKey[:], polyKey[:])
  620. s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes
  621. // There is no blocksize, so fall back to multiple of 8 byte
  622. // padding, as described in RFC 4253, Sec 6.
  623. const packetSizeMultiple = 8
  624. padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple
  625. if padding < 4 {
  626. padding += packetSizeMultiple
  627. }
  628. // size (4 bytes), padding (1), payload, padding, tag.
  629. totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize
  630. if cap(c.buf) < totalLength {
  631. c.buf = make([]byte, totalLength)
  632. } else {
  633. c.buf = c.buf[:totalLength]
  634. }
  635. binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding))
  636. ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce)
  637. if err != nil {
  638. return err
  639. }
  640. ls.XORKeyStream(c.buf, c.buf[:4])
  641. c.buf[4] = byte(padding)
  642. copy(c.buf[5:], payload)
  643. packetEnd := 5 + len(payload) + padding
  644. if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil {
  645. return err
  646. }
  647. s.XORKeyStream(c.buf[4:], c.buf[4:packetEnd])
  648. var mac [poly1305.TagSize]byte
  649. poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey)
  650. copy(c.buf[packetEnd:], mac[:])
  651. if _, err := w.Write(c.buf); err != nil {
  652. return err
  653. }
  654. return nil
  655. }