serverApi.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. // ***TEMP***
  197. session.clientRegion = "CA"
  198. // Store discovered server entries
  199. for _, encodedServerEntry := range handshakeConfig.EncodedServerList {
  200. serverEntry, err := DecodeServerEntry(encodedServerEntry)
  201. if err != nil {
  202. return ContextError(err)
  203. }
  204. err = ValidateServerEntry(serverEntry)
  205. if err != nil {
  206. // Skip this entry and continue with the next one
  207. continue
  208. }
  209. err = StoreServerEntry(serverEntry, true)
  210. if err != nil {
  211. return ContextError(err)
  212. }
  213. }
  214. // TODO: formally communicate the sponsor and upgrade info to an
  215. // outer client via some control interface.
  216. for _, homepage := range handshakeConfig.Homepages {
  217. NoticeHomepage(homepage)
  218. }
  219. if handshakeConfig.UpgradeClientVersion != "" {
  220. NoticeClientUpgradeAvailable(handshakeConfig.UpgradeClientVersion)
  221. }
  222. var regexpsNotices []string
  223. session.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  224. handshakeConfig.PageViewRegexes,
  225. handshakeConfig.HttpsRequestRegexes)
  226. for _, notice := range regexpsNotices {
  227. NoticeAlert(notice)
  228. }
  229. return nil
  230. }
  231. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  232. func (session *Session) doGetRequest(requestUrl string) (responseBody []byte, err error) {
  233. response, err := session.psiphonHttpsClient.Get(requestUrl)
  234. if err != nil {
  235. // Trim this error since it may include long URLs
  236. return nil, ContextError(TrimError(err))
  237. }
  238. defer response.Body.Close()
  239. body, err := ioutil.ReadAll(response.Body)
  240. if err != nil {
  241. return nil, ContextError(err)
  242. }
  243. if response.StatusCode != http.StatusOK {
  244. return nil, ContextError(fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode))
  245. }
  246. return body, nil
  247. }
  248. // doPostRequest makes a tunneled HTTPS POST request.
  249. func (session *Session) doPostRequest(requestUrl string, bodyType string, body io.Reader) (err error) {
  250. response, err := session.psiphonHttpsClient.Post(requestUrl, bodyType, body)
  251. if err != nil {
  252. // Trim this error since it may include long URLs
  253. return ContextError(TrimError(err))
  254. }
  255. response.Body.Close()
  256. if response.StatusCode != http.StatusOK {
  257. return ContextError(fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode))
  258. }
  259. return
  260. }
  261. // makeBaseRequestUrl makes a URL containing all the common parameters
  262. // that are included with Psiphon API requests. These common parameters
  263. // are used for statistics.
  264. func makeBaseRequestUrl(config *Config, tunnel *Tunnel, sessionId string) string {
  265. var requestUrl bytes.Buffer
  266. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  267. // e.g., don't do this: requestUrl.WriteString("https://")
  268. requestUrl.WriteString("http://")
  269. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  270. requestUrl.WriteString(":")
  271. requestUrl.WriteString(tunnel.serverEntry.WebServerPort)
  272. requestUrl.WriteString("/")
  273. // Placeholder for the path component of a request
  274. requestUrl.WriteString("%s")
  275. requestUrl.WriteString("?client_session_id=")
  276. requestUrl.WriteString(sessionId)
  277. requestUrl.WriteString("&server_secret=")
  278. requestUrl.WriteString(tunnel.serverEntry.WebServerSecret)
  279. requestUrl.WriteString("&propagation_channel_id=")
  280. requestUrl.WriteString(config.PropagationChannelId)
  281. requestUrl.WriteString("&sponsor_id=")
  282. requestUrl.WriteString(config.SponsorId)
  283. requestUrl.WriteString("&client_version=")
  284. requestUrl.WriteString(config.ClientVersion)
  285. // TODO: client_tunnel_core_version
  286. requestUrl.WriteString("&relay_protocol=")
  287. requestUrl.WriteString(tunnel.protocol)
  288. requestUrl.WriteString("&client_platform=")
  289. requestUrl.WriteString(config.ClientPlatform)
  290. requestUrl.WriteString("&tunnel_whole_device=")
  291. requestUrl.WriteString(strconv.Itoa(config.TunnelWholeDevice))
  292. return requestUrl.String()
  293. }
  294. type ExtraParam struct{ name, value string }
  295. // buildRequestUrl makes a URL for an API request. The URL includes the
  296. // base request URL and any extra parameters for the specific request.
  297. func (session *Session) buildRequestUrl(path string, extraParams ...*ExtraParam) string {
  298. var requestUrl bytes.Buffer
  299. requestUrl.WriteString(fmt.Sprintf(session.baseRequestUrl, path))
  300. for _, extraParam := range extraParams {
  301. requestUrl.WriteString("&")
  302. requestUrl.WriteString(extraParam.name)
  303. requestUrl.WriteString("=")
  304. requestUrl.WriteString(extraParam.value)
  305. }
  306. return requestUrl.String()
  307. }
  308. // makeHttpsClient creates a Psiphon HTTPS client that tunnels requests and which validates
  309. // the web server using the Psiphon server entry web server certificate.
  310. // This is not a general purpose HTTPS client.
  311. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  312. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  313. // handshake inside the explicit TLS session.
  314. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  315. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  316. if err != nil {
  317. return nil, ContextError(err)
  318. }
  319. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  320. return tunnel.sshClient.Dial("tcp", addr)
  321. }
  322. dialer := NewCustomTLSDialer(
  323. &CustomTLSConfig{
  324. Dial: tunneledDialer,
  325. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  326. SendServerName: false,
  327. VerifyLegacyCertificate: certificate,
  328. })
  329. transport := &http.Transport{
  330. Dial: dialer,
  331. ResponseHeaderTimeout: PSIPHON_API_SERVER_TIMEOUT,
  332. }
  333. return &http.Client{
  334. Transport: transport,
  335. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  336. }, nil
  337. }