serverApi.go 13 KB

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