userAgent_test.go 6.9 KB

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