common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // common.go - Transport common implementation.
  2. // Copyright (C) 2016 Yawning Angel.
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as
  6. // published by the Free Software Foundation, either version 3 of the
  7. // License, or (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. // Package basket2 implements the basket2 authenticated/encrypted/obfuscated
  17. // network transport protocol.
  18. //
  19. // Note that the package will block during init() if the system entropy pool
  20. // is not properly initialized on systems where there is support for
  21. // determining this information. This is a feature, and "working around" this
  22. // "bug" will likely totally destroy security.
  23. package basket2
  24. import (
  25. "errors"
  26. "fmt"
  27. "io"
  28. mrand "math/rand"
  29. "net"
  30. "sync"
  31. "time"
  32. "git.schwanenlied.me/yawning/basket2.git/crypto/rand"
  33. "git.schwanenlied.me/yawning/basket2.git/framing"
  34. "git.schwanenlied.me/yawning/basket2.git/framing/tentp"
  35. )
  36. const (
  37. // ProtocolVersion is the transport protocol version.
  38. ProtocolVersion = 0
  39. // PaddingInvalid is a invalid/undefined padding method.
  40. PaddingInvalid PaddingMethod = 0xff
  41. minReqExtDataSize = 1 + 1 + 1 // Version, nrPaddingAlgs, > 1 padding alg.
  42. minRespExtDataSize = 1 + 1 + 1 // Version, authPolicy, padding alg.
  43. tauReadDelay = 5000 // Microseconds.
  44. defaultCopyBufferSize = 32 * 1024
  45. )
  46. var (
  47. // ErrInvalidState is the error returned on an invalid state or transition.
  48. ErrInvalidState = errors.New("basket2: invalid state")
  49. // ErrInvalidCmd is the error returned on decoding a framing packet with
  50. // an invalid command.
  51. ErrInvalidCmd = errors.New("basket2: invalid command")
  52. // ErrInvalidPadding is the error returned when the client requests no
  53. // compatible padding methods, or the server specifies a incompatible
  54. // padding method.
  55. ErrInvalidPadding = errors.New("basket2: invalid padding")
  56. // ErrMsgSize is the error returned on a message size violation.
  57. ErrMsgSize = errors.New("basket2: oversized message")
  58. // ErrInvalidExtData is the error returned when the req/resp handshake
  59. // extData is invalid.
  60. ErrInvalidExtData = errors.New("basket2: invalid ext data")
  61. // ErrNotSupported is the error returned on an unsupported call.
  62. ErrNotSupported = errors.New("basket2: operation not supported")
  63. supportedPaddingMethods = []PaddingMethod{
  64. PaddingTamaraw,
  65. PaddingObfs4BurstIAT,
  66. PaddingObfs4Burst,
  67. PaddingNull,
  68. }
  69. )
  70. // PaddingMethod is a given padding algorithm identifier.
  71. type PaddingMethod byte
  72. // AuthPolicy is the server authentication policy.
  73. type AuthPolicy byte
  74. const (
  75. // AuthNone indicates that the client must not authenticate.
  76. AuthNone AuthPolicy = iota
  77. // AuthMust indicates that the client must authenticate.
  78. AuthMust
  79. )
  80. type connState int
  81. const (
  82. stateInit connState = iota
  83. stateHandshaking
  84. stateAuthenticate
  85. stateEstablished
  86. stateError
  87. )
  88. // ToHexString returns the hexdecimal string representation of a padding method.
  89. func (m PaddingMethod) ToHexString() string {
  90. return fmt.Sprintf("%02x", m)
  91. }
  92. // ToString returms the descriptive string representaiton of a padding method.
  93. func (m PaddingMethod) ToString() string {
  94. switch m {
  95. case PaddingNull:
  96. return "Null"
  97. case PaddingObfs4Burst:
  98. return "Obfs4Burst"
  99. case PaddingObfs4BurstIAT:
  100. return "Obfs4BurstIAT"
  101. case PaddingTamaraw:
  102. return "Tamaraw"
  103. default:
  104. return "[Unknown algorithm]"
  105. }
  106. }
  107. // PaddingMethodFromString returns the PaddingMethod corresponding to a given
  108. // string.
  109. func PaddingMethodFromString(s string) PaddingMethod {
  110. switch s {
  111. case "Null":
  112. return PaddingNull
  113. case "Obfs4Burst":
  114. return PaddingObfs4Burst
  115. case "Obfs4BurstIAT":
  116. return PaddingObfs4BurstIAT
  117. case "Tamaraw":
  118. return PaddingTamaraw
  119. default:
  120. return PaddingInvalid
  121. }
  122. }
  123. // ConnStats contains the per-connection metrics useful for examining the
  124. // overhead/performance of the various padding algorithms.
  125. type ConnStats struct {
  126. RxBytes uint64
  127. RxOverheadBytes uint64
  128. RxPayloadBytes uint64
  129. RxPaddingBytes uint64
  130. TxBytes uint64
  131. TxOverheadBytes uint64
  132. TxPayloadBytes uint64
  133. TxPaddingBytes uint64
  134. }
  135. // ToString returns the descriptive string representation of the connection
  136. // statistics.
  137. func (s *ConnStats) ToString() string {
  138. rxGoodput := float64(s.RxPayloadBytes) / float64(s.RxBytes)
  139. txGoodput := float64(s.TxPayloadBytes) / float64(s.TxBytes)
  140. return fmt.Sprintf("Receive: Total: %v Overhead: %v Payload: %v Padding: %v Goodput: %v Trasmit: Total: %v Overhead: %v Payload: %v Padding: %v Goodput: %v", s.RxBytes, s.RxOverheadBytes, s.RxPayloadBytes, s.RxPaddingBytes, rxGoodput, s.TxBytes, s.TxOverheadBytes, s.TxPayloadBytes, s.TxPaddingBytes, txGoodput)
  141. }
  142. type commonConn struct {
  143. sync.Mutex
  144. mRNG *mrand.Rand
  145. state connState
  146. stats ConnStats
  147. rawConn net.Conn
  148. txEncoder *tentp.Encoder
  149. rxDecoder *tentp.Decoder
  150. impl paddingImpl
  151. paddingMethod PaddingMethod
  152. maxRecordSize int
  153. copyBufferSize int
  154. enforceRecordSize bool
  155. enableReadDelay bool
  156. isClient bool
  157. }
  158. // Stats returns the connection's ConnStats structure.
  159. func (c *commonConn) Stats() *ConnStats {
  160. return &c.stats
  161. }
  162. // SetCopyBufferSize sets the hint used to detect large bulk transfers
  163. // when the connection is the destination side of io.Copy()/io.CopyBuffer().
  164. // By default something sensible for io.Copy() will be used.
  165. func (c *commonConn) SetCopyBufferSize(sz int) {
  166. if sz <= 0 {
  167. panic("basket2: SetCopyBufferSize called with invalid value")
  168. }
  169. c.copyBufferSize = sz
  170. }
  171. // Write writes len(p) bytes to the stream, and returns the number of bytes
  172. // written, or an error. All errors must be considered fatal.
  173. func (c *commonConn) Write(p []byte) (n int, err error) {
  174. defer func() {
  175. if err != nil {
  176. c.setState(stateError)
  177. }
  178. }()
  179. if !c.stateAllowsIO() {
  180. return 0, ErrInvalidState
  181. }
  182. return c.impl.Write(p)
  183. }
  184. // Read reads up to len(p) bytes from the stream, and returns the number of
  185. // bytes read, or an error. All errors must be considered fatal.
  186. func (c *commonConn) Read(p []byte) (n int, err error) {
  187. defer func() {
  188. if err != nil {
  189. c.setState(stateError)
  190. }
  191. }()
  192. if !c.stateAllowsIO() {
  193. return 0, ErrInvalidState
  194. }
  195. n, err = c.impl.Read(p)
  196. if c.enableReadDelay && n > 0 {
  197. // If data payload was received and read delay is enabled,
  198. // delay for a random interval [0, 2 * tau) usec.
  199. //
  200. // This is primarily intended for the server side of the Tor
  201. // Pluggable transport code in an attempt to mitigate delay based
  202. // flow tagging attacks for upstream traffic into the Tor network.
  203. delay := time.Duration(c.mRNG.Intn(tauReadDelay*2)) * time.Microsecond
  204. time.Sleep(delay)
  205. }
  206. return n, err
  207. }
  208. // Close closes the connection and purges cryptographic keying material from
  209. // memory.
  210. func (c *commonConn) Close() error {
  211. err := c.rawConn.Close()
  212. c.setState(stateError)
  213. return err
  214. }
  215. // LocalAddr returns the local address of the connection.
  216. func (c *commonConn) LocalAddr() net.Addr {
  217. return c.rawConn.LocalAddr()
  218. }
  219. // RemoteAddr returns the remote address of the connection.
  220. func (c *commonConn) RemoteAddr() net.Addr {
  221. return c.rawConn.RemoteAddr()
  222. }
  223. // SetDeadline returns ErrNotSupported.
  224. func (c *commonConn) SetDeadline(t time.Time) error {
  225. return ErrNotSupported
  226. }
  227. // SetReadDeadline returns ErrNotSupported.
  228. func (c *commonConn) SetReadDeadline(t time.Time) error {
  229. return ErrNotSupported
  230. }
  231. // SetWriteDeadline returns ErrNotSupported.
  232. func (c *commonConn) SetWriteDeadline(t time.Time) error {
  233. return ErrNotSupported
  234. }
  235. func (c *commonConn) initConn(conn net.Conn) error {
  236. var err error
  237. if err = c.setState(stateHandshaking); err != nil {
  238. return err
  239. }
  240. c.paddingMethod = PaddingInvalid
  241. c.mRNG = rand.New()
  242. c.copyBufferSize = defaultCopyBufferSize
  243. // Derive the "max" record size based off the remote address,
  244. // under the assumption that 1500 byte MTU ethernet is in use.
  245. //
  246. // This value is intended as a hint for the padding algorithms
  247. // when determining how to size records, and may not actually
  248. // resemble what goes out on the wire depending on what the kernel
  249. // does and the state of the TCP/IP stack.
  250. if taddr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  251. if taddr.IP.To16() != nil {
  252. // Connected to an IPv6 peer.
  253. c.maxRecordSize = tentp.MaxIdealIPv6Size
  254. } else {
  255. // Commected to an IPv4 peer.
  256. c.maxRecordSize = tentp.MaxIdealIPv4Size
  257. }
  258. } else {
  259. // No idea what kind of connection this is, use the IPv4 max frame
  260. // size.
  261. c.maxRecordSize = tentp.MaxIdealIPv4Size
  262. }
  263. c.rawConn = conn
  264. return nil
  265. }
  266. func (c *commonConn) initFraming(kdf io.Reader) error {
  267. var err error
  268. if c.isClient {
  269. if c.txEncoder, err = tentp.NewEncoderFromKDF(kdf); err != nil {
  270. return err
  271. }
  272. if c.rxDecoder, err = tentp.NewDecoderFromKDF(kdf); err != nil {
  273. return err
  274. }
  275. } else {
  276. if c.rxDecoder, err = tentp.NewDecoderFromKDF(kdf); err != nil {
  277. return err
  278. }
  279. if c.txEncoder, err = tentp.NewEncoderFromKDF(kdf); err != nil {
  280. return err
  281. }
  282. }
  283. return nil
  284. }
  285. func (c *commonConn) setState(newState connState) error {
  286. c.Lock()
  287. defer c.Unlock()
  288. switch newState {
  289. case stateInit:
  290. panic("basket2: state transition to Init should NEVER happen")
  291. case stateHandshaking:
  292. if c.state != stateInit {
  293. return ErrInvalidState
  294. }
  295. case stateAuthenticate:
  296. if c.state != stateHandshaking {
  297. return ErrInvalidState
  298. }
  299. case stateEstablished:
  300. if c.state != stateHandshaking && c.state != stateAuthenticate {
  301. return ErrInvalidState
  302. }
  303. case stateError:
  304. // Transition to stateError is always allowed, and will obliterate
  305. // cryptographic material.
  306. if c.txEncoder != nil {
  307. c.txEncoder.Reset()
  308. c.txEncoder = nil
  309. }
  310. if c.rxDecoder != nil {
  311. c.rxDecoder.Reset()
  312. c.rxDecoder = nil
  313. }
  314. // If the padding implementation is present, call the termination
  315. // handler.
  316. if c.impl != nil {
  317. c.impl.OnClose()
  318. c.impl = nil
  319. }
  320. default:
  321. panic(fmt.Sprintf("basket2: state transition to unknown state: %v", newState))
  322. }
  323. c.state = newState
  324. return nil
  325. }
  326. func (c *commonConn) stateAllowsIO() bool {
  327. c.Lock()
  328. defer c.Unlock()
  329. return c.state == stateAuthenticate || c.state == stateEstablished
  330. }
  331. func (c *commonConn) setPadding(method PaddingMethod, params []byte) error {
  332. switch method {
  333. case PaddingNull:
  334. c.impl = newNullPadding(c)
  335. case PaddingObfs4Burst, PaddingObfs4BurstIAT:
  336. var err error
  337. c.impl, err = newObfs4Padding(c, method, params)
  338. if err != nil {
  339. return err
  340. }
  341. case PaddingTamaraw:
  342. c.impl = newTamarawPadding(c, c.isClient)
  343. default:
  344. return ErrInvalidPadding
  345. }
  346. c.paddingMethod = method
  347. return nil
  348. }
  349. func (c *commonConn) setNagle(enable bool) {
  350. if tconn, ok := c.rawConn.(*net.TCPConn); ok {
  351. tconn.SetNoDelay(!enable)
  352. }
  353. }
  354. // SendRawRecord sends a raw record to the peer with the specified command,
  355. // payload and padding length. This call should NOT be interleaved/mixed
  356. // with the net.Conn Read/Write interface.
  357. func (c *commonConn) SendRawRecord(cmd byte, msg []byte, padLen int) (err error) {
  358. defer func() {
  359. if err != nil {
  360. c.setState(stateError)
  361. }
  362. }()
  363. // Validate the state.
  364. if !c.stateAllowsIO() {
  365. return ErrInvalidState
  366. }
  367. if !c.isClient {
  368. cmd |= framing.CmdServer
  369. }
  370. // Encode the TENTP record.
  371. var rec []byte
  372. rec, err = c.txEncoder.EncodeRecord(cmd, msg, padLen)
  373. if err != nil {
  374. return
  375. }
  376. // Transmit the record.
  377. var n int
  378. n, err = c.rawConn.Write(rec)
  379. if err != nil {
  380. return
  381. }
  382. if n != len(rec) {
  383. return io.ErrShortWrite
  384. }
  385. c.stats.TxBytes += uint64(len(rec))
  386. c.stats.TxPayloadBytes += uint64(len(msg))
  387. c.stats.TxOverheadBytes += uint64(len(rec) - (len(msg) + padLen))
  388. c.stats.TxPaddingBytes += uint64(padLen)
  389. return
  390. }
  391. // RecvRawRecord receives a raw record from the peer. This call should NOT be
  392. // interleaved/mixed with the net.Conn Read/Write interface.
  393. func (c *commonConn) RecvRawRecord() (cmd byte, msg []byte, err error) {
  394. defer func() {
  395. if err != nil {
  396. cmd = 0
  397. msg = nil
  398. c.setState(stateError)
  399. }
  400. }()
  401. // Validate the state.
  402. if !c.stateAllowsIO() {
  403. return 0, nil, ErrInvalidState
  404. }
  405. // Receive/Decode the TENTP header.
  406. var recHdr [tentp.FramingOverhead]byte
  407. if _, err = io.ReadFull(c.rawConn, recHdr[:]); err != nil {
  408. return
  409. }
  410. var want int
  411. cmd, want, err = c.rxDecoder.DecodeRecordHdr(recHdr[:])
  412. if err != nil {
  413. return
  414. }
  415. c.stats.RxBytes += tentp.FramingOverhead
  416. c.stats.RxOverheadBytes += tentp.FramingOverhead
  417. // Validate the command direction bit.
  418. cmdCtoS := cmd&framing.CmdServer == 0
  419. if c.isClient == cmdCtoS {
  420. return 0, nil, ErrInvalidCmd
  421. }
  422. cmd &= framing.CmdServerMask
  423. if want == 0 {
  424. // Record with no payload, return early.
  425. return
  426. }
  427. if c.enforceRecordSize && want > c.maxRecordSize+tentp.PayloadOverhead {
  428. return 0, nil, ErrMsgSize
  429. }
  430. // Receive/Decode the TENTP record body.
  431. recBody := make([]byte, want)
  432. if _, err = io.ReadFull(c.rawConn, recBody); err != nil {
  433. return
  434. }
  435. if msg, err = c.rxDecoder.DecodeRecordBody(recBody); err != nil {
  436. return
  437. }
  438. c.stats.RxBytes += uint64(want)
  439. c.stats.RxOverheadBytes += tentp.PayloadOverhead
  440. c.stats.RxPayloadBytes += uint64(len(msg))
  441. c.stats.RxPaddingBytes += uint64(want - (tentp.PayloadOverhead + len(msg)))
  442. return
  443. }
  444. // PaddingMethod returns the padding method negotiated with the peer. This
  445. // will only be set to something useful after a Handshake() call completes
  446. // successfully.
  447. func (c *commonConn) PaddingMethod() PaddingMethod {
  448. return c.paddingMethod
  449. }
  450. func paddingOk(needle PaddingMethod, haystack []PaddingMethod) bool {
  451. for _, v := range haystack {
  452. if needle == v {
  453. return true
  454. }
  455. }
  456. return false
  457. }
  458. // DefaultPaddingParams returns "sensible" parameters for each supported
  459. // padding method that requires parameterization.
  460. func DefaultPaddingParams(method PaddingMethod) ([]byte, error) {
  461. switch method {
  462. case PaddingNull:
  463. return nil, nil
  464. case PaddingObfs4Burst, PaddingObfs4BurstIAT:
  465. // This should be parameterized from persistent state, but allow
  466. // random parametrization.
  467. seed := make([]byte, Obfs4SeedLength)
  468. if _, err := io.ReadFull(rand.Reader, seed); err != nil {
  469. return nil, err
  470. }
  471. return seed, nil
  472. }
  473. return nil, ErrInvalidPadding
  474. }
  475. // SupportedPaddingMethods returns the list of supported padding methods in
  476. // order of preference.
  477. func SupportedPaddingMethods() []PaddingMethod {
  478. var ret []PaddingMethod
  479. ret = append(ret, supportedPaddingMethods...)
  480. return ret
  481. }
  482. func init() {
  483. // This check is here for a reason. If you comment it out, you will
  484. // receive absolutely NO SUPPORT, and bug reports that do not contain
  485. // patches will be IGNORED.
  486. if !isRecentEnoughGo() {
  487. panic("basket2: built with a Go version that is too old")
  488. }
  489. }