userAgent_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 server receives and records correct user_agent value
  31. func TestOSSHUserAgent(t *testing.T) {
  32. attemptConnectionsWithUserAgent(t, "OSSH", true)
  33. }
  34. func TestUnfrontedMeekUserAgent(t *testing.T) {
  35. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-OSSH", false)
  36. }
  37. func TestUnfrontedMeekHTTPSUserAgent(t *testing.T) {
  38. attemptConnectionsWithUserAgent(t, "UNFRONTED-MEEK-HTTPS-OSSH", true)
  39. }
  40. var mockUserAgents = []string{"UserAgentA", "UserAgentB"}
  41. var userAgentCountsMutex sync.Mutex
  42. var userAgentCounts map[string]int
  43. var initUserAgentCounter sync.Once
  44. func pickUserAgent() string {
  45. index, _ := common.MakeSecureRandomInt(len(mockUserAgents))
  46. return mockUserAgents[index]
  47. }
  48. func initMockUserAgentPicker() {
  49. common.RegisterUserAgentPicker(pickUserAgent)
  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. initMockUserAgentPicker()
  125. initUserAgentCounterUpstreamProxy()
  126. resetUserAgentCounts()
  127. // create a server entry
  128. var err error
  129. serverIPaddress := ""
  130. for _, interfaceName := range []string{"eth0", "en0"} {
  131. serverIPaddress, err = common.GetInterfaceIPAddress(interfaceName)
  132. if err == nil {
  133. break
  134. }
  135. }
  136. if err != nil {
  137. t.Fatalf("error getting server IP address: %s", err)
  138. }
  139. _, _, encodedServerEntry, err := server.GenerateConfig(
  140. &server.GenerateConfigParams{
  141. ServerIPAddress: serverIPaddress,
  142. EnableSSHAPIRequests: true,
  143. WebServerPort: 8000,
  144. TunnelProtocolPorts: map[string]int{tunnelProtocol: 4000},
  145. })
  146. if err != nil {
  147. t.Fatalf("error generating server config: %s", err)
  148. }
  149. // attempt connections with client
  150. // Connections are made through a mock upstream proxy that
  151. // counts user agents. No server is running, and the upstream
  152. // proxy rejects connections after counting the user agent.
  153. // Note: calling LoadConfig ensures all *int config fields are initialized
  154. clientConfigJSON := `
  155. {
  156. "ClientPlatform" : "Windows",
  157. "ClientVersion" : "0",
  158. "SponsorId" : "0",
  159. "PropagationChannelId" : "0",
  160. "ConnectionPoolSize" : 1,
  161. "EstablishTunnelPausePeriodSeconds" : 1,
  162. "DisableRemoteServerListFetcher" : true,
  163. "TransformHostNames" : "never",
  164. "UpstreamProxyUrl" : "http://127.0.0.1:2163"
  165. }`
  166. clientConfig, _ := LoadConfig([]byte(clientConfigJSON))
  167. clientConfig.TargetServerEntry = string(encodedServerEntry)
  168. clientConfig.TunnelProtocol = tunnelProtocol
  169. clientConfig.DataStoreDirectory = testDataDirName
  170. err = InitDataStore(clientConfig)
  171. if err != nil {
  172. t.Fatalf("error initializing client datastore: %s", err)
  173. }
  174. SetNoticeOutput(NewNoticeReceiver(
  175. func(notice []byte) {
  176. noticeType, payload, err := GetNotice(notice)
  177. if err != nil {
  178. return
  179. }
  180. if noticeType == "ConnectingServer" {
  181. selectedUserAgent := payload["selectedUserAgent"].(bool)
  182. userAgent := payload["userAgent"].(string)
  183. if selectedUserAgent {
  184. countNoticeUserAgent(userAgent)
  185. }
  186. }
  187. }))
  188. controller, err := NewController(clientConfig)
  189. if err != nil {
  190. t.Fatalf("error creating client controller: %s", err)
  191. }
  192. controllerShutdownBroadcast := make(chan struct{})
  193. controllerWaitGroup := new(sync.WaitGroup)
  194. controllerWaitGroup.Add(1)
  195. go func() {
  196. defer controllerWaitGroup.Done()
  197. controller.Run(controllerShutdownBroadcast)
  198. }()
  199. // repeat attempts for long enough to select each user agent
  200. time.Sleep(20 * time.Second)
  201. close(controllerShutdownBroadcast)
  202. controllerWaitGroup.Wait()
  203. checkUserAgentCounts(t, isCONNECT)
  204. }