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