obfuscatedSshConn.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package obfuscator
  20. import (
  21. "bytes"
  22. "encoding/binary"
  23. "errors"
  24. "io"
  25. "io/ioutil"
  26. "net"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  29. )
  30. const (
  31. SSH_MAX_SERVER_LINE_LENGTH = 1024
  32. SSH_PACKET_PREFIX_LENGTH = 5 // uint32 + byte
  33. SSH_MAX_PACKET_LENGTH = 256 * 1024 // OpenSSH max packet length
  34. SSH_MSG_NEWKEYS = 21
  35. SSH_MAX_PADDING_LENGTH = 255 // RFC 4253 sec. 6
  36. SSH_PADDING_MULTIPLE = 16 // Default cipher block size
  37. )
  38. // ObfuscatedSSHConn wraps a Conn and applies the obfuscated SSH protocol
  39. // to the traffic on the connection:
  40. // https://github.com/brl/obfuscated-openssh/blob/master/README.obfuscation
  41. //
  42. // ObfuscatedSSHConn is used to add obfuscation to golang's stock "ssh"
  43. // client and server without modification to that standard library code.
  44. // The underlying connection must be used for SSH traffic. This code
  45. // injects the obfuscated seed message, applies obfuscated stream cipher
  46. // transformations, and performs minimal parsing of the SSH protocol to
  47. // determine when to stop obfuscation (after the first SSH_MSG_NEWKEYS is
  48. // sent and received).
  49. //
  50. // WARNING: doesn't fully conform to net.Conn concurrency semantics: there's
  51. // no synchronization of access to the read/writeBuffers, so concurrent
  52. // calls to one of Read or Write will result in undefined behavior.
  53. //
  54. type ObfuscatedSSHConn struct {
  55. net.Conn
  56. mode ObfuscatedSSHConnMode
  57. obfuscator *Obfuscator
  58. readDeobfuscate func([]byte)
  59. writeObfuscate func([]byte)
  60. readState ObfuscatedSSHReadState
  61. writeState ObfuscatedSSHWriteState
  62. readBuffer *bytes.Buffer
  63. writeBuffer *bytes.Buffer
  64. transformBuffer *bytes.Buffer
  65. legacyPadding bool
  66. paddingLength int
  67. paddingPRNG *prng.PRNG
  68. }
  69. type ObfuscatedSSHConnMode int
  70. const (
  71. OBFUSCATION_CONN_MODE_CLIENT = iota
  72. OBFUSCATION_CONN_MODE_SERVER
  73. )
  74. type ObfuscatedSSHReadState int
  75. const (
  76. OBFUSCATION_READ_STATE_IDENTIFICATION_LINES = iota
  77. OBFUSCATION_READ_STATE_KEX_PACKETS
  78. OBFUSCATION_READ_STATE_FLUSH
  79. OBFUSCATION_READ_STATE_FINISHED
  80. )
  81. type ObfuscatedSSHWriteState int
  82. const (
  83. OBFUSCATION_WRITE_STATE_CLIENT_SEND_SEED_MESSAGE = iota
  84. OBFUSCATION_WRITE_STATE_SERVER_SEND_IDENTIFICATION_LINE_PADDING
  85. OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE
  86. OBFUSCATION_WRITE_STATE_KEX_PACKETS
  87. OBFUSCATION_WRITE_STATE_FINISHED
  88. )
  89. // NewObfuscatedSSHConn creates a new ObfuscatedSSHConn.
  90. // The underlying conn must be used for SSH traffic and must have
  91. // transferred no traffic.
  92. //
  93. // In client mode, NewObfuscatedSSHConn does not block or initiate network
  94. // I/O. The obfuscation seed message is sent when Write() is first called.
  95. //
  96. // In server mode, NewObfuscatedSSHConn cannot completely initialize itself
  97. // without the seed message from the client to derive obfuscation keys. So
  98. // NewObfuscatedSSHConn blocks on reading the client seed message from the
  99. // underlying conn.
  100. //
  101. // obfuscationPaddingPRNGSeed is required and used only in
  102. // OBFUSCATION_CONN_MODE_CLIENT mode and allows for optional replay of the
  103. // same padding: both in the initial obfuscator message and in the SSH KEX
  104. // sequence. In OBFUSCATION_CONN_MODE_SERVER mode, the server obtains its PRNG
  105. // seed from the client's initial obfuscator message, resulting in the server
  106. // replaying its padding as well.
  107. func NewObfuscatedSSHConn(
  108. mode ObfuscatedSSHConnMode,
  109. conn net.Conn,
  110. obfuscationKeyword string,
  111. obfuscationPaddingPRNGSeed *prng.Seed,
  112. minPadding, maxPadding *int) (*ObfuscatedSSHConn, error) {
  113. var err error
  114. var obfuscator *Obfuscator
  115. var readDeobfuscate, writeObfuscate func([]byte)
  116. var writeState ObfuscatedSSHWriteState
  117. if mode == OBFUSCATION_CONN_MODE_CLIENT {
  118. obfuscator, err = NewClientObfuscator(
  119. &ObfuscatorConfig{
  120. Keyword: obfuscationKeyword,
  121. PaddingPRNGSeed: obfuscationPaddingPRNGSeed,
  122. MinPadding: minPadding,
  123. MaxPadding: maxPadding,
  124. })
  125. if err != nil {
  126. return nil, common.ContextError(err)
  127. }
  128. readDeobfuscate = obfuscator.ObfuscateServerToClient
  129. writeObfuscate = obfuscator.ObfuscateClientToServer
  130. writeState = OBFUSCATION_WRITE_STATE_CLIENT_SEND_SEED_MESSAGE
  131. } else {
  132. // NewServerObfuscator reads a seed message from conn
  133. obfuscator, err = NewServerObfuscator(
  134. conn, &ObfuscatorConfig{
  135. Keyword: obfuscationKeyword,
  136. })
  137. if err != nil {
  138. // Obfuscated SSH protocol spec:
  139. // "If these checks fail the server will continue reading and discarding all data
  140. // until the client closes the connection without sending anything in response."
  141. //
  142. // This may be terminated by a server-side connection establishment timeout.
  143. io.Copy(ioutil.Discard, conn)
  144. return nil, common.ContextError(err)
  145. }
  146. readDeobfuscate = obfuscator.ObfuscateClientToServer
  147. writeObfuscate = obfuscator.ObfuscateServerToClient
  148. writeState = OBFUSCATION_WRITE_STATE_SERVER_SEND_IDENTIFICATION_LINE_PADDING
  149. }
  150. paddingPRNG, err := obfuscator.GetDerivedPRNG("obfuscated-ssh-padding")
  151. if err != nil {
  152. return nil, common.ContextError(err)
  153. }
  154. return &ObfuscatedSSHConn{
  155. Conn: conn,
  156. mode: mode,
  157. obfuscator: obfuscator,
  158. readDeobfuscate: readDeobfuscate,
  159. writeObfuscate: writeObfuscate,
  160. readState: OBFUSCATION_READ_STATE_IDENTIFICATION_LINES,
  161. writeState: writeState,
  162. readBuffer: new(bytes.Buffer),
  163. writeBuffer: new(bytes.Buffer),
  164. transformBuffer: new(bytes.Buffer),
  165. paddingLength: -1,
  166. paddingPRNG: paddingPRNG,
  167. }, nil
  168. }
  169. // GetDerivedPRNG creates a new PRNG with a seed derived from the
  170. // ObfuscatedSSHConn padding seed and distinguished by the salt, which should
  171. // be a unique identifier for each usage context.
  172. //
  173. // In OBFUSCATION_CONN_MODE_SERVER mode, the ObfuscatedSSHConn padding seed is
  174. // obtained from the client, so derived PRNGs may be used to replay sequences
  175. // post-initial obfuscator message.
  176. func (conn *ObfuscatedSSHConn) GetDerivedPRNG(salt string) (*prng.PRNG, error) {
  177. return conn.obfuscator.GetDerivedPRNG(salt)
  178. }
  179. // GetMetrics implements the common.MetricsSource interface.
  180. func (conn *ObfuscatedSSHConn) GetMetrics() common.LogFields {
  181. logFields := make(common.LogFields)
  182. if conn.mode == OBFUSCATION_CONN_MODE_CLIENT {
  183. paddingLength := conn.obfuscator.GetPaddingLength()
  184. if paddingLength != -1 {
  185. logFields["upstream_ossh_padding"] = paddingLength
  186. }
  187. } else {
  188. if conn.paddingLength != -1 {
  189. logFields["downstream_ossh_padding"] = conn.paddingLength
  190. }
  191. }
  192. return logFields
  193. }
  194. // Read wraps standard Read, transparently applying the obfuscation
  195. // transformations.
  196. func (conn *ObfuscatedSSHConn) Read(buffer []byte) (int, error) {
  197. if conn.readState == OBFUSCATION_READ_STATE_FINISHED {
  198. return conn.Conn.Read(buffer)
  199. }
  200. n, err := conn.readAndTransform(buffer)
  201. if err != nil {
  202. err = common.ContextError(err)
  203. }
  204. return n, err
  205. }
  206. // Write wraps standard Write, transparently applying the obfuscation
  207. // transformations.
  208. func (conn *ObfuscatedSSHConn) Write(buffer []byte) (int, error) {
  209. if conn.writeState == OBFUSCATION_WRITE_STATE_FINISHED {
  210. return conn.Conn.Write(buffer)
  211. }
  212. err := conn.transformAndWrite(buffer)
  213. if err != nil {
  214. return 0, common.ContextError(err)
  215. }
  216. // Reports that we wrote all the bytes
  217. // (although we may have buffered some or all)
  218. return len(buffer), nil
  219. }
  220. // readAndTransform reads and transforms the downstream bytes stream
  221. // while in an obfucation state. It parses the stream of bytes read
  222. // looking for the first SSH_MSG_NEWKEYS packet sent from the peer,
  223. // after which obfuscation is turned off. Since readAndTransform may
  224. // read in more bytes that the higher-level conn.Read() can consume,
  225. // read bytes are buffered and may be returned in subsequent calls.
  226. //
  227. // readAndTransform also implements a workaround for issues with
  228. // ssh/transport.go exchangeVersions/readVersion and Psiphon's openssh
  229. // server.
  230. //
  231. // Psiphon's server sends extra lines before the version line, as
  232. // permitted by http://www.ietf.org/rfc/rfc4253.txt sec 4.2:
  233. // The server MAY send other lines of data before sending the
  234. // version string. [...] Clients MUST be able to process such lines.
  235. //
  236. // A comment in exchangeVersions explains that the golang code doesn't
  237. // support this:
  238. // Contrary to the RFC, we do not ignore lines that don't
  239. // start with "SSH-2.0-" to make the library usable with
  240. // nonconforming servers.
  241. //
  242. // In addition, Psiphon's server sends up to 512 characters per extra
  243. // line. It's not clear that the 255 max string size in sec 4.2 refers
  244. // to the extra lines as well, but in any case golang's code only
  245. // supports 255 character lines.
  246. //
  247. // State OBFUSCATION_READ_STATE_IDENTIFICATION_LINES: in this
  248. // state, extra lines are read and discarded. Once the peer's
  249. // identification string line is read, it is buffered and returned
  250. // as per the requested read buffer size.
  251. //
  252. // State OBFUSCATION_READ_STATE_KEX_PACKETS: reads, deobfuscates,
  253. // and buffers full SSH packets, checking for SSH_MSG_NEWKEYS. Packet
  254. // data is returned as per the requested read buffer size.
  255. //
  256. // State OBFUSCATION_READ_STATE_FLUSH: after SSH_MSG_NEWKEYS, no more
  257. // packets are read by this function, but bytes from the SSH_MSG_NEWKEYS
  258. // packet may need to be buffered due to partial reading.
  259. func (conn *ObfuscatedSSHConn) readAndTransform(buffer []byte) (int, error) {
  260. nextState := conn.readState
  261. switch conn.readState {
  262. case OBFUSCATION_READ_STATE_IDENTIFICATION_LINES:
  263. // TODO: only client should accept multiple lines?
  264. if conn.readBuffer.Len() == 0 {
  265. for {
  266. err := readSSHIdentificationLine(
  267. conn.Conn, conn.readDeobfuscate, conn.readBuffer)
  268. if err != nil {
  269. return 0, common.ContextError(err)
  270. }
  271. if bytes.HasPrefix(conn.readBuffer.Bytes(), []byte("SSH-")) {
  272. if bytes.Contains(conn.readBuffer.Bytes(), []byte("Ganymed")) {
  273. conn.legacyPadding = true
  274. }
  275. break
  276. }
  277. // Discard extra line
  278. conn.readBuffer.Truncate(0)
  279. }
  280. }
  281. nextState = OBFUSCATION_READ_STATE_KEX_PACKETS
  282. case OBFUSCATION_READ_STATE_KEX_PACKETS:
  283. if conn.readBuffer.Len() == 0 {
  284. isMsgNewKeys, err := readSSHPacket(
  285. conn.Conn, conn.readDeobfuscate, conn.readBuffer)
  286. if err != nil {
  287. return 0, common.ContextError(err)
  288. }
  289. if isMsgNewKeys {
  290. nextState = OBFUSCATION_READ_STATE_FLUSH
  291. }
  292. }
  293. case OBFUSCATION_READ_STATE_FLUSH:
  294. nextState = OBFUSCATION_READ_STATE_FINISHED
  295. case OBFUSCATION_READ_STATE_FINISHED:
  296. return 0, common.ContextError(errors.New("invalid read state"))
  297. }
  298. n, err := conn.readBuffer.Read(buffer)
  299. if err == io.EOF {
  300. err = nil
  301. }
  302. if err != nil {
  303. return n, common.ContextError(err)
  304. }
  305. if conn.readBuffer.Len() == 0 {
  306. conn.readState = nextState
  307. if conn.readState == OBFUSCATION_READ_STATE_FINISHED {
  308. // The buffer memory is no longer used
  309. conn.readBuffer = nil
  310. }
  311. }
  312. return n, nil
  313. }
  314. // transformAndWrite transforms the upstream bytes stream while in an
  315. // obfucation state, buffers bytes as necessary for parsing, and writes
  316. // transformed bytes to the network connection. Bytes are obfuscated until
  317. // after the first SSH_MSG_NEWKEYS packet is sent.
  318. //
  319. // There are two mode-specific states:
  320. //
  321. // State OBFUSCATION_WRITE_STATE_CLIENT_SEND_SEED_MESSAGE: the initial
  322. // state, when the client has not sent any data. In this state, the seed message
  323. // is injected into the client output stream.
  324. //
  325. // State OBFUSCATION_WRITE_STATE_SERVER_SEND_IDENTIFICATION_LINE_PADDING: the
  326. // initial state, when the server has not sent any data. In this state, the
  327. // additional lines of padding are injected into the server output stream.
  328. // This padding is a partial defense against traffic analysis against the
  329. // otherwise-fixed size server version line. This makes use of the
  330. // "other lines of data" allowance, before the version line, which clients
  331. // will ignore (http://tools.ietf.org/html/rfc4253#section-4.2).
  332. //
  333. // State OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE: before
  334. // packets are sent, the SSH peer sends an identification line terminated by CRLF:
  335. // http://www.ietf.org/rfc/rfc4253.txt sec 4.2.
  336. // In this state, the CRLF terminator is used to parse message boundaries.
  337. //
  338. // State OBFUSCATION_WRITE_STATE_KEX_PACKETS: follows the binary
  339. // packet protocol, parsing each packet until the first SSH_MSG_NEWKEYS.
  340. // http://www.ietf.org/rfc/rfc4253.txt sec 6:
  341. // uint32 packet_length
  342. // byte padding_length
  343. // byte[n1] payload; n1 = packet_length - padding_length - 1
  344. // byte[n2] random padding; n2 = padding_length
  345. // byte[m] mac (Message Authentication Code - MAC); m = mac_length
  346. // m is 0 as no MAC ha yet been negotiated.
  347. // http://www.ietf.org/rfc/rfc4253.txt sec 7.3, 12:
  348. // The payload for SSH_MSG_NEWKEYS is one byte, the packet type, value 21.
  349. //
  350. // SSH packet padding values are transformed to achieve random, variable length
  351. // padding during the KEX phase as a partial defense against traffic analysis.
  352. // (The transformer can do this since only the payload and not the padding of
  353. // these packets is authenticated in the "exchange hash").
  354. func (conn *ObfuscatedSSHConn) transformAndWrite(buffer []byte) error {
  355. // The seed message (client) and identification line padding (server)
  356. // are injected before any standard SSH traffic.
  357. if conn.writeState == OBFUSCATION_WRITE_STATE_CLIENT_SEND_SEED_MESSAGE {
  358. _, err := conn.Conn.Write(conn.obfuscator.SendSeedMessage())
  359. if err != nil {
  360. return common.ContextError(err)
  361. }
  362. conn.writeState = OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE
  363. } else if conn.writeState == OBFUSCATION_WRITE_STATE_SERVER_SEND_IDENTIFICATION_LINE_PADDING {
  364. padding := makeServerIdentificationLinePadding(conn.paddingPRNG)
  365. conn.paddingLength = len(padding)
  366. conn.writeObfuscate(padding)
  367. _, err := conn.Conn.Write(padding)
  368. if err != nil {
  369. return common.ContextError(err)
  370. }
  371. conn.writeState = OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE
  372. }
  373. // writeBuffer is used to buffer bytes received from Write() until a
  374. // complete SSH message is received. transformBuffer is used as a scratch
  375. // buffer for size-changing tranformations, including padding transforms.
  376. // All data flows as follows:
  377. // conn.Write() -> writeBuffer -> transformBuffer -> conn.Conn.Write()
  378. conn.writeBuffer.Write(buffer)
  379. switch conn.writeState {
  380. case OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE:
  381. hasIdentificationLine := extractSSHIdentificationLine(
  382. conn.writeBuffer, conn.transformBuffer)
  383. if hasIdentificationLine {
  384. conn.writeState = OBFUSCATION_WRITE_STATE_KEX_PACKETS
  385. }
  386. case OBFUSCATION_WRITE_STATE_KEX_PACKETS:
  387. hasMsgNewKeys, err := extractSSHPackets(
  388. conn.paddingPRNG,
  389. conn.legacyPadding,
  390. conn.writeBuffer,
  391. conn.transformBuffer)
  392. if err != nil {
  393. return common.ContextError(err)
  394. }
  395. if hasMsgNewKeys {
  396. conn.writeState = OBFUSCATION_WRITE_STATE_FINISHED
  397. }
  398. case OBFUSCATION_WRITE_STATE_FINISHED:
  399. return common.ContextError(errors.New("invalid write state"))
  400. }
  401. if conn.transformBuffer.Len() > 0 {
  402. sendData := conn.transformBuffer.Next(conn.transformBuffer.Len())
  403. conn.writeObfuscate(sendData)
  404. _, err := conn.Conn.Write(sendData)
  405. if err != nil {
  406. return common.ContextError(err)
  407. }
  408. }
  409. if conn.writeState == OBFUSCATION_WRITE_STATE_FINISHED {
  410. if conn.writeBuffer.Len() > 0 {
  411. // After SSH_MSG_NEWKEYS, any remaining bytes are un-obfuscated
  412. _, err := conn.Conn.Write(conn.writeBuffer.Bytes())
  413. if err != nil {
  414. return common.ContextError(err)
  415. }
  416. }
  417. // The buffer memory is no longer used
  418. conn.writeBuffer = nil
  419. conn.transformBuffer = nil
  420. }
  421. return nil
  422. }
  423. func readSSHIdentificationLine(
  424. conn net.Conn,
  425. deobfuscate func([]byte),
  426. readBuffer *bytes.Buffer) error {
  427. // TODO: less redundant string searching?
  428. var oneByte [1]byte
  429. var validLine = false
  430. readBuffer.Grow(SSH_MAX_SERVER_LINE_LENGTH)
  431. for i := 0; i < SSH_MAX_SERVER_LINE_LENGTH; i++ {
  432. _, err := io.ReadFull(conn, oneByte[:])
  433. if err != nil {
  434. return common.ContextError(err)
  435. }
  436. deobfuscate(oneByte[:])
  437. readBuffer.WriteByte(oneByte[0])
  438. if bytes.HasSuffix(readBuffer.Bytes(), []byte("\r\n")) {
  439. validLine = true
  440. break
  441. }
  442. }
  443. if !validLine {
  444. return common.ContextError(errors.New("invalid identification line"))
  445. }
  446. return nil
  447. }
  448. func readSSHPacket(
  449. conn net.Conn,
  450. deobfuscate func([]byte),
  451. readBuffer *bytes.Buffer) (bool, error) {
  452. prefixOffset := readBuffer.Len()
  453. readBuffer.Grow(SSH_PACKET_PREFIX_LENGTH)
  454. n, err := readBuffer.ReadFrom(io.LimitReader(conn, SSH_PACKET_PREFIX_LENGTH))
  455. if err == nil && n != SSH_PACKET_PREFIX_LENGTH {
  456. err = errors.New("unxpected number of bytes read")
  457. }
  458. if err != nil {
  459. return false, common.ContextError(err)
  460. }
  461. prefix := readBuffer.Bytes()[prefixOffset : prefixOffset+SSH_PACKET_PREFIX_LENGTH]
  462. deobfuscate(prefix)
  463. _, _, payloadLength, messageLength, err := getSSHPacketPrefix(prefix)
  464. if err != nil {
  465. return false, common.ContextError(err)
  466. }
  467. remainingReadLength := messageLength - SSH_PACKET_PREFIX_LENGTH
  468. readBuffer.Grow(remainingReadLength)
  469. n, err = readBuffer.ReadFrom(io.LimitReader(conn, int64(remainingReadLength)))
  470. if err == nil && n != int64(remainingReadLength) {
  471. err = errors.New("unxpected number of bytes read")
  472. }
  473. if err != nil {
  474. return false, common.ContextError(err)
  475. }
  476. remainingBytes := readBuffer.Bytes()[prefixOffset+SSH_PACKET_PREFIX_LENGTH:]
  477. deobfuscate(remainingBytes)
  478. isMsgNewKeys := false
  479. if payloadLength > 0 {
  480. packetType := int(readBuffer.Bytes()[prefixOffset+SSH_PACKET_PREFIX_LENGTH])
  481. if packetType == SSH_MSG_NEWKEYS {
  482. isMsgNewKeys = true
  483. }
  484. }
  485. return isMsgNewKeys, nil
  486. }
  487. // From the original patch to sshd.c:
  488. // https://bitbucket.org/psiphon/psiphon-circumvention-system/commits/f40865ce624b680be840dc2432283c8137bd896d
  489. func makeServerIdentificationLinePadding(prng *prng.PRNG) []byte {
  490. paddingLength := prng.Intn(OBFUSCATE_MAX_PADDING - 2 + 1) // 2 = CRLF
  491. paddingLength += 2
  492. padding := make([]byte, paddingLength)
  493. // For backwards compatibility with some clients, send no more than 512 characters
  494. // per line (including CRLF). To keep the padding distribution between 0 and OBFUSCATE_MAX_PADDING
  495. // characters, we send lines that add up to padding_length characters including all CRLFs.
  496. minLineLength := 2
  497. maxLineLength := 512
  498. lineStartIndex := 0
  499. for paddingLength > 0 {
  500. lineLength := paddingLength
  501. if lineLength > maxLineLength {
  502. lineLength = maxLineLength
  503. }
  504. // Leave enough padding allowance to send a full CRLF on the last line
  505. if paddingLength-lineLength > 0 &&
  506. paddingLength-lineLength < minLineLength {
  507. lineLength -= minLineLength - (paddingLength - lineLength)
  508. }
  509. padding[lineStartIndex+lineLength-2] = '\r'
  510. padding[lineStartIndex+lineLength-1] = '\n'
  511. lineStartIndex += lineLength
  512. paddingLength -= lineLength
  513. }
  514. return padding
  515. }
  516. func extractSSHIdentificationLine(writeBuffer, transformBuffer *bytes.Buffer) bool {
  517. index := bytes.Index(writeBuffer.Bytes(), []byte("\r\n"))
  518. if index != -1 {
  519. lineLength := index + 2 // + 2 for \r\n
  520. transformBuffer.Write(writeBuffer.Next(lineLength))
  521. return true
  522. }
  523. return false
  524. }
  525. func extractSSHPackets(
  526. prng *prng.PRNG,
  527. legacyPadding bool,
  528. writeBuffer, transformBuffer *bytes.Buffer) (bool, error) {
  529. hasMsgNewKeys := false
  530. for writeBuffer.Len() >= SSH_PACKET_PREFIX_LENGTH {
  531. packetLength, paddingLength, payloadLength, messageLength, err := getSSHPacketPrefix(
  532. writeBuffer.Bytes()[:SSH_PACKET_PREFIX_LENGTH])
  533. if err != nil {
  534. return false, common.ContextError(err)
  535. }
  536. if writeBuffer.Len() < messageLength {
  537. // We don't have the complete packet yet
  538. break
  539. }
  540. packet := writeBuffer.Next(messageLength)
  541. if payloadLength > 0 {
  542. packetType := int(packet[SSH_PACKET_PREFIX_LENGTH])
  543. if packetType == SSH_MSG_NEWKEYS {
  544. hasMsgNewKeys = true
  545. }
  546. }
  547. transformedPacketOffset := transformBuffer.Len()
  548. transformBuffer.Write(packet)
  549. transformedPacket := transformBuffer.Bytes()[transformedPacketOffset:]
  550. // Padding transformation
  551. extraPaddingLength := 0
  552. if !legacyPadding {
  553. // This does not satisfy RFC 4253 sec. 6 constraints:
  554. // - The goal is to vary packet sizes as much as possible.
  555. // - We implement both the client and server sides and both sides accept
  556. // less constrained paddings (for plaintext packets).
  557. possibleExtraPaddingLength := (SSH_MAX_PADDING_LENGTH - paddingLength)
  558. if possibleExtraPaddingLength > 0 {
  559. // extraPaddingLength is integer in range [0, possiblePadding + 1)
  560. extraPaddingLength = prng.Intn(possibleExtraPaddingLength + 1)
  561. }
  562. } else {
  563. // See RFC 4253 sec. 6 for constraints
  564. possiblePaddings := (SSH_MAX_PADDING_LENGTH - paddingLength) / SSH_PADDING_MULTIPLE
  565. if possiblePaddings > 0 {
  566. // selectedPadding is integer in range [0, possiblePaddings)
  567. selectedPadding := prng.Intn(possiblePaddings)
  568. extraPaddingLength = selectedPadding * SSH_PADDING_MULTIPLE
  569. }
  570. }
  571. extraPadding := prng.Bytes(extraPaddingLength)
  572. setSSHPacketPrefix(
  573. transformedPacket,
  574. packetLength+extraPaddingLength,
  575. paddingLength+extraPaddingLength)
  576. transformBuffer.Write(extraPadding)
  577. }
  578. return hasMsgNewKeys, nil
  579. }
  580. func getSSHPacketPrefix(buffer []byte) (int, int, int, int, error) {
  581. packetLength := int(binary.BigEndian.Uint32(buffer[0 : SSH_PACKET_PREFIX_LENGTH-1]))
  582. if packetLength < 1 || packetLength > SSH_MAX_PACKET_LENGTH {
  583. return 0, 0, 0, 0, common.ContextError(errors.New("invalid SSH packet length"))
  584. }
  585. paddingLength := int(buffer[SSH_PACKET_PREFIX_LENGTH-1])
  586. payloadLength := packetLength - paddingLength - 1
  587. messageLength := SSH_PACKET_PREFIX_LENGTH + packetLength - 1
  588. return packetLength, paddingLength, payloadLength, messageLength, nil
  589. }
  590. func setSSHPacketPrefix(buffer []byte, packetLength, paddingLength int) {
  591. binary.BigEndian.PutUint32(buffer, uint32(packetLength))
  592. buffer[SSH_PACKET_PREFIX_LENGTH-1] = byte(paddingLength)
  593. }