serverApi.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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/base64"
  23. "encoding/hex"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  28. "io"
  29. "io/ioutil"
  30. "net"
  31. "net/http"
  32. "strconv"
  33. )
  34. // Session is a utility struct which holds all of the data associated
  35. // with a Psiphon session. In addition to the established tunnel, this
  36. // includes the session ID (used for Psiphon API requests) and a http
  37. // client configured to make tunneled Psiphon API requests.
  38. type Session struct {
  39. sessionId string
  40. baseRequestUrl string
  41. psiphonHttpsClient *http.Client
  42. statsRegexps *transferstats.Regexps
  43. statsServerId string
  44. clientRegion string
  45. }
  46. // MakeSessionId creates a new session ID. Making the session ID is not done
  47. // in NewSession because:
  48. // (1) the transport needs to send the ID in the SSH credentials before the tunnel
  49. // is established and NewSession performs a handshake on an established tunnel.
  50. // (2) the same session ID is used across multi-tunnel controller runs, where each
  51. // tunnel has its own Session instance.
  52. func MakeSessionId() (sessionId string, err error) {
  53. randomId, err := MakeSecureRandomBytes(PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  54. if err != nil {
  55. return "", ContextError(err)
  56. }
  57. return hex.EncodeToString(randomId), nil
  58. }
  59. // NewSession makes the tunnelled handshake request to the
  60. // Psiphon server and returns a Session struct, initialized with the
  61. // session ID, for use with subsequent Psiphon server API requests (e.g.,
  62. // periodic connected and status requests).
  63. func NewSession(config *Config, tunnel *Tunnel, sessionId string) (session *Session, err error) {
  64. psiphonHttpsClient, err := makePsiphonHttpsClient(tunnel)
  65. if err != nil {
  66. return nil, ContextError(err)
  67. }
  68. session = &Session{
  69. sessionId: sessionId,
  70. baseRequestUrl: makeBaseRequestUrl(config, tunnel, sessionId),
  71. psiphonHttpsClient: psiphonHttpsClient,
  72. statsServerId: tunnel.serverEntry.IpAddress,
  73. }
  74. err = session.doHandshakeRequest()
  75. if err != nil {
  76. return nil, ContextError(err)
  77. }
  78. return session, nil
  79. }
  80. // DoConnectedRequest performs the connected API request. This request is
  81. // used for statistics. The server returns a last_connected token for
  82. // the client to store and send next time it connects. This token is
  83. // a timestamp (using the server clock, and should be rounded to the
  84. // nearest hour) which is used to determine when a connection represents
  85. // a unique user for a time period.
  86. func (session *Session) DoConnectedRequest() error {
  87. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  88. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  89. if err != nil {
  90. return ContextError(err)
  91. }
  92. if lastConnected == "" {
  93. lastConnected = "None"
  94. }
  95. url := session.buildRequestUrl(
  96. "connected",
  97. &ExtraParam{"session_id", session.sessionId},
  98. &ExtraParam{"last_connected", lastConnected})
  99. responseBody, err := session.doGetRequest(url)
  100. if err != nil {
  101. return ContextError(err)
  102. }
  103. var response struct {
  104. connectedTimestamp string `json:connected_timestamp`
  105. }
  106. err = json.Unmarshal(responseBody, &response)
  107. if err != nil {
  108. return ContextError(err)
  109. }
  110. err = SetKeyValue(DATA_STORE_LAST_CONNECTED_KEY, response.connectedTimestamp)
  111. if err != nil {
  112. return ContextError(err)
  113. }
  114. return nil
  115. }
  116. // ServerID provides a unique identifier for the server the session connects to.
  117. // This ID is consistent between multiple sessions/tunnels connected to that server.
  118. func (session *Session) StatsServerID() string {
  119. return session.statsServerId
  120. }
  121. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  122. func (session *Session) StatsRegexps() *transferstats.Regexps {
  123. return session.statsRegexps
  124. }
  125. // DoStatusRequest makes a /status request to the server, sending session stats.
  126. func (session *Session) DoStatusRequest(statsPayload json.Marshaler) error {
  127. statsPayloadJSON, err := json.Marshal(statsPayload)
  128. if err != nil {
  129. return ContextError(err)
  130. }
  131. // Add a random amount of padding to help prevent stats updates from being
  132. // a predictable size (which often happens when the connection is quiet).
  133. padding := MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  134. // "connected" is a legacy parameter. This client does not report when
  135. // it has disconnected.
  136. url := session.buildRequestUrl(
  137. "status",
  138. &ExtraParam{"session_id", session.sessionId},
  139. &ExtraParam{"connected", "1"},
  140. // TODO: base64 encoding of padding means the padding
  141. // size is not exactly [0, PADDING_MAX_BYTES]
  142. &ExtraParam{"padding", base64.StdEncoding.EncodeToString(padding)})
  143. err = session.doPostRequest(url, "application/json", bytes.NewReader(statsPayloadJSON))
  144. if err != nil {
  145. return ContextError(err)
  146. }
  147. return nil
  148. }
  149. // doHandshakeRequest performs the handshake API request. The handshake
  150. // returns upgrade info, newly discovered server entries -- which are
  151. // stored -- and sponsor info (home pages, stat regexes).
  152. func (session *Session) doHandshakeRequest() error {
  153. extraParams := make([]*ExtraParam, 0)
  154. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  155. if err != nil {
  156. return ContextError(err)
  157. }
  158. // Submit a list of known servers -- this will be used for
  159. // discovery statistics.
  160. for _, ipAddress := range serverEntryIpAddresses {
  161. extraParams = append(extraParams, &ExtraParam{"known_server", ipAddress})
  162. }
  163. url := session.buildRequestUrl("handshake", extraParams...)
  164. responseBody, err := session.doGetRequest(url)
  165. if err != nil {
  166. return ContextError(err)
  167. }
  168. // Skip legacy format lines and just parse the JSON config line
  169. configLinePrefix := []byte("Config: ")
  170. var configLine []byte
  171. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  172. if bytes.HasPrefix(line, configLinePrefix) {
  173. configLine = line[len(configLinePrefix):]
  174. break
  175. }
  176. }
  177. if len(configLine) == 0 {
  178. return ContextError(errors.New("no config line found"))
  179. }
  180. // Note:
  181. // - 'preemptive_reconnect_lifetime_milliseconds' is currently unused
  182. // - 'ssh_session_id' is ignored; client session ID is used instead
  183. var handshakeConfig struct {
  184. Homepages []string `json:"homepages"`
  185. UpgradeClientVersion string `json:"upgrade_client_version"`
  186. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  187. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  188. EncodedServerList []string `json:"encoded_server_list"`
  189. ClientRegion string `json:"client_region"`
  190. }
  191. err = json.Unmarshal(configLine, &handshakeConfig)
  192. if err != nil {
  193. return ContextError(err)
  194. }
  195. session.clientRegion = handshakeConfig.ClientRegion
  196. // Store discovered server entries
  197. for _, encodedServerEntry := range handshakeConfig.EncodedServerList {
  198. serverEntry, err := DecodeServerEntry(encodedServerEntry)
  199. if err != nil {
  200. return ContextError(err)
  201. }
  202. err = ValidateServerEntry(serverEntry)
  203. if err != nil {
  204. // Skip this entry and continue with the next one
  205. continue
  206. }
  207. err = StoreServerEntry(serverEntry, true)
  208. if err != nil {
  209. return ContextError(err)
  210. }
  211. }
  212. // TODO: formally communicate the sponsor and upgrade info to an
  213. // outer client via some control interface.
  214. for _, homepage := range handshakeConfig.Homepages {
  215. NoticeHomepage(homepage)
  216. }
  217. if handshakeConfig.UpgradeClientVersion != "" {
  218. NoticeClientUpgradeAvailable(handshakeConfig.UpgradeClientVersion)
  219. }
  220. var regexpsNotices []string
  221. session.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  222. handshakeConfig.PageViewRegexes,
  223. handshakeConfig.HttpsRequestRegexes)
  224. for _, notice := range regexpsNotices {
  225. NoticeAlert(notice)
  226. }
  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. }