cipher.go 20 KB

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