serverApi.go 12 KB

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