userAgent_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. "fmt"
  22. "net/http"
  23. "sync"
  24. "testing"
  25. "time"
  26. "github.com/Psiphon-Inc/goproxy"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server"
  29. )
  30. // TODO: test that emitted NoticeConnectedTunnelDialStats reports correct userAgent value
  31. // TODO: test that server receives and records correct user_agent value
  32. func TestOSSHUserAgent(t *testing.T) {
  33. attemptConnectionsWithUserAgent(t, "OSSH", true)
  34. }
  35. func TestUnfrontedMeekUserAgent(t *testing.T) {
  36. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-OSSH", false)
  37. }
  38. func TestUnfrontedMeekHTTPSUserAgent(t *testing.T) {
  39. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-HTTPS-OSSH", true)
  40. }
  41. var mockUserAgents = []string{"UserAgentA", "UserAgentB"}
  42. var userAgentCountsMutex sync.Mutex
  43. var userAgentCounts map[string]int
  44. var initUserAgentCounter sync.Once
  45. func pickUserAgent() string {
  46. index, _ := common.MakeSecureRandomInt(len(mockUserAgents))
  47. return mockUserAgents[index]
  48. }
  49. func initMockUserAgentPicker() {
  50. common.RegisterUserAgentPicker(pickUserAgent)
  51. }
  52. func resetUserAgentCounts() {
  53. userAgentCountsMutex.Lock()
  54. defer userAgentCountsMutex.Unlock()
  55. userAgentCounts = make(map[string]int)
  56. }
  57. func countUserAgent(headers http.Header, isCONNECT bool) {
  58. userAgentCountsMutex.Lock()
  59. defer userAgentCountsMutex.Unlock()
  60. if _, ok := headers["User-Agent"]; !ok {
  61. userAgentCounts["BLANK"]++
  62. } else if isCONNECT {
  63. userAgentCounts["CONNECT-"+headers.Get("User-Agent")]++
  64. } else {
  65. userAgentCounts[headers.Get("User-Agent")]++
  66. }
  67. }
  68. func checkUserAgentCounts(t *testing.T, isCONNECT bool) {
  69. userAgentCountsMutex.Lock()
  70. defer userAgentCountsMutex.Unlock()
  71. for _, userAgent := range mockUserAgents {
  72. if isCONNECT {
  73. if userAgentCounts["CONNECT-"+userAgent] == 0 {
  74. t.Fatalf("unexpected CONNECT user agent count of 0: %+v", userAgentCounts)
  75. return
  76. }
  77. } else {
  78. if userAgentCounts[userAgent] == 0 {
  79. t.Fatalf("unexpected non-CONNECT user agent count of 0: %+v", userAgentCounts)
  80. return
  81. }
  82. }
  83. }
  84. if userAgentCounts["BLANK"] == 0 {
  85. t.Fatalf("unexpected BLANK user agent count of 0: %+v", userAgentCounts)
  86. return
  87. }
  88. // TODO: check proportions
  89. t.Logf("%+v", userAgentCounts)
  90. }
  91. func initUserAgentCounterUpstreamProxy() {
  92. initUserAgentCounter.Do(func() {
  93. go func() {
  94. proxy := goproxy.NewProxyHttpServer()
  95. proxy.OnRequest().DoFunc(
  96. func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
  97. countUserAgent(r.Header, false)
  98. return nil, goproxy.NewResponse(r, goproxy.ContentTypeText, http.StatusUnauthorized, "")
  99. })
  100. proxy.OnRequest().HandleConnectFunc(
  101. func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
  102. countUserAgent(ctx.Req.Header, true)
  103. return goproxy.RejectConnect, host
  104. })
  105. err := http.ListenAndServe("127.0.0.1:2163", proxy)
  106. if err != nil {
  107. fmt.Printf("upstream proxy failed: %s\n", err)
  108. }
  109. }()
  110. // TODO: more robust wait-until-listening
  111. time.Sleep(1 * time.Second)
  112. })
  113. }
  114. func attemptConnectionsWithUserAgent(
  115. t *testing.T, tunnelProtocol string, isCONNECT bool) {
  116. initMockUserAgentPicker()
  117. initUserAgentCounterUpstreamProxy()
  118. resetUserAgentCounts()
  119. // create a server entry
  120. var err error
  121. serverIPaddress := ""
  122. for _, interfaceName := range []string{"eth0", "en0"} {
  123. serverIPaddress, err = common.GetInterfaceIPAddress(interfaceName)
  124. if err == nil {
  125. break
  126. }
  127. }
  128. if err != nil {
  129. t.Fatalf("error getting server IP address: %s", err)
  130. }
  131. _, _, encodedServerEntry, err := server.GenerateConfig(
  132. &server.GenerateConfigParams{
  133. ServerIPAddress: serverIPaddress,
  134. EnableSSHAPIRequests: true,
  135. WebServerPort: 8000,
  136. TunnelProtocolPorts: map[string]int{tunnelProtocol: 4000},
  137. })
  138. if err != nil {
  139. t.Fatalf("error generating server config: %s", err)
  140. }
  141. // attempt connections with client
  142. // Connections are made through a mock upstream proxy that
  143. // counts user agents. No server is running, and the upstream
  144. // proxy rejects connections after counting the user agent.
  145. // Note: calling LoadConfig ensures all *int config fields are initialized
  146. clientConfigJSON := `
  147. {
  148. "ClientPlatform" : "Windows",
  149. "ClientVersion" : "0",
  150. "SponsorId" : "0",
  151. "PropagationChannelId" : "0",
  152. "ConnectionPoolSize" : 1,
  153. "EstablishTunnelPausePeriodSeconds" : 1,
  154. "DisableRemoteServerListFetcher" : true,
  155. "TransformHostNames" : "never",
  156. "UpstreamProxyUrl" : "http://127.0.0.1:2163"
  157. }`
  158. clientConfig, _ := LoadConfig([]byte(clientConfigJSON))
  159. clientConfig.TargetServerEntry = string(encodedServerEntry)
  160. clientConfig.TunnelProtocol = tunnelProtocol
  161. clientConfig.DataStoreDirectory = testDataDirName
  162. err = InitDataStore(clientConfig)
  163. if err != nil {
  164. t.Fatalf("error initializing client datastore: %s", err)
  165. }
  166. SetNoticeOutput(NewNoticeReceiver(
  167. func(notice []byte) {
  168. // (inspect notices here)
  169. }))
  170. controller, err := NewController(clientConfig)
  171. if err != nil {
  172. t.Fatalf("error creating client controller: %s", err)
  173. }
  174. controllerShutdownBroadcast := make(chan struct{})
  175. controllerWaitGroup := new(sync.WaitGroup)
  176. controllerWaitGroup.Add(1)
  177. go func() {
  178. defer controllerWaitGroup.Done()
  179. controller.Run(controllerShutdownBroadcast)
  180. }()
  181. // repeat attempts for long enough to select each user agent
  182. time.Sleep(20 * time.Second)
  183. close(controllerShutdownBroadcast)
  184. controllerWaitGroup.Wait()
  185. checkUserAgentCounts(t, isCONNECT)
  186. }