serverApi.go 13 KB

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