sessionID_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "context"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. "os"
  26. "path/filepath"
  27. "strings"
  28. "sync"
  29. "testing"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. )
  35. func TestDuplicateSessionID(t *testing.T) {
  36. testDataDirName, err := ioutil.TempDir("", "psiphond-duplicate-session-id-test")
  37. if err != nil {
  38. t.Fatalf("TempDir failed: %s", err)
  39. }
  40. defer os.RemoveAll(testDataDirName)
  41. psiphon.SetEmitDiagnosticNotices(true, true)
  42. // Configure server
  43. generateConfigParams := &GenerateConfigParams{
  44. ServerIPAddress: "127.0.0.1",
  45. EnableSSHAPIRequests: true,
  46. WebServerPort: 8000,
  47. TunnelProtocolPorts: map[string]int{"OSSH": 4000},
  48. }
  49. serverConfigJSON, _, _, _, encodedServerEntry, err := GenerateConfig(generateConfigParams)
  50. if err != nil {
  51. t.Fatalf("error generating server config: %s", err)
  52. }
  53. var serverConfig map[string]interface{}
  54. json.Unmarshal(serverConfigJSON, &serverConfig)
  55. serverConfig["LogFilename"] = filepath.Join(testDataDirName, "psiphond.log")
  56. serverConfig["LogLevel"] = "debug"
  57. serverConfigJSON, _ = json.Marshal(serverConfig)
  58. numConcurrentClients := 50
  59. stoppingEvent := "stopping existing client with duplicate session ID"
  60. abortingEvent := "aborting new client with duplicate session ID"
  61. // Sufficiently buffer channel so log callback handler doesn't cause server
  62. // operations to block while handling concurrent clients.
  63. duplicateSessionIDEvents := make(chan string, numConcurrentClients)
  64. setLogCallback(func(log []byte) {
  65. strLog := string(log)
  66. var event string
  67. if strings.Contains(strLog, stoppingEvent) {
  68. event = stoppingEvent
  69. } else if strings.Contains(strLog, abortingEvent) {
  70. event = abortingEvent
  71. }
  72. if event != "" {
  73. select {
  74. case duplicateSessionIDEvents <- event:
  75. default:
  76. }
  77. }
  78. })
  79. // Run server
  80. serverWaitGroup := new(sync.WaitGroup)
  81. serverWaitGroup.Add(1)
  82. go func() {
  83. defer serverWaitGroup.Done()
  84. err := RunServices(serverConfigJSON)
  85. if err != nil {
  86. t.Errorf("error running server: %s", err)
  87. }
  88. }()
  89. defer func() {
  90. p, _ := os.FindProcess(os.Getpid())
  91. p.Signal(os.Interrupt)
  92. serverWaitGroup.Wait()
  93. }()
  94. // TODO: monitor logs for more robust wait-until-loaded.
  95. time.Sleep(1 * time.Second)
  96. // Initialize tunnel clients. Bypassing Controller and using Tunnel directly
  97. // to permit multiple concurrent clients.
  98. //
  99. // Limitation: all tunnels still use one singleton datastore and notice
  100. // handler.
  101. psiphon.SetNoticeWriter(ioutil.Discard)
  102. clientConfigJSONTemplate := `
  103. {
  104. "DataRootDirectory" : "%s",
  105. "SponsorId" : "0",
  106. "PropagationChannelId" : "0",
  107. "SessionID" : "00000000000000000000000000000000"
  108. }`
  109. clientConfigJSON := fmt.Sprintf(
  110. clientConfigJSONTemplate,
  111. testDataDirName)
  112. clientConfig, err := psiphon.LoadConfig([]byte(clientConfigJSON))
  113. if err != nil {
  114. t.Fatalf("LoadConfig failed: %s", err)
  115. }
  116. err = clientConfig.Commit(false)
  117. if err != nil {
  118. t.Fatalf("Commit failed: %s", err)
  119. }
  120. err = psiphon.OpenDataStore(clientConfig)
  121. if err != nil {
  122. t.Fatalf("OpenDataStore failed: %s", err)
  123. }
  124. defer psiphon.CloseDataStore()
  125. serverEntry, err := protocol.DecodeServerEntry(
  126. string(encodedServerEntry),
  127. common.GetCurrentTimestamp(),
  128. protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  129. if err != nil {
  130. t.Fatalf("DecodeServerEntry failed: %s", err)
  131. }
  132. dialTunnel := func(ctx context.Context) *psiphon.Tunnel {
  133. dialParams, err := psiphon.MakeDialParameters(
  134. clientConfig,
  135. func(_ *protocol.ServerEntry, _ string) bool { return false },
  136. func(_ *protocol.ServerEntry) (string, bool) { return "OSSH", true },
  137. serverEntry,
  138. false,
  139. 0,
  140. 0)
  141. if err != nil {
  142. t.Fatalf("MakeDialParameters failed: %s", err)
  143. }
  144. tunnel, err := psiphon.ConnectTunnel(
  145. ctx,
  146. clientConfig,
  147. time.Now(),
  148. dialParams)
  149. if err != nil {
  150. t.Fatalf("ConnectTunnel failed: %s", err)
  151. }
  152. return tunnel
  153. }
  154. handshakeTunnel := func(tunnel *psiphon.Tunnel, expectSuccess bool) {
  155. _, err = psiphon.NewServerContext(tunnel)
  156. if expectSuccess && err != nil || (!expectSuccess && err == nil) {
  157. t.Fatalf("Unexpected handshake result: %s", err)
  158. }
  159. }
  160. ctx, cancelFunc := context.WithCancel(context.Background())
  161. defer cancelFunc()
  162. // Test: normal case
  163. //
  164. // First tunnel, t1, fully establishes and then is superceded by new tunnel, t2.
  165. t1 := dialTunnel(ctx)
  166. handshakeTunnel(t1, true)
  167. t2 := dialTunnel(ctx)
  168. expectEvent := <-duplicateSessionIDEvents
  169. if expectEvent != stoppingEvent {
  170. t.Fatalf("Unexpected duplicate session ID event")
  171. }
  172. handshakeTunnel(t2, true)
  173. t1.Close(true)
  174. t2.Close(true)
  175. // Test: simultaneous/interleaved case
  176. //
  177. // First tunnel connects but then tries to handshake after second tunnel has
  178. // connected.
  179. t1 = dialTunnel(ctx)
  180. // TODO: await log confirmation that t1 completed registerEstablishedClient?
  181. // Otherwise, there's some small chance that t2 is the "first" tunnel and the
  182. // test could fail (false negative).
  183. t2 = dialTunnel(ctx)
  184. expectEvent = <-duplicateSessionIDEvents
  185. if expectEvent != stoppingEvent {
  186. t.Fatalf("Unexpected duplicate session ID event")
  187. }
  188. handshakeTunnel(t1, false)
  189. handshakeTunnel(t2, true)
  190. t1.Close(true)
  191. t2.Close(true)
  192. // Test: 50 concurrent clients, all with the same session ID.
  193. //
  194. // This should be enough concurrent clients to trigger both the "stopping"
  195. // and "aborting" duplicate session ID cases.
  196. tunnels := make([]*psiphon.Tunnel, numConcurrentClients)
  197. waitGroup := new(sync.WaitGroup)
  198. for i := 0; i < numConcurrentClients; i++ {
  199. waitGroup.Add(1)
  200. go func(i int) {
  201. defer waitGroup.Done()
  202. tunnels[i] = dialTunnel(ctx)
  203. }(i)
  204. }
  205. waitGroup.Wait()
  206. for _, t := range tunnels {
  207. if t == nil {
  208. continue
  209. }
  210. t.Close(true)
  211. }
  212. receivedEvents := make(map[string]int)
  213. for i := 0; i < numConcurrentClients-1; i++ {
  214. receivedEvents[<-duplicateSessionIDEvents] += 1
  215. }
  216. if receivedEvents[stoppingEvent] < 1 {
  217. t.Fatalf("No stopping events received")
  218. }
  219. if receivedEvents[abortingEvent] < 1 {
  220. t.Fatalf("No aborting events received")
  221. }
  222. }