serverApi.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * Copyright (c) 2014, 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. "bytes"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "io/ioutil"
  26. "net/http"
  27. "strconv"
  28. )
  29. // Session is a utility struct which holds all of the data associated
  30. // with a Psiphon session. In addition to the established tunnel, this
  31. // includes the session ID (used for Psiphon API requests) and a http
  32. // client configured to make tunnelled Psiphon API requests.
  33. type Session struct {
  34. sessionId string
  35. config *Config
  36. tunnel *Tunnel
  37. pendingConns *PendingConns
  38. psiphonHttpsClient *http.Client
  39. }
  40. // NewSession makes tunnelled handshake and connected requests to the
  41. // Psiphon server and returns a Session struct, initialized with the
  42. // session ID, for use with subsequent Psiphon server API requests (e.g.,
  43. // periodic status requests).
  44. func NewSession(
  45. config *Config,
  46. tunnel *Tunnel,
  47. localHttpProxyAddress, sessionId string) (session *Session, err error) {
  48. pendingConns := new(PendingConns)
  49. psiphonHttpsClient, err := makePsiphonHttpsClient(tunnel, pendingConns, localHttpProxyAddress)
  50. if err != nil {
  51. return nil, ContextError(err)
  52. }
  53. session = &Session{
  54. sessionId: sessionId,
  55. config: config,
  56. tunnel: tunnel,
  57. pendingConns: pendingConns,
  58. psiphonHttpsClient: psiphonHttpsClient,
  59. }
  60. // Sending two seperate requests is a legacy from when the handshake was
  61. // performed before a tunnel was established and the connect was performed
  62. // within the established tunnel. Here we perform both requests back-to-back
  63. // inside the tunnel.
  64. err = session.doHandshakeRequest()
  65. if err != nil {
  66. return nil, ContextError(err)
  67. }
  68. err = session.doConnectedRequest()
  69. if err != nil {
  70. return nil, ContextError(err)
  71. }
  72. return session, nil
  73. }
  74. func (session *Session) DoStatusRequest() {
  75. // TODO: implement (required for page view stats)
  76. }
  77. // doHandshakeRequest performs the handshake API request. The handshake
  78. // returns upgrade info, newly discovered server entries -- which are
  79. // stored -- and sponsor info (home pages, stat regexes).
  80. func (session *Session) doHandshakeRequest() error {
  81. extraParams := make([]*ExtraParam, 0)
  82. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  83. if err != nil {
  84. return ContextError(err)
  85. }
  86. // Submit a list of known servers -- this will be used for
  87. // discovery statistics.
  88. for _, ipAddress := range serverEntryIpAddresses {
  89. extraParams = append(extraParams, &ExtraParam{"known_server", ipAddress})
  90. }
  91. url := session.buildRequestUrl("handshake", extraParams...)
  92. responseBody, err := session.doGetRequest(url)
  93. if err != nil {
  94. return ContextError(err)
  95. }
  96. // Skip legacy format lines and just parse the JSON config line
  97. configLinePrefix := []byte("Config: ")
  98. var configLine []byte
  99. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  100. if bytes.HasPrefix(line, configLinePrefix) {
  101. configLine = line[len(configLinePrefix):]
  102. break
  103. }
  104. }
  105. if len(configLine) == 0 {
  106. return ContextError(errors.New("no config line found"))
  107. }
  108. // Note:
  109. // - 'preemptive_reconnect_lifetime_milliseconds' is currently unused
  110. // - 'ssh_session_id' is ignored; client session ID is used instead
  111. var handshakeConfig struct {
  112. Homepages []string `json:"homepages"`
  113. UpgradeClientVersion string `json:"upgrade_client_version"`
  114. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  115. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  116. EncodedServerList []string `json:"encoded_server_list"`
  117. }
  118. err = json.Unmarshal(configLine, &handshakeConfig)
  119. if err != nil {
  120. return ContextError(err)
  121. }
  122. for _, encodedServerEntry := range handshakeConfig.EncodedServerList {
  123. serverEntry, err := DecodeServerEntry(encodedServerEntry)
  124. if err != nil {
  125. return ContextError(err)
  126. }
  127. err = StoreServerEntry(serverEntry, true)
  128. if err != nil {
  129. return ContextError(err)
  130. }
  131. }
  132. // TODO: formally communicate the sponsor and upgrade info to an
  133. // outer client via some control interface.
  134. for _, homepage := range handshakeConfig.Homepages {
  135. Notice(NOTICE_HOMEPAGE, homepage)
  136. }
  137. upgradeClientVersion, err := strconv.Atoi(handshakeConfig.UpgradeClientVersion)
  138. if err != nil {
  139. return ContextError(err)
  140. }
  141. if upgradeClientVersion > session.config.ClientVersion {
  142. Notice(NOTICE_UPGRADE, "%d", upgradeClientVersion)
  143. }
  144. for _, pageViewRegex := range handshakeConfig.PageViewRegexes {
  145. Notice(NOTICE_PAGE_VIEW_REGEX, "%s %s", pageViewRegex["regex"], pageViewRegex["replace"])
  146. }
  147. for _, httpsRequestRegex := range handshakeConfig.HttpsRequestRegexes {
  148. Notice(NOTICE_HTTPS_REGEX, "%s %s", httpsRequestRegex["regex"], httpsRequestRegex["replace"])
  149. }
  150. return nil
  151. }
  152. // doConnectedRequest performs the connected API request. This request is
  153. // used for statistics. The server returns a last_connected token for
  154. // the client to store and send next time it connects. This token is
  155. // a timestamp (using the server clock, and should be rounded to the
  156. // nearest hour) which is used to determine when a new connection is
  157. // a unique user for a time period.
  158. func (session *Session) doConnectedRequest() error {
  159. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  160. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  161. if err != nil {
  162. return ContextError(err)
  163. }
  164. if lastConnected == "" {
  165. lastConnected = "None"
  166. }
  167. url := session.buildRequestUrl(
  168. "connected",
  169. &ExtraParam{"session_id", session.sessionId},
  170. &ExtraParam{"last_connected", lastConnected})
  171. responseBody, err := session.doGetRequest(url)
  172. if err != nil {
  173. return ContextError(err)
  174. }
  175. var response struct {
  176. connectedTimestamp string `json:connected_timestamp`
  177. }
  178. err = json.Unmarshal(responseBody, &response)
  179. if err != nil {
  180. return ContextError(err)
  181. }
  182. err = SetKeyValue(DATA_STORE_LAST_CONNECTED_KEY, response.connectedTimestamp)
  183. if err != nil {
  184. return ContextError(err)
  185. }
  186. return nil
  187. }
  188. type ExtraParam struct{ name, value string }
  189. // buildRequestUrl makes a URL containing all the common parameters
  190. // that are included with Psiphon API requests. These common parameters
  191. // are used for statistics.
  192. func (session *Session) buildRequestUrl(path string, extraParams ...*ExtraParam) string {
  193. var requestUrl bytes.Buffer
  194. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  195. // e.g., don't do this: requestUrl.WriteString("https://")
  196. requestUrl.WriteString("http://")
  197. requestUrl.WriteString(session.tunnel.serverEntry.IpAddress)
  198. requestUrl.WriteString(":")
  199. requestUrl.WriteString(session.tunnel.serverEntry.WebServerPort)
  200. requestUrl.WriteString("/")
  201. requestUrl.WriteString(path)
  202. requestUrl.WriteString("?client_session_id=")
  203. requestUrl.WriteString(session.sessionId)
  204. requestUrl.WriteString("&server_secret=")
  205. requestUrl.WriteString(session.tunnel.serverEntry.WebServerSecret)
  206. requestUrl.WriteString("&propagation_channel_id=")
  207. requestUrl.WriteString(session.config.PropagationChannelId)
  208. requestUrl.WriteString("&sponsor_id=")
  209. requestUrl.WriteString(session.config.SponsorId)
  210. requestUrl.WriteString("&client_version=")
  211. requestUrl.WriteString(strconv.Itoa(session.config.ClientVersion))
  212. // TODO: client_tunnel_core_version
  213. requestUrl.WriteString("&relay_protocol=")
  214. requestUrl.WriteString(session.tunnel.protocol)
  215. requestUrl.WriteString("&client_platform=")
  216. requestUrl.WriteString(session.config.ClientPlatform)
  217. requestUrl.WriteString("&tunnel_whole_device=")
  218. requestUrl.WriteString(strconv.Itoa(session.config.TunnelWholeDevice))
  219. for _, extraParam := range extraParams {
  220. requestUrl.WriteString("&")
  221. requestUrl.WriteString(extraParam.name)
  222. requestUrl.WriteString("=")
  223. requestUrl.WriteString(extraParam.value)
  224. }
  225. return requestUrl.String()
  226. }
  227. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  228. func (session *Session) doGetRequest(requestUrl string) (responseBody []byte, err error) {
  229. response, err := session.psiphonHttpsClient.Get(requestUrl)
  230. if err != nil {
  231. // Trim this error since it may include long URLs
  232. return nil, ContextError(TrimError(err))
  233. }
  234. defer response.Body.Close()
  235. body, err := ioutil.ReadAll(response.Body)
  236. if err != nil {
  237. return nil, ContextError(err)
  238. }
  239. if response.StatusCode != http.StatusOK {
  240. return nil, ContextError(fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode))
  241. }
  242. return body, nil
  243. }
  244. // makeHttpsClient creates a Psiphon HTTPS client that uses the local http proxy to tunnel
  245. // requests and which validates the web server using the Psiphon server entry web server certificate.
  246. // This is not a general purpose HTTPS client.
  247. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  248. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  249. // handshake inside the explicit TLS session.
  250. func makePsiphonHttpsClient(
  251. tunnel *Tunnel,
  252. pendingConns *PendingConns,
  253. localHttpProxyAddress string) (httpsClient *http.Client, err error) {
  254. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  255. if err != nil {
  256. return nil, ContextError(err)
  257. }
  258. // Note: This use of readTimeout will tear down persistent HTTP connections, which is not the
  259. // intended purpose. The readTimeout is to abort NewSession when the Psiphon server responds to
  260. // handshake/connected requests but fails to deliver the response body (e.g., ResponseHeaderTimeout
  261. // is not sufficient to timeout this case).
  262. directDialer := NewDirectDialer(
  263. PSIPHON_API_SERVER_TIMEOUT,
  264. PSIPHON_API_SERVER_TIMEOUT,
  265. PSIPHON_API_SERVER_TIMEOUT,
  266. pendingConns)
  267. dialer := NewCustomTLSDialer(
  268. &CustomTLSConfig{
  269. Dial: directDialer,
  270. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  271. HttpProxyAddress: localHttpProxyAddress,
  272. SendServerName: false,
  273. VerifyLegacyCertificate: certificate,
  274. })
  275. transport := &http.Transport{
  276. Dial: dialer,
  277. ResponseHeaderTimeout: PSIPHON_API_SERVER_TIMEOUT,
  278. }
  279. return &http.Client{Transport: transport}, nil
  280. }