serverApi.go 13 KB

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