userAgent_test.go 7.0 KB

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