serverApi.go 11 KB

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