serverApi.go 10.0 KB

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