serverApi.go 13 KB

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