httpTransformer.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2023, 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 transforms
  20. import (
  21. "bytes"
  22. "context"
  23. "math"
  24. "net"
  25. "net/textproto"
  26. "strconv"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  30. )
  31. type HTTPTransformerParameters struct {
  32. // ProtocolTransformName specifies the name associated with
  33. // ProtocolTransformSpec and is used for metrics.
  34. ProtocolTransformName string
  35. // ProtocolTransformSpec specifies a transform to apply to the HTTP request.
  36. // See: "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms".
  37. //
  38. // HTTP transforms include strategies discovered by the Geneva team,
  39. // https://geneva.cs.umd.edu.
  40. ProtocolTransformSpec Spec
  41. // ProtocolTransformSeed specifies the seed to use for generating random
  42. // data in the ProtocolTransformSpec transform. To replay a transform,
  43. // specify the same seed.
  44. ProtocolTransformSeed *prng.Seed
  45. }
  46. const (
  47. // httpTransformerReadHeader HTTPTransformer is waiting to finish reading
  48. // the next HTTP request header.
  49. httpTransformerReadHeader = 0
  50. // httpTransformerReadWriteBody HTTPTransformer is waiting to finish reading
  51. // and writing the current HTTP request body.
  52. httpTransformerReadWriteBody = 1
  53. )
  54. // HTTPTransformer wraps a net.Conn, intercepting Write calls and applying the
  55. // specified protocol transform.
  56. //
  57. // The HTTP request to be written (input to the Write) is converted to a
  58. // string, transformed, and converted back to binary and then actually written
  59. // to the underlying net.Conn.
  60. //
  61. // HTTPTransformer is not safe for concurrent use.
  62. type HTTPTransformer struct {
  63. transform Spec
  64. seed *prng.Seed
  65. // state is the HTTPTransformer state. Possible values are
  66. // httpTransformerReadingHeader and httpTransformerReadingBody.
  67. state int64
  68. // b is the accumulated bytes of the current HTTP request.
  69. b []byte
  70. // remain is the number of remaining HTTP request body bytes to read into b.
  71. remain uint64
  72. net.Conn
  73. }
  74. // Warning: Does not handle chunked encoding and multiple HTTP
  75. // requests written in a single Write(). Must be called synchronously.
  76. func (t *HTTPTransformer) Write(b []byte) (int, error) {
  77. if t.state == httpTransformerReadHeader {
  78. t.b = append(t.b, b...)
  79. // Wait until the entire HTTP request header has been read. Must check
  80. // all accumulated bytes incase the "\r\n\r\n" separator is written over
  81. // multiple Write() calls; from reading the net/http code the entire
  82. // HTTP request is written in a single Write() call.
  83. sep := []byte("\r\n\r\n")
  84. headerBodyLines := bytes.SplitN(t.b, sep, 2) // split header and body
  85. if len(headerBodyLines) > 1 {
  86. // read Content-Length before applying transform
  87. var headerLines [][]byte
  88. lines := bytes.Split(headerBodyLines[0], []byte("\r\n"))
  89. if len(lines) > 1 {
  90. // skip request line, e.g. "GET /foo HTTP/1.1"
  91. headerLines = lines[1:]
  92. }
  93. var cl []byte
  94. contentLengthHeader := []byte("Content-Length:")
  95. for _, header := range headerLines {
  96. if bytes.HasPrefix(header, contentLengthHeader) {
  97. cl = textproto.TrimBytes(header[len(contentLengthHeader):])
  98. break
  99. }
  100. }
  101. if len(cl) == 0 {
  102. // Either Content-Length header missing or Content-Length
  103. // header value is empty, e.g. "Content-Length: ".
  104. // b buffered in t.b
  105. return len(b), errors.TraceNew("Content-Length missing")
  106. }
  107. n, err := strconv.ParseUint(string(cl), 10, 63)
  108. if err != nil {
  109. // b buffered in t.b
  110. return len(b), errors.Trace(err)
  111. }
  112. t.remain = n
  113. // transform and write header
  114. headerLen := len(headerBodyLines[0]) + len(sep)
  115. header := t.b[:headerLen]
  116. if t.transform != nil {
  117. newHeaderS, err := t.transform.Apply(t.seed, string(header))
  118. if err != nil {
  119. // b buffered in t.b
  120. return len(b), errors.Trace(err)
  121. }
  122. newHeader := []byte(newHeaderS)
  123. // only allocate new slice if header length changed
  124. if len(newHeader) == len(header) {
  125. copy(t.b[:len(header)], newHeader)
  126. } else {
  127. t.b = append(newHeader, t.b[len(header):]...)
  128. }
  129. header = newHeader
  130. }
  131. if math.MaxUint64-t.remain < uint64(len(header)) {
  132. // b buffered in t.b
  133. return len(b), errors.TraceNew("t.remain + uint64(len(header)) overflows")
  134. }
  135. t.remain += uint64(len(header))
  136. err = t.writeBuffer()
  137. if t.remain > 0 {
  138. // Entire request, header and body, has been written. Return to
  139. // waiting for next HTTP request header to arrive.
  140. t.state = httpTransformerReadWriteBody
  141. }
  142. if err != nil {
  143. // b buffered in t.b
  144. return len(b), errors.Trace(err)
  145. }
  146. }
  147. // b buffered in t.b
  148. return len(b), nil
  149. }
  150. // HTTP request header has been transformed. Write any remaining bytes of
  151. // HTTP request header and then write HTTP request body.
  152. // Must write buffered bytes first, in-order, to write bytes to underlying
  153. // Conn in the same order they were received in.
  154. err := t.writeBuffer()
  155. if err != nil {
  156. // b not written or buffered
  157. return 0, errors.Trace(err)
  158. }
  159. n, err := t.Conn.Write(b)
  160. if uint64(n) > t.remain {
  161. return 0, errors.TraceNew("t.remain - uint64(n) underflows")
  162. }
  163. t.remain -= uint64(n)
  164. if t.remain <= 0 {
  165. // Entire request, header and body, has been written. Return to
  166. // waiting for next HTTP request header to arrive.
  167. t.state = httpTransformerReadHeader
  168. t.remain = 0
  169. }
  170. return n, errors.Trace(err)
  171. }
  172. func (t *HTTPTransformer) writeBuffer() error {
  173. for len(t.b) > 0 {
  174. n, err := t.Conn.Write(t.b)
  175. if uint64(n) > t.remain {
  176. return errors.TraceNew("t.remain - uint64(n) underflows")
  177. }
  178. t.remain -= uint64(n)
  179. if n == len(t.b) {
  180. t.b = nil
  181. } else {
  182. t.b = t.b[n:]
  183. }
  184. if err != nil {
  185. return errors.Trace(err)
  186. }
  187. }
  188. return nil
  189. }
  190. func WrapDialerWithHTTPTransformer(dialer common.Dialer, params *HTTPTransformerParameters) common.Dialer {
  191. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  192. conn, err := dialer(ctx, network, addr)
  193. if err != nil {
  194. return nil, errors.Trace(err)
  195. }
  196. return &HTTPTransformer{
  197. Conn: conn,
  198. transform: params.ProtocolTransformSpec,
  199. seed: params.ProtocolTransformSeed,
  200. }, nil
  201. }
  202. }