serverApi.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. // TODO: remove regex notices -- regexes will be used internally
  138. /*
  139. for _, pageViewRegex := range handshakeConfig.PageViewRegexes {
  140. Notice(NOTICE_PAGE_VIEW_REGEX, "%s %s", pageViewRegex["regex"], pageViewRegex["replace"])
  141. }
  142. for _, httpsRequestRegex := range handshakeConfig.HttpsRequestRegexes {
  143. Notice(NOTICE_HTTPS_REGEX, "%s %s", httpsRequestRegex["regex"], httpsRequestRegex["replace"])
  144. }
  145. */
  146. return nil
  147. }
  148. // doConnectedRequest performs the connected API request. This request is
  149. // used for statistics. The server returns a last_connected token for
  150. // the client to store and send next time it connects. This token is
  151. // a timestamp (using the server clock, and should be rounded to the
  152. // nearest hour) which is used to determine when a new connection is
  153. // a unique user for a time period.
  154. func (session *Session) doConnectedRequest() error {
  155. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  156. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  157. if err != nil {
  158. return ContextError(err)
  159. }
  160. if lastConnected == "" {
  161. lastConnected = "None"
  162. }
  163. url := session.buildRequestUrl(
  164. "connected",
  165. &ExtraParam{"session_id", session.tunnel.sessionId},
  166. &ExtraParam{"last_connected", lastConnected})
  167. responseBody, err := session.doGetRequest(url)
  168. if err != nil {
  169. return ContextError(err)
  170. }
  171. var response struct {
  172. connectedTimestamp string `json:connected_timestamp`
  173. }
  174. err = json.Unmarshal(responseBody, &response)
  175. if err != nil {
  176. return ContextError(err)
  177. }
  178. err = SetKeyValue(DATA_STORE_LAST_CONNECTED_KEY, response.connectedTimestamp)
  179. if err != nil {
  180. return ContextError(err)
  181. }
  182. return nil
  183. }
  184. type ExtraParam struct{ name, value string }
  185. // buildRequestUrl makes a URL containing all the common parameters
  186. // that are included with Psiphon API requests. These common parameters
  187. // are used for statistics.
  188. func (session *Session) buildRequestUrl(path string, extraParams ...*ExtraParam) string {
  189. var requestUrl bytes.Buffer
  190. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  191. // e.g., don't do this: requestUrl.WriteString("https://")
  192. requestUrl.WriteString("http://")
  193. requestUrl.WriteString(session.tunnel.serverEntry.IpAddress)
  194. requestUrl.WriteString(":")
  195. requestUrl.WriteString(session.tunnel.serverEntry.WebServerPort)
  196. requestUrl.WriteString("/")
  197. requestUrl.WriteString(path)
  198. requestUrl.WriteString("?client_session_id=")
  199. requestUrl.WriteString(session.tunnel.sessionId)
  200. requestUrl.WriteString("&server_secret=")
  201. requestUrl.WriteString(session.tunnel.serverEntry.WebServerSecret)
  202. requestUrl.WriteString("&propagation_channel_id=")
  203. requestUrl.WriteString(session.config.PropagationChannelId)
  204. requestUrl.WriteString("&sponsor_id=")
  205. requestUrl.WriteString(session.config.SponsorId)
  206. requestUrl.WriteString("&client_version=")
  207. requestUrl.WriteString(strconv.Itoa(session.config.ClientVersion))
  208. // TODO: client_tunnel_core_version
  209. requestUrl.WriteString("&relay_protocol=")
  210. requestUrl.WriteString(session.tunnel.protocol)
  211. requestUrl.WriteString("&client_platform=")
  212. requestUrl.WriteString(session.config.ClientPlatform)
  213. requestUrl.WriteString("&tunnel_whole_device=")
  214. requestUrl.WriteString(strconv.Itoa(session.config.TunnelWholeDevice))
  215. for _, extraParam := range extraParams {
  216. requestUrl.WriteString("&")
  217. requestUrl.WriteString(extraParam.name)
  218. requestUrl.WriteString("=")
  219. requestUrl.WriteString(extraParam.value)
  220. }
  221. return requestUrl.String()
  222. }
  223. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  224. func (session *Session) doGetRequest(requestUrl string) (responseBody []byte, err error) {
  225. response, err := session.psiphonHttpsClient.Get(requestUrl)
  226. if err != nil {
  227. // Trim this error since it may include long URLs
  228. return nil, ContextError(TrimError(err))
  229. }
  230. defer response.Body.Close()
  231. body, err := ioutil.ReadAll(response.Body)
  232. if err != nil {
  233. return nil, ContextError(err)
  234. }
  235. if response.StatusCode != http.StatusOK {
  236. return nil, ContextError(fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode))
  237. }
  238. return body, nil
  239. }
  240. // makeHttpsClient creates a Psiphon HTTPS client that tunnels requests and which validates
  241. // the web server using the Psiphon server entry web server certificate.
  242. // This is not a general purpose HTTPS client.
  243. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  244. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  245. // handshake inside the explicit TLS session.
  246. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  247. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  248. if err != nil {
  249. return nil, ContextError(err)
  250. }
  251. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  252. return tunnel.sshClient.Dial("tcp", addr)
  253. }
  254. dialer := NewCustomTLSDialer(
  255. &CustomTLSConfig{
  256. Dial: tunneledDialer,
  257. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  258. SendServerName: false,
  259. VerifyLegacyCertificate: certificate,
  260. })
  261. transport := &http.Transport{
  262. Dial: dialer,
  263. ResponseHeaderTimeout: PSIPHON_API_SERVER_TIMEOUT,
  264. }
  265. return &http.Client{
  266. Transport: transport,
  267. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  268. }, nil
  269. }