transferstats_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 transferstats
  20. import (
  21. "errors"
  22. "fmt"
  23. "net"
  24. "net/http"
  25. "regexp"
  26. "testing"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. mapset "github.com/deckarep/golang-set"
  29. "github.com/stretchr/testify/suite"
  30. )
  31. const (
  32. _SERVER_ID = "myserverid"
  33. )
  34. var nextServerID = 0
  35. type StatsTestSuite struct {
  36. suite.Suite
  37. serverID string
  38. httpClient *http.Client
  39. }
  40. func TestStatsTestSuite(t *testing.T) {
  41. suite.Run(t, new(StatsTestSuite))
  42. }
  43. func (suite *StatsTestSuite) SetupTest() {
  44. suite.serverID = fmt.Sprintf("%s-%d", _SERVER_ID, nextServerID)
  45. nextServerID++
  46. suite.httpClient = &http.Client{
  47. Transport: &http.Transport{
  48. Dial: makeStatsDialer(suite.serverID, &Regexps{}),
  49. },
  50. }
  51. }
  52. func (suite *StatsTestSuite) TearDownTest() {
  53. suite.httpClient = nil
  54. }
  55. func makeStatsDialer(serverID string, regexps *Regexps) func(network, addr string) (conn net.Conn, err error) {
  56. return func(network, addr string) (conn net.Conn, err error) {
  57. var subConn net.Conn
  58. switch network {
  59. case "tcp", "tcp4", "tcp6":
  60. tcpAddr, err := net.ResolveTCPAddr(network, addr)
  61. if err != nil {
  62. return nil, err
  63. }
  64. subConn, err = net.DialTCP(network, nil, tcpAddr)
  65. if err != nil {
  66. return nil, err
  67. }
  68. default:
  69. err = errors.New("using an unsupported testing network type")
  70. return
  71. }
  72. conn = NewConn(subConn, serverID, regexps)
  73. err = nil
  74. return
  75. }
  76. }
  77. func (suite *StatsTestSuite) Test_StatsConn() {
  78. resp, err := suite.httpClient.Get("http://psiphon.ca/index.html")
  79. suite.Nil(err, "basic HTTP requests should succeed")
  80. resp.Body.Close()
  81. resp, err = suite.httpClient.Get("https://psiphon.ca/index.html")
  82. suite.Nil(err, "basic HTTPS requests should succeed")
  83. resp.Body.Close()
  84. }
  85. func (suite *StatsTestSuite) Test_TakeOutStatsForServer() {
  86. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  87. payload := TakeOutStatsForServer(suite.serverID)
  88. suite.Equal(payload, zeroPayload, "should get zero stats before any traffic")
  89. resp, err := suite.httpClient.Get("https://psiphon.ca/index.html")
  90. suite.Nil(err, "need successful http to proceed with tests")
  91. resp.Body.Close()
  92. payload = TakeOutStatsForServer(suite.serverID)
  93. suite.NotNil(payload, "should receive valid payload for valid server ID")
  94. // After we retrieve the stats for a server, they should be cleared out of the tracked stats
  95. payload = TakeOutStatsForServer(suite.serverID)
  96. suite.Equal(payload, zeroPayload, "after retrieving stats for a server, there should be zero stats (until more data goes through)")
  97. }
  98. func (suite *StatsTestSuite) Test_PutBackStatsForServer() {
  99. // Set a regexp for the httpClient to ensure it at least records "(OTHER)" domain bytes;
  100. // The regex is set to "nomatch.com" so that it _will_ exercise the "(OTHER)" case.
  101. regexp, _ := regexp.Compile(`^[a-z0-9\.]*\.(nomatch\.com)$`)
  102. replace := "$1"
  103. regexps := &Regexps{regexpReplace{regexp: regexp, replace: replace}}
  104. statsDialer := makeStatsDialer(suite.serverID, regexps)
  105. // Track all conns underlying the HTTP client, to facilitate closing them
  106. // all and ensuring no further traffic after that point. See below.
  107. trackConns := common.NewConns[net.Conn]()
  108. trackConnDialer := func(network, addr string) (net.Conn, error) {
  109. conn, err := statsDialer(network, addr)
  110. if err == nil {
  111. trackConns.Add(conn)
  112. }
  113. return conn, err
  114. }
  115. suite.httpClient = &http.Client{
  116. Transport: &http.Transport{
  117. Dial: trackConnDialer,
  118. },
  119. }
  120. resp, err := suite.httpClient.Get("https://psiphon.ca/index.html")
  121. suite.Nil(err, "need successful http to proceed with tests")
  122. resp.Body.Close()
  123. // Close all conns to ensure transfer stats recording is stopped.
  124. // Otherwise, any additional traffic that occurs between the take-out and
  125. // put-back may invalidate the assertion that the 2nd take-out is
  126. // identical.
  127. trackConns.CloseAll()
  128. payloadToPutBack := TakeOutStatsForServer(suite.serverID)
  129. suite.NotNil(payloadToPutBack, "should receive valid payload for valid server ID")
  130. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  131. payload := TakeOutStatsForServer(suite.serverID)
  132. suite.Equal(payload, zeroPayload, "should be zero stats after getting them")
  133. PutBackStatsForServer(suite.serverID, payloadToPutBack)
  134. payload = TakeOutStatsForServer(suite.serverID)
  135. suite.NotEqual(payload, zeroPayload, "stats should be re-added after putting back")
  136. suite.Equal(payload, payloadToPutBack, "stats should be the same as after the first retrieval")
  137. }
  138. func (suite *StatsTestSuite) Test_NoRegexes() {
  139. // Set no regexps for the httpClient
  140. suite.httpClient = &http.Client{
  141. Transport: &http.Transport{
  142. Dial: makeStatsDialer(suite.serverID, &Regexps{}),
  143. },
  144. }
  145. // Ensure there are no stats before making the no-regex request
  146. _ = TakeOutStatsForServer(suite.serverID)
  147. resp, err := suite.httpClient.Get("http://psiphon.ca/index.html")
  148. suite.Nil(err, "need successful http to proceed with tests")
  149. resp.Body.Close()
  150. zeroPayload := &AccumulatedStats{hostnameToStats: make(map[string]*hostStats)}
  151. payload := TakeOutStatsForServer(suite.serverID)
  152. suite.Equal(payload, zeroPayload, "should be zero stats after getting them")
  153. }
  154. func (suite *StatsTestSuite) Test_MakeRegexps() {
  155. hostnameRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  156. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  157. hostnameRegexes[0]["replace"] = "$1"
  158. hostnameRegexes[1]["regex"] = `^.*example\.org$`
  159. hostnameRegexes[1]["replace"] = "replacement"
  160. regexps, notices := MakeRegexps(hostnameRegexes)
  161. suite.NotNil(regexps, "should return a valid object")
  162. suite.Len(*regexps, 2, "should only have processed hostnameRegexes")
  163. suite.Len(notices, 0, "should return no notices")
  164. //
  165. // Test some bad regexps
  166. //
  167. hostnameRegexes[0]["regex"] = ""
  168. hostnameRegexes[0]["replace"] = "$1"
  169. regexps, notices = MakeRegexps(hostnameRegexes)
  170. suite.NotNil(regexps, "should return a valid object")
  171. suite.Len(*regexps, 1, "should have discarded one regexp")
  172. suite.Len(notices, 1, "should have returned one notice")
  173. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com)$`
  174. hostnameRegexes[0]["replace"] = ""
  175. regexps, notices = MakeRegexps(hostnameRegexes)
  176. suite.NotNil(regexps, "should return a valid object")
  177. suite.Len(*regexps, 1, "should have discarded one regexp")
  178. suite.Len(notices, 1, "should have returned one notice")
  179. hostnameRegexes[0]["regex"] = `^[a-z0-9\.]*\.(example\.com$` // missing closing paren
  180. hostnameRegexes[0]["replace"] = "$1"
  181. regexps, notices = MakeRegexps(hostnameRegexes)
  182. suite.NotNil(regexps, "should return a valid object")
  183. suite.Len(*regexps, 1, "should have discarded one regexp")
  184. suite.Len(notices, 1, "should have returned one notice")
  185. }
  186. func (suite *StatsTestSuite) Test_Regex() {
  187. // We'll make a new client with actual regexps.
  188. hostnameRegexes := []map[string]string{make(map[string]string), make(map[string]string)}
  189. hostnameRegexes[0]["regex"] = `^[w0-9\.]*\.(psiphon\.ca)$`
  190. hostnameRegexes[0]["replace"] = "$1"
  191. hostnameRegexes[1]["regex"] = `^psiphon\.ca$`
  192. hostnameRegexes[1]["replace"] = "replacement"
  193. regexps, _ := MakeRegexps(hostnameRegexes)
  194. suite.httpClient = &http.Client{
  195. Transport: &http.Transport{
  196. Dial: makeStatsDialer(suite.serverID, regexps),
  197. },
  198. }
  199. // Using both HTTP and HTTPS will help us to exercise both methods of hostname parsing
  200. for _, scheme := range []string{"http", "https"} {
  201. // Won't match regex
  202. url := fmt.Sprintf("%s://blog.psiphon.ca/index.html", scheme)
  203. resp, err := suite.httpClient.Get(url)
  204. suite.Nil(err)
  205. resp.Body.Close()
  206. // Will match the first regex
  207. url = fmt.Sprintf("%s://www.psiphon.ca/index.html", scheme)
  208. resp, err = suite.httpClient.Get(url)
  209. suite.Nil(err)
  210. resp.Body.Close()
  211. // Will match the second regex
  212. url = fmt.Sprintf("%s://psiphon.ca/index.html", scheme)
  213. resp, err = suite.httpClient.Get(url)
  214. suite.Nil(err)
  215. resp.Body.Close()
  216. payload := TakeOutStatsForServer(suite.serverID)
  217. suite.NotNil(payload, "should get stats because we made HTTP reqs; %s", scheme)
  218. expectedHostnames := mapset.NewSet()
  219. expectedHostnames.Add("(OTHER)")
  220. expectedHostnames.Add("psiphon.ca")
  221. expectedHostnames.Add("replacement")
  222. hostnames := make([]interface{}, 0)
  223. for hostname := range payload.hostnameToStats {
  224. hostnames = append(hostnames, hostname)
  225. }
  226. actualHostnames := mapset.NewSetFromSlice(hostnames)
  227. suite.Equal(expectedHostnames, actualHostnames, "post-regex hostnames should be processed as expected: %s", scheme)
  228. }
  229. }
  230. func (suite *StatsTestSuite) Test_getTLSHostname() {
  231. // TODO: Create a more robust/antagonistic set of negative tests.
  232. // We can write raw TCP to simulate any arbitrary degree of "almost looks
  233. // like a TLS handshake".
  234. // These tests are basically just checking for crashes.
  235. //
  236. // An easier way to construct valid client-hello messages (but not malicious ones)
  237. // would be to use the clientHelloMsg struct and marshal function from:
  238. // https://github.com/golang/go/blob/master/src/crypto/tls/handshake_messages.go
  239. // TODO: Talk to a local TCP server instead of depending on a remote site.
  240. dialer := makeStatsDialer(suite.serverID, nil)
  241. // Data too short
  242. conn, err := dialer("tcp", "psiphon.ca:80")
  243. suite.Nil(err)
  244. b := []byte(`my bytes`)
  245. n, err := conn.Write(b)
  246. suite.Nil(err)
  247. suite.Equal(len(b), n)
  248. err = conn.Close()
  249. suite.Nil(err)
  250. // Data long enough, but wrong first byte
  251. conn, err = dialer("tcp", "psiphon.ca:80")
  252. suite.Nil(err)
  253. b = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  254. n, err = conn.Write(b)
  255. suite.Nil(err)
  256. suite.Equal(len(b), n)
  257. err = conn.Close()
  258. suite.Nil(err)
  259. // Data long enough, correct first byte
  260. conn, err = dialer("tcp", "psiphon.ca:80")
  261. suite.Nil(err)
  262. b = []byte{22, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  263. n, err = conn.Write(b)
  264. suite.Nil(err)
  265. suite.Equal(len(b), n)
  266. err = conn.Close()
  267. suite.Nil(err)
  268. // Correct until after SSL version
  269. conn, err = dialer("tcp", "psiphon.ca:80")
  270. suite.Nil(err)
  271. b = []byte{22, 3, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  272. n, err = conn.Write(b)
  273. suite.Nil(err)
  274. suite.Equal(len(b), n)
  275. err = conn.Close()
  276. suite.Nil(err)
  277. plaintextLen := byte(70)
  278. // Correct until after plaintext length
  279. conn, err = dialer("tcp", "psiphon.ca:80")
  280. suite.Nil(err)
  281. b = []byte{22, 3, 1, 0, plaintextLen, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  282. n, err = conn.Write(b)
  283. suite.Nil(err)
  284. suite.Equal(len(b), n)
  285. err = conn.Close()
  286. suite.Nil(err)
  287. // Correct until after handshake type
  288. conn, err = dialer("tcp", "psiphon.ca:80")
  289. suite.Nil(err)
  290. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  291. n, err = conn.Write(b)
  292. suite.Nil(err)
  293. suite.Equal(len(b), n)
  294. err = conn.Close()
  295. suite.Nil(err)
  296. // Correct until after handshake length
  297. conn, err = dialer("tcp", "psiphon.ca:80")
  298. suite.Nil(err)
  299. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 0, plaintextLen - 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  300. n, err = conn.Write(b)
  301. suite.Nil(err)
  302. suite.Equal(len(b), n)
  303. err = conn.Close()
  304. suite.Nil(err)
  305. // Correct until after protocol version
  306. conn, err = dialer("tcp", "psiphon.ca:80")
  307. suite.Nil(err)
  308. b = []byte{22, 3, 1, 0, plaintextLen, 1, 0, 0, plaintextLen - 4, 3, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  309. n, err = conn.Write(b)
  310. suite.Nil(err)
  311. suite.Equal(len(b), n)
  312. err = conn.Close()
  313. suite.Nil(err)
  314. }