obfuscator.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. "crypto/rc4"
  23. "crypto/sha1"
  24. "crypto/sha256"
  25. "encoding/binary"
  26. "fmt"
  27. "io"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  33. "golang.org/x/crypto/hkdf"
  34. )
  35. const (
  36. OBFUSCATE_SEED_LENGTH = 16
  37. OBFUSCATE_KEY_LENGTH = 16
  38. OBFUSCATE_HASH_ITERATIONS = 6000
  39. OBFUSCATE_MAX_PADDING = 8192
  40. OBFUSCATE_MAGIC_VALUE = 0x0BF5CA7E
  41. OBFUSCATE_CLIENT_TO_SERVER_IV = "client_to_server"
  42. OBFUSCATE_SERVER_TO_CLIENT_IV = "server_to_client"
  43. // Preamble header is the first 24 bytes of the connection. If no prefix is applied,
  44. // the first 24 bytes are the Obfuscated SSH seed, magic value and padding length.
  45. PREAMBLE_HEADER_LENGTH = OBFUSCATE_SEED_LENGTH + 8 // 4 bytes each for magic value and padding length
  46. PREFIX_TERMINATOR_LENGTH = 16
  47. PREFIX_TERM_SEARCH_BUF_SIZE = 8192
  48. PREFIX_MAX_LENGTH = 65536
  49. PREFIX_MAX_HEADER_LENGTH = 4096
  50. )
  51. type OSSHPrefixSpec struct {
  52. Name string
  53. Spec transforms.Spec
  54. Seed *prng.Seed
  55. }
  56. // OSSHPrefixHeader is the prefix header. It is written by the client
  57. // when a prefix is applied, and read by the server to determine the
  58. // prefix-spec to use.
  59. type OSSHPrefixHeader struct {
  60. SpecName string
  61. }
  62. // OSSHPrefixSplitConfig are parameters for splitting the
  63. // preamble into two writes: prefix followed by rest of the preamble.
  64. type OSSHPrefixSplitConfig struct {
  65. Seed *prng.Seed
  66. MinDelay time.Duration
  67. MaxDelay time.Duration
  68. }
  69. // Obfuscator implements the seed message, key derivation, and
  70. // stream ciphers for:
  71. // https://github.com/brl/obfuscated-openssh/blob/master/README.obfuscation
  72. //
  73. // Limitation: the RC4 cipher is vulnerable to ciphertext malleability and
  74. // the "magic" value provides only weak authentication due to its small
  75. // size. Increasing the size of the magic field will break compatibility
  76. // with legacy clients. New protocols and schemes should not use this
  77. // obfuscator.
  78. type Obfuscator struct {
  79. preamble []byte
  80. // Length of the prefix in the preamble.
  81. preambleOSSHPrefixLength int
  82. // osshPrefixHeader is the prefix header written by the client,
  83. // or the prefix header read by the server.
  84. osshPrefixHeader *OSSHPrefixHeader
  85. osshPrefixSplitConfig *OSSHPrefixSplitConfig
  86. keyword string
  87. paddingLength int
  88. clientToServerCipher *rc4.Cipher
  89. serverToClientCipher *rc4.Cipher
  90. paddingPRNGSeed *prng.Seed
  91. paddingPRNG *prng.PRNG
  92. }
  93. // ObfuscatorConfig specifies an Obfuscator configuration.
  94. type ObfuscatorConfig struct {
  95. IsOSSH bool
  96. Keyword string
  97. ClientPrefixSpec *OSSHPrefixSpec
  98. ServerPrefixSpecs transforms.Specs
  99. OSSHPrefixSplitConfig *OSSHPrefixSplitConfig
  100. PaddingPRNGSeed *prng.Seed
  101. MinPadding *int
  102. MaxPadding *int
  103. ObfuscatorSeedTransformerParameters *transforms.ObfuscatorSeedTransformerParameters
  104. // SeedHistory and IrregularLogger are optional parameters used only by
  105. // server obfuscators.
  106. SeedHistory *SeedHistory
  107. StrictHistoryMode bool
  108. IrregularLogger func(clientIP string, err error, logFields common.LogFields)
  109. }
  110. // NewClientObfuscator creates a new Obfuscator, staging a seed message to be
  111. // sent to the server (by the caller) and initializing stream ciphers to
  112. // obfuscate data.
  113. //
  114. // ObfuscatorConfig.PaddingPRNGSeed allows for optional replay of the
  115. // obfuscator padding and must not be nil.
  116. func NewClientObfuscator(
  117. config *ObfuscatorConfig) (obfuscator *Obfuscator, err error) {
  118. if config.Keyword == "" {
  119. return nil, errors.TraceNew("missing keyword")
  120. }
  121. if config.PaddingPRNGSeed == nil {
  122. return nil, errors.TraceNew("missing padding seed")
  123. }
  124. paddingPRNG := prng.NewPRNGWithSeed(config.PaddingPRNGSeed)
  125. obfuscatorSeed, err := common.MakeSecureRandomBytes(OBFUSCATE_SEED_LENGTH)
  126. if err != nil {
  127. return nil, errors.Trace(err)
  128. }
  129. // This transform may reduce the entropy of the seed, which decreases
  130. // the security of the stream cipher key. However, the stream cipher is
  131. // for obfuscation purposes only.
  132. if config.IsOSSH && config.ObfuscatorSeedTransformerParameters != nil {
  133. err = config.ObfuscatorSeedTransformerParameters.Apply(obfuscatorSeed)
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. }
  138. clientToServerCipher, serverToClientCipher, err := initObfuscatorCiphers(config, obfuscatorSeed)
  139. if err != nil {
  140. return nil, errors.Trace(err)
  141. }
  142. // The first prng.SEED_LENGTH bytes of the initial obfuscator message
  143. // padding field is used by the server as a seed for its obfuscator
  144. // padding and other protocol attributes (directly and via
  145. // GetDerivedPRNG). This allows for optional downstream replay of these
  146. // protocol attributes. Accordingly, the minimum padding is set to at
  147. // least prng.SEED_LENGTH.
  148. minPadding := prng.SEED_LENGTH
  149. if config.MinPadding != nil &&
  150. *config.MinPadding >= prng.SEED_LENGTH &&
  151. *config.MinPadding <= OBFUSCATE_MAX_PADDING {
  152. minPadding = *config.MinPadding
  153. }
  154. maxPadding := OBFUSCATE_MAX_PADDING
  155. if config.MaxPadding != nil &&
  156. *config.MaxPadding >= prng.SEED_LENGTH &&
  157. *config.MaxPadding <= OBFUSCATE_MAX_PADDING &&
  158. *config.MaxPadding >= minPadding {
  159. maxPadding = *config.MaxPadding
  160. }
  161. preamble, prefixLen, prefixHeader, paddingLength, err := makeClientPreamble(
  162. config.Keyword, config.ClientPrefixSpec,
  163. paddingPRNG, minPadding, maxPadding, obfuscatorSeed,
  164. clientToServerCipher)
  165. if err != nil {
  166. return nil, errors.Trace(err)
  167. }
  168. return &Obfuscator{
  169. preamble: preamble,
  170. preambleOSSHPrefixLength: prefixLen,
  171. osshPrefixHeader: prefixHeader,
  172. osshPrefixSplitConfig: config.OSSHPrefixSplitConfig,
  173. keyword: config.Keyword,
  174. paddingLength: paddingLength,
  175. clientToServerCipher: clientToServerCipher,
  176. serverToClientCipher: serverToClientCipher,
  177. paddingPRNGSeed: config.PaddingPRNGSeed,
  178. paddingPRNG: paddingPRNG}, nil
  179. }
  180. // NewServerObfuscator creates a new Obfuscator, reading a seed message directly
  181. // from the clientReader and initializing stream ciphers to obfuscate data.
  182. //
  183. // ObfuscatorConfig.PaddingPRNGSeed is not used, as the server obtains a PRNG
  184. // seed from the client's initial obfuscator message; this scheme allows for
  185. // optional replay of the downstream obfuscator padding.
  186. //
  187. // The clientIP value is used by the SeedHistory, which retains client IP values
  188. // for a short time. See SeedHistory documentation.
  189. func NewServerObfuscator(
  190. config *ObfuscatorConfig, clientIP string, clientReader io.Reader) (obfuscator *Obfuscator, err error) {
  191. if config.Keyword == "" {
  192. return nil, errors.TraceNew("missing keyword")
  193. }
  194. clientToServerCipher, serverToClientCipher, paddingPRNGSeed, prefixHeader, err := readPreamble(
  195. config, clientIP, clientReader)
  196. if err != nil {
  197. return nil, errors.Trace(err)
  198. }
  199. preamble, prefixLen, err := makeServerPreamble(prefixHeader, config.ServerPrefixSpecs, config.Keyword)
  200. if err != nil {
  201. return nil, errors.Trace(err)
  202. }
  203. return &Obfuscator{
  204. preamble: preamble,
  205. preambleOSSHPrefixLength: prefixLen,
  206. osshPrefixHeader: prefixHeader,
  207. osshPrefixSplitConfig: config.OSSHPrefixSplitConfig,
  208. keyword: config.Keyword,
  209. paddingLength: -1,
  210. clientToServerCipher: clientToServerCipher,
  211. serverToClientCipher: serverToClientCipher,
  212. paddingPRNGSeed: paddingPRNGSeed,
  213. paddingPRNG: prng.NewPRNGWithSeed(paddingPRNGSeed),
  214. }, nil
  215. }
  216. // GetDerivedPRNG creates a new PRNG with a seed derived from the obfuscator
  217. // padding seed and distinguished by the salt, which should be a unique
  218. // identifier for each usage context.
  219. //
  220. // For NewServerObfuscator, the obfuscator padding seed is obtained from the
  221. // client, so derived PRNGs may be used to replay sequences post-initial
  222. // obfuscator message.
  223. func (obfuscator *Obfuscator) GetDerivedPRNG(salt string) (*prng.PRNG, error) {
  224. seed, err := prng.NewPRNGWithSaltedSeed(obfuscator.paddingPRNGSeed, salt)
  225. return seed, errors.Trace(err)
  226. }
  227. // GetDerivedPRNGSeed creates a new PRNG seed derived from the obfuscator
  228. // padding seed and distinguished by the salt, which should be a unique
  229. // identifier for each usage context.
  230. //
  231. // For NewServerObfuscator, the obfuscator padding seed is obtained from the
  232. // client, so derived seeds may be used to replay sequences post-initial
  233. // obfuscator message.
  234. func (obfuscator *Obfuscator) GetDerivedPRNGSeed(salt string) (*prng.Seed, error) {
  235. seed, err := prng.NewSaltedSeed(obfuscator.paddingPRNGSeed, salt)
  236. return seed, errors.Trace(err)
  237. }
  238. // GetPaddingLength returns the client seed message padding length. Only valid
  239. // for NewClientObfuscator.
  240. func (obfuscator *Obfuscator) GetPaddingLength() int {
  241. return obfuscator.paddingLength
  242. }
  243. // SendPreamble returns the preamble created in NewObfuscatorClient or
  244. // NewServerObfuscator, removing the reference so that it may be garbage collected.
  245. func (obfuscator *Obfuscator) SendPreamble() ([]byte, int) {
  246. msg := obfuscator.preamble
  247. prefixLen := obfuscator.preambleOSSHPrefixLength
  248. obfuscator.preamble = nil
  249. obfuscator.preambleOSSHPrefixLength = 0
  250. return msg, prefixLen
  251. }
  252. // ObfuscateClientToServer applies the client RC4 stream to the bytes in buffer.
  253. func (obfuscator *Obfuscator) ObfuscateClientToServer(buffer []byte) {
  254. obfuscator.clientToServerCipher.XORKeyStream(buffer, buffer)
  255. }
  256. // ObfuscateServerToClient applies the server RC4 stream to the bytes in buffer.
  257. func (obfuscator *Obfuscator) ObfuscateServerToClient(buffer []byte) {
  258. obfuscator.serverToClientCipher.XORKeyStream(buffer, buffer)
  259. }
  260. func initObfuscatorCiphers(
  261. config *ObfuscatorConfig, obfuscatorSeed []byte) (*rc4.Cipher, *rc4.Cipher, error) {
  262. clientToServerKey, err := deriveKey(obfuscatorSeed, []byte(config.Keyword), []byte(OBFUSCATE_CLIENT_TO_SERVER_IV))
  263. if err != nil {
  264. return nil, nil, errors.Trace(err)
  265. }
  266. serverToClientKey, err := deriveKey(obfuscatorSeed, []byte(config.Keyword), []byte(OBFUSCATE_SERVER_TO_CLIENT_IV))
  267. if err != nil {
  268. return nil, nil, errors.Trace(err)
  269. }
  270. clientToServerCipher, err := rc4.NewCipher(clientToServerKey)
  271. if err != nil {
  272. return nil, nil, errors.Trace(err)
  273. }
  274. serverToClientCipher, err := rc4.NewCipher(serverToClientKey)
  275. if err != nil {
  276. return nil, nil, errors.Trace(err)
  277. }
  278. return clientToServerCipher, serverToClientCipher, nil
  279. }
  280. func deriveKey(obfuscatorSeed, keyword, iv []byte) ([]byte, error) {
  281. h := sha1.New()
  282. h.Write(obfuscatorSeed)
  283. h.Write(keyword)
  284. h.Write(iv)
  285. digest := h.Sum(nil)
  286. for i := 0; i < OBFUSCATE_HASH_ITERATIONS; i++ {
  287. h.Reset()
  288. h.Write(digest)
  289. digest = h.Sum(nil)
  290. }
  291. if len(digest) < OBFUSCATE_KEY_LENGTH {
  292. return nil, errors.TraceNew("insufficient bytes for obfuscation key")
  293. }
  294. return digest[0:OBFUSCATE_KEY_LENGTH], nil
  295. }
  296. // makeClientPreamble generates the preamble bytes for the Obfuscated SSH protocol.
  297. //
  298. // If a prefix is applied, preamble bytes refer to the prefix, prefix terminator,
  299. // followed by the Obufscted SSH initial client message, followed by the
  300. // prefix header.
  301. //
  302. // If a prefix is not applied, preamble bytes refer to the Obfuscated SSH
  303. // initial client message (referred to as the "seed message" in the original spec):
  304. // https://github.com/brl/obfuscated-openssh/blob/master/README.obfuscation
  305. //
  306. // Obfuscated SSH initial client message (no prefix):
  307. //
  308. // [ 16 byte random seed ][ OSSH magic ][ padding length ][ padding ]
  309. // |_____________________||_________________________________________|
  310. //
  311. // | |
  312. // Plaintext Encrypted with key derived from seed
  313. //
  314. // Prefix + Obfuscated SSH initial client message:
  315. //
  316. // [ 24+ byte prefix ][ terminator ][ OSSH initial client message ][ prefix header ]
  317. // |_________________||____________________________________________________________|
  318. //
  319. // | |
  320. // Plaintext Encrypted with key derived from first 24 bytes
  321. //
  322. // Returns the preamble, the prefix header if a prefix was generated,
  323. // and the padding length.
  324. func makeClientPreamble(
  325. keyword string,
  326. prefixSpec *OSSHPrefixSpec,
  327. paddingPRNG *prng.PRNG,
  328. minPadding, maxPadding int,
  329. obfuscatorSeed []byte,
  330. clientToServerCipher *rc4.Cipher) ([]byte, int, *OSSHPrefixHeader, int, error) {
  331. padding := paddingPRNG.Padding(minPadding, maxPadding)
  332. buffer := new(bytes.Buffer)
  333. magicValueStartIndex := len(obfuscatorSeed)
  334. prefixLen := 0
  335. if prefixSpec != nil {
  336. var b []byte
  337. var err error
  338. b, prefixLen, err = makeTerminatedPrefixWithPadding(prefixSpec, keyword, OBFUSCATE_CLIENT_TO_SERVER_IV)
  339. if err != nil {
  340. return nil, 0, nil, 0, errors.Trace(err)
  341. }
  342. _, err = buffer.Write(b)
  343. if err != nil {
  344. return nil, 0, nil, 0, errors.Trace(err)
  345. }
  346. magicValueStartIndex += len(b)
  347. }
  348. err := binary.Write(buffer, binary.BigEndian, obfuscatorSeed)
  349. if err != nil {
  350. return nil, 0, nil, 0, errors.Trace(err)
  351. }
  352. err = binary.Write(buffer, binary.BigEndian, uint32(OBFUSCATE_MAGIC_VALUE))
  353. if err != nil {
  354. return nil, 0, nil, 0, errors.Trace(err)
  355. }
  356. err = binary.Write(buffer, binary.BigEndian, uint32(len(padding)))
  357. if err != nil {
  358. return nil, 0, nil, 0, errors.Trace(err)
  359. }
  360. err = binary.Write(buffer, binary.BigEndian, padding)
  361. if err != nil {
  362. return nil, 0, nil, 0, errors.Trace(err)
  363. }
  364. var prefixHeader *OSSHPrefixHeader = nil
  365. if prefixSpec != nil {
  366. // Writes the prefix header after the padding.
  367. err := prefixSpec.writePrefixHeader(buffer)
  368. if err != nil {
  369. return nil, 0, nil, 0, errors.Trace(err)
  370. }
  371. prefixHeader = &OSSHPrefixHeader{
  372. SpecName: prefixSpec.Name,
  373. }
  374. }
  375. preamble := buffer.Bytes()
  376. // Encryptes what comes after the magic value.
  377. clientToServerCipher.XORKeyStream(
  378. preamble[magicValueStartIndex:],
  379. preamble[magicValueStartIndex:])
  380. return preamble, prefixLen, prefixHeader, len(padding), nil
  381. }
  382. // makeServerPreamble generates a server preamble (prefix or nil).
  383. // If the header is nil, nil is returned. Otherwise, prefix is generated
  384. // from serverSpecs matching the spec name in the header.
  385. // If the spec name is not found in serverSpecs, random bytes
  386. // of length PREAMBLE_HEADER_LENGTH are returned.
  387. func makeServerPreamble(
  388. header *OSSHPrefixHeader,
  389. serverSpecs transforms.Specs,
  390. keyword string) ([]byte, int, error) {
  391. if header == nil {
  392. return nil, 0, nil
  393. }
  394. spec, ok := serverSpecs[header.SpecName]
  395. if !ok {
  396. // Generate a random prefix if the spec is not found.
  397. spec = transforms.Spec{{"", fmt.Sprintf(`[\x00-\xff]{%d}`, PREAMBLE_HEADER_LENGTH)}}
  398. }
  399. seed, err := prng.NewSeed()
  400. if err != nil {
  401. return nil, 0, errors.Trace(err)
  402. }
  403. prefixSpec := &OSSHPrefixSpec{
  404. Name: header.SpecName,
  405. Spec: spec,
  406. Seed: seed,
  407. }
  408. return makeTerminatedPrefixWithPadding(prefixSpec, keyword, OBFUSCATE_SERVER_TO_CLIENT_IV)
  409. }
  410. // readPreamble reads the preamble bytes from the client. If it does not detect
  411. // valid magic value in the first 24 bytes, it assumes that a prefix is applied.
  412. // If a prefix is applied, it first discard the prefix and the terminator, before
  413. // looking for a valid Obfuscated SSH initial client message.
  414. func readPreamble(
  415. config *ObfuscatorConfig,
  416. clientIP string,
  417. clientReader io.Reader) (*rc4.Cipher, *rc4.Cipher, *prng.Seed, *OSSHPrefixHeader, error) {
  418. return readPreambleHelper(config, clientIP, clientReader, false)
  419. }
  420. func readPreambleHelper(
  421. config *ObfuscatorConfig,
  422. clientIP string,
  423. clientReader io.Reader,
  424. removedPrefix bool) (*rc4.Cipher, *rc4.Cipher, *prng.Seed, *OSSHPrefixHeader, error) {
  425. // To distinguish different cases, irregular tunnel logs should indicate
  426. // which function called NewServerObfuscator.
  427. errBackTrace := "obfuscator.NewServerObfuscator"
  428. // Since the OSSH stream might be prefixed, the seed might not be the first
  429. // 16 bytes of the stream. The stream is read until valid magic value
  430. // is detected, PREFIX_MAX_LENGTH is reached, or until the stream is exhausted.
  431. // If the magic value is found, the seed is the 16 bytes before the magic value,
  432. // and is added to and checked against the seed history.
  433. preambleHeader := make([]byte, PREAMBLE_HEADER_LENGTH)
  434. _, err := io.ReadFull(clientReader, preambleHeader)
  435. if err != nil {
  436. return nil, nil, nil, nil, errors.Trace(err)
  437. }
  438. osshSeed := preambleHeader[:OBFUSCATE_SEED_LENGTH]
  439. clientToServerCipher, serverToClientCipher, err := initObfuscatorCiphers(
  440. config, osshSeed)
  441. if err != nil {
  442. return nil, nil, nil, nil, errors.Trace(err)
  443. }
  444. osshFixedLengthFields := make([]byte, 8) // 4 bytes each for magic value and padding length
  445. clientToServerCipher.XORKeyStream(osshFixedLengthFields, preambleHeader[OBFUSCATE_SEED_LENGTH:])
  446. // The magic value must be validated before acting on paddingLength as
  447. // paddingLength validation is vulnerable to a chosen ciphertext probing
  448. // attack: only a fixed number of any possible byte value for each
  449. // paddingLength is valid.
  450. buffer := bytes.NewReader(osshFixedLengthFields)
  451. var magicValue, paddingLength int32
  452. err = binary.Read(buffer, binary.BigEndian, &magicValue)
  453. if err != nil {
  454. return nil, nil, nil, nil, errors.Trace(err)
  455. }
  456. err = binary.Read(buffer, binary.BigEndian, &paddingLength)
  457. if err != nil {
  458. return nil, nil, nil, nil, errors.Trace(err)
  459. }
  460. if magicValue != OBFUSCATE_MAGIC_VALUE && removedPrefix {
  461. // Prefix terminator was found, but rest of the stream is not valid
  462. // Obfuscated SSH.
  463. errStr := "invalid magic value"
  464. if config.IrregularLogger != nil {
  465. config.IrregularLogger(
  466. clientIP,
  467. errors.BackTraceNew(errBackTrace, errStr),
  468. nil)
  469. }
  470. return nil, nil, nil, nil, errors.TraceNew(errStr)
  471. }
  472. if magicValue == OBFUSCATE_MAGIC_VALUE {
  473. if config.SeedHistory != nil {
  474. // Adds the seed to the seed history only if the magic value is valid.
  475. // This is to prevent malicious clients from filling up the history cache.
  476. ok, duplicateLogFields := config.SeedHistory.AddNew(
  477. config.StrictHistoryMode, clientIP, "obfuscator-seed", osshSeed)
  478. errStr := "duplicate obfuscation seed"
  479. if duplicateLogFields != nil {
  480. if config.IrregularLogger != nil {
  481. config.IrregularLogger(
  482. clientIP,
  483. errors.BackTraceNew(errBackTrace, errStr),
  484. *duplicateLogFields)
  485. }
  486. }
  487. if !ok {
  488. return nil, nil, nil, nil, errors.TraceNew(errStr)
  489. }
  490. }
  491. if paddingLength < 0 || paddingLength > OBFUSCATE_MAX_PADDING {
  492. errStr := "invalid padding length"
  493. if config.IrregularLogger != nil {
  494. config.IrregularLogger(
  495. clientIP,
  496. errors.BackTraceNew(errBackTrace, errStr),
  497. nil)
  498. }
  499. return nil, nil, nil, nil, errors.TraceNew(errStr)
  500. }
  501. padding := make([]byte, paddingLength)
  502. _, err = io.ReadFull(clientReader, padding)
  503. if err != nil {
  504. return nil, nil, nil, nil, errors.Trace(err)
  505. }
  506. clientToServerCipher.XORKeyStream(padding, padding)
  507. var prefixHeader *OSSHPrefixHeader = nil
  508. if removedPrefix {
  509. // This is a valid prefixed OSSH stream.
  510. prefixHeader, err = readPrefixHeader(clientReader, clientToServerCipher)
  511. if err != nil {
  512. if config.IrregularLogger != nil {
  513. config.IrregularLogger(
  514. clientIP,
  515. errors.BackTraceNew(errBackTrace, "invalid prefix header"),
  516. nil)
  517. }
  518. return nil, nil, nil, nil, errors.Trace(err)
  519. }
  520. }
  521. // Use the first prng.SEED_LENGTH bytes of padding as a PRNG seed for
  522. // subsequent operations. This allows the client to direct server-side
  523. // replay of certain protocol attributes.
  524. //
  525. // Since legacy clients may send < prng.SEED_LENGTH bytes of padding,
  526. // generate a new seed in that case.
  527. var paddingPRNGSeed *prng.Seed
  528. if len(padding) >= prng.SEED_LENGTH {
  529. paddingPRNGSeed = new(prng.Seed)
  530. copy(paddingPRNGSeed[:], padding[0:prng.SEED_LENGTH])
  531. } else {
  532. paddingPRNGSeed, err = prng.NewSeed()
  533. if err != nil {
  534. return nil, nil, nil, nil, errors.Trace(err)
  535. }
  536. }
  537. return clientToServerCipher, serverToClientCipher, paddingPRNGSeed, prefixHeader, nil
  538. }
  539. if !removedPrefix {
  540. // No magic value found, could be a prefixed OSSH stream.
  541. // Skips up to the prefix terminator, and looks for the magic value again.
  542. clientReader, ok := clientReader.(*SkipReader)
  543. if !ok {
  544. return nil, nil, nil, nil, errors.TraceNew("expected SkipReader")
  545. }
  546. terminator, err := makeTerminator(config.Keyword, preambleHeader, OBFUSCATE_CLIENT_TO_SERVER_IV)
  547. if err != nil {
  548. return nil, nil, nil, nil, errors.Trace(err)
  549. }
  550. err = clientReader.SkipUpToToken(terminator, PREFIX_TERM_SEARCH_BUF_SIZE, PREFIX_MAX_LENGTH)
  551. if err != nil {
  552. // No magic value or prefix terminator found,
  553. // log irregular tunnel and return error.
  554. errStr := "no prefix terminator or invalid magic value"
  555. if config.IrregularLogger != nil {
  556. config.IrregularLogger(
  557. clientIP,
  558. errors.BackTraceNew(errBackTrace, errStr),
  559. nil)
  560. }
  561. return nil, nil, nil, nil, errors.TraceNew(errStr)
  562. }
  563. // Reads OSSH initial client message followed by prefix header.
  564. return readPreambleHelper(config, clientIP, clientReader, true)
  565. }
  566. // Should never reach here.
  567. return nil, nil, nil, nil, errors.TraceNew("unexpected error")
  568. }
  569. // makeTerminator generates a prefix terminator used in finding end of prefix
  570. // placed before OSSH stream.
  571. // b should be at least PREAMBLE_HEADER_LENGTH bytes and contain enough entropy.
  572. func makeTerminator(keyword string, b []byte, direction string) ([]byte, error) {
  573. // Bytes length is at least equal to obfuscator seed message.
  574. if len(b) < PREAMBLE_HEADER_LENGTH {
  575. return nil, errors.TraceNew("bytes too short")
  576. }
  577. if (direction != OBFUSCATE_CLIENT_TO_SERVER_IV) &&
  578. (direction != OBFUSCATE_SERVER_TO_CLIENT_IV) {
  579. return nil, errors.TraceNew("invalid direction")
  580. }
  581. hkdf := hkdf.New(sha256.New,
  582. []byte(keyword),
  583. b[:PREAMBLE_HEADER_LENGTH],
  584. []byte(direction))
  585. terminator := make([]byte, PREFIX_TERMINATOR_LENGTH)
  586. _, err := io.ReadFull(hkdf, terminator)
  587. if err != nil {
  588. return nil, errors.Trace(err)
  589. }
  590. return terminator, nil
  591. }
  592. // makeTerminatedPrefixWithPadding generates bytes starting with the prefix bytes defiend
  593. // by spec and ending with the generated terminator.
  594. // If the generated prefix is shorter than PREAMBLE_HEADER_LENGTH, it is padded
  595. // with random bytes.
  596. // Returns the generated prefix with teminator, and the length of the prefix if no error.
  597. func makeTerminatedPrefixWithPadding(spec *OSSHPrefixSpec, keyword, direction string) ([]byte, int, error) {
  598. prefix, prefixLen, err := spec.Spec.ApplyPrefix(spec.Seed, PREAMBLE_HEADER_LENGTH)
  599. if err != nil {
  600. return nil, 0, errors.Trace(err)
  601. }
  602. terminator, err := makeTerminator(keyword, prefix, direction)
  603. if err != nil {
  604. return nil, 0, errors.Trace(err)
  605. }
  606. terminatedPrefix := append(prefix, terminator...)
  607. return terminatedPrefix, prefixLen, nil
  608. }
  609. // writePrefixHeader writes the prefix header to the given writer.
  610. // The prefix header is written in the following format:
  611. //
  612. // [ 2 byte version ][4 byte spec-length ][ .. prefix-spec-name ...]
  613. func (spec *OSSHPrefixSpec) writePrefixHeader(w io.Writer) error {
  614. if len(spec.Name) > PREFIX_MAX_HEADER_LENGTH {
  615. return errors.TraceNew("prefix name too long")
  616. }
  617. err := binary.Write(w, binary.BigEndian, uint16(0x01))
  618. if err != nil {
  619. return errors.Trace(err)
  620. }
  621. err = binary.Write(w, binary.BigEndian, uint16(len(spec.Name)))
  622. if err != nil {
  623. return errors.Trace(err)
  624. }
  625. _, err = w.Write([]byte(spec.Name))
  626. if err != nil {
  627. return errors.Trace(err)
  628. }
  629. return nil
  630. }
  631. func readPrefixHeader(
  632. clientReader io.Reader,
  633. cipher *rc4.Cipher) (*OSSHPrefixHeader, error) {
  634. fixedLengthFields := make([]byte, 4)
  635. _, err := io.ReadFull(clientReader, fixedLengthFields)
  636. if err != nil {
  637. return nil, errors.Trace(err)
  638. }
  639. cipher.XORKeyStream(fixedLengthFields, fixedLengthFields)
  640. buffer := bytes.NewBuffer(fixedLengthFields)
  641. var version uint16
  642. err = binary.Read(buffer, binary.BigEndian, &version)
  643. if err != nil {
  644. return nil, errors.Trace(err)
  645. }
  646. if version != 0x01 {
  647. return nil, errors.TraceNew("invalid version")
  648. }
  649. var specLen uint16
  650. err = binary.Read(buffer, binary.BigEndian, &specLen)
  651. if err != nil {
  652. return nil, errors.Trace(err)
  653. }
  654. if specLen > PREFIX_MAX_HEADER_LENGTH {
  655. return nil, errors.TraceNew("invalid header length")
  656. }
  657. // Read the spec name.
  658. specName := make([]byte, specLen)
  659. _, err = io.ReadFull(clientReader, specName)
  660. if err != nil {
  661. return nil, errors.Trace(err)
  662. }
  663. cipher.XORKeyStream(specName, specName)
  664. return &OSSHPrefixHeader{
  665. SpecName: string(specName),
  666. }, nil
  667. }