userAgent_test.go 7.0 KB

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