serverApi.go 9.9 KB

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