userAgent_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2017, 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 psiphon
  20. import (
  21. "context"
  22. "fmt"
  23. "io/ioutil"
  24. "net/http"
  25. "os"
  26. "sync"
  27. "testing"
  28. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server"
  31. "github.com/elazarl/goproxy"
  32. )
  33. // TODO: test that server receives and records correct user_agent value
  34. func TestOSSHUserAgent(t *testing.T) {
  35. attemptConnectionsWithUserAgent(t, "OSSH", true)
  36. }
  37. func TestUnfrontedMeekUserAgent(t *testing.T) {
  38. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-OSSH", false)
  39. }
  40. func TestUnfrontedMeekHTTPSUserAgent(t *testing.T) {
  41. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-HTTPS-OSSH", true)
  42. }
  43. var mockUserAgents = []string{"UserAgentA", "UserAgentB"}
  44. var userAgentCountsMutex sync.Mutex
  45. var userAgentCounts map[string]int
  46. var initUserAgentCounter sync.Once
  47. func initMockUserAgents() {
  48. values.SetUserAgentsSpec(values.NewPickOneSpec(mockUserAgents))
  49. }
  50. func resetUserAgentCounts() {
  51. userAgentCountsMutex.Lock()
  52. defer userAgentCountsMutex.Unlock()
  53. userAgentCounts = make(map[string]int)
  54. }
  55. func countHTTPUserAgent(headers http.Header, isCONNECT bool) {
  56. userAgentCountsMutex.Lock()
  57. defer userAgentCountsMutex.Unlock()
  58. if _, ok := headers["User-Agent"]; !ok {
  59. userAgentCounts["BLANK"]++
  60. } else if isCONNECT {
  61. userAgentCounts["CONNECT-"+headers.Get("User-Agent")]++
  62. } else {
  63. userAgentCounts[headers.Get("User-Agent")]++
  64. }
  65. }
  66. func countNoticeUserAgent(userAgent string) {
  67. userAgentCountsMutex.Lock()
  68. defer userAgentCountsMutex.Unlock()
  69. userAgentCounts["NOTICE-"+userAgent]++
  70. }
  71. func checkUserAgentCounts(t *testing.T, isCONNECT bool) {
  72. userAgentCountsMutex.Lock()
  73. defer userAgentCountsMutex.Unlock()
  74. for _, userAgent := range mockUserAgents {
  75. if isCONNECT {
  76. if userAgentCounts["CONNECT-"+userAgent] == 0 {
  77. t.Fatalf("unexpected CONNECT user agent count of 0: %+v", userAgentCounts)
  78. return
  79. }
  80. } else {
  81. if userAgentCounts[userAgent] == 0 {
  82. t.Fatalf("unexpected non-CONNECT user agent count of 0: %+v", userAgentCounts)
  83. return
  84. }
  85. }
  86. if userAgentCounts["NOTICE-"+userAgent] == 0 {
  87. t.Fatalf("unexpected NOTICE user agent count of 0: %+v", userAgentCounts)
  88. return
  89. }
  90. }
  91. if userAgentCounts["BLANK"] == 0 {
  92. t.Fatalf("unexpected BLANK user agent count of 0: %+v", userAgentCounts)
  93. return
  94. }
  95. // TODO: check proportions
  96. t.Logf("%+v", userAgentCounts)
  97. }
  98. func initUserAgentCounterUpstreamProxy() {
  99. initUserAgentCounter.Do(func() {
  100. go func() {
  101. proxy := goproxy.NewProxyHttpServer()
  102. proxy.OnRequest().DoFunc(
  103. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  104. countHTTPUserAgent(r.Header, false)
  105. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  106. })
  107. proxy.OnRequest().HandleConnectFunc(
  108. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  109. countHTTPUserAgent(ctx.Req.Header, true)
  110. return goproxy.RejectConnect, host
  111. })
  112. err := http.ListenAndServe("127.0.0.1:2163", proxy)
  113. if err != nil {
  114. fmt.Printf("upstream proxy failed: %s\n", err)
  115. }
  116. }()
  117. // TODO: more robust wait-until-listening
  118. time.Sleep(1 * time.Second)
  119. })
  120. }
  121. func attemptConnectionsWithUserAgent(
  122. t *testing.T, tunnelProtocol string, isCONNECT bool) {
  123. testDataDirName, err := ioutil.TempDir("", "psiphon-user-agent-test")
  124. if err != nil {
  125. t.Fatalf("TempDir failed: %s\n", err)
  126. }
  127. defer os.RemoveAll(testDataDirName)
  128. initMockUserAgents()
  129. initUserAgentCounterUpstreamProxy()
  130. resetUserAgentCounts()
  131. // create a server entry
  132. _, _, _, _, encodedServerEntry, err := server.GenerateConfig(
  133. &server.GenerateConfigParams{
  134. ServerIPAddress: "127.0.0.1",
  135. TunnelProtocolPorts: map[string]int{tunnelProtocol: 4000},
  136. })
  137. if err != nil {
  138. t.Fatalf("error generating server config: %s", err)
  139. }
  140. // attempt connections with client
  141. // Connections are made through a mock upstream proxy that
  142. // counts user agents. No server is running, and the upstream
  143. // proxy rejects connections after counting the user agent.
  144. // Note: calling LoadConfig ensures all *int config fields are initialized
  145. clientConfigJSON := `
  146. {
  147. "ClientPlatform" : "Windows",
  148. "ClientVersion" : "0",
  149. "SponsorId" : "0000000000000000",
  150. "PropagationChannelId" : "0000000000000000",
  151. "ConnectionWorkerPoolSize" : 1,
  152. "EstablishTunnelPausePeriodSeconds" : 1,
  153. "DisableRemoteServerListFetcher" : true,
  154. "TransformHostNameProbability" : 0.0,
  155. "UpstreamProxyUrl" : "http://127.0.0.1:2163",
  156. "UpstreamProxyAllowAllServerEntrySources" : true
  157. }`
  158. clientConfig, err := LoadConfig([]byte(clientConfigJSON))
  159. if err != nil {
  160. t.Fatalf("error processing configuration file: %s", err)
  161. }
  162. clientConfig.TargetServerEntry = string(encodedServerEntry)
  163. clientConfig.TunnelProtocol = tunnelProtocol
  164. clientConfig.DataRootDirectory = testDataDirName
  165. err = clientConfig.Commit(false)
  166. if err != nil {
  167. t.Fatalf("error committing configuration file: %s", err)
  168. }
  169. err = OpenDataStore(clientConfig)
  170. if err != nil {
  171. t.Fatalf("error initializing client datastore: %s", err)
  172. }
  173. defer CloseDataStore()
  174. err = SetNoticeWriter(NewNoticeReceiver(
  175. func(notice []byte) {
  176. noticeType, payload, err := GetNotice(notice)
  177. if err != nil {
  178. return
  179. }
  180. if noticeType == "ConnectingServer" {
  181. userAgent, ok := payload["userAgent"]
  182. if ok {
  183. countNoticeUserAgent(userAgent.(string))
  184. }
  185. }
  186. }))
  187. if err != nil {
  188. t.Fatalf("error setting notice writer: %s", err)
  189. }
  190. defer ResetNoticeWriter()
  191. controller, err := NewController(clientConfig)
  192. if err != nil {
  193. t.Fatalf("error creating client controller: %s", err)
  194. }
  195. ctx, cancelFunc := context.WithCancel(context.Background())
  196. controllerWaitGroup := new(sync.WaitGroup)
  197. controllerWaitGroup.Add(1)
  198. go func() {
  199. defer controllerWaitGroup.Done()
  200. controller.Run(ctx)
  201. }()
  202. // repeat attempts for long enough to select each user agent
  203. time.Sleep(30 * time.Second)
  204. cancelFunc()
  205. controllerWaitGroup.Wait()
  206. checkUserAgentCounts(t, isCONNECT)
  207. }