serverApi.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "net/url"
  32. "strconv"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  37. )
  38. // ServerContext is a utility struct which holds all of the data associated
  39. // with a Psiphon server connection. In addition to the established tunnel, this
  40. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  41. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  42. // API through SSH requests made directly through the tunnel's SSH client.
  43. type ServerContext struct {
  44. // Note: 64-bit ints used with atomic operations are at placed
  45. // at the start of struct to ensure 64-bit alignment.
  46. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  47. tunnelNumber int64
  48. sessionId string
  49. tunnel *Tunnel
  50. psiphonHttpsClient *http.Client
  51. statsRegexps *transferstats.Regexps
  52. clientRegion string
  53. clientUpgradeVersion string
  54. serverHandshakeTimestamp string
  55. }
  56. // nextTunnelNumber is a monotonically increasing number assigned to each
  57. // successive tunnel connection. The sessionId and tunnelNumber together
  58. // form a globally unique identifier for tunnels, which is used for
  59. // stats. Note that the number is increasing but not necessarily
  60. // consecutive for each active tunnel in session.
  61. var nextTunnelNumber int64
  62. // MakeSessionId creates a new session ID. The same session ID is used across
  63. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  64. // instance.
  65. // In server-side stats, we now consider a "session" to be the lifetime of the
  66. // Controller (e.g., the user's commanded start and stop) and we measure this
  67. // duration as well as the duration of each tunnel within the session.
  68. func MakeSessionId() (sessionId string, err error) {
  69. randomId, err := common.MakeSecureRandomBytes(common.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  70. if err != nil {
  71. return "", common.ContextError(err)
  72. }
  73. return hex.EncodeToString(randomId), nil
  74. }
  75. // NewServerContext makes the tunnelled handshake request to the Psiphon server
  76. // and returns a ServerContext struct for use with subsequent Psiphon server API
  77. // requests (e.g., periodic connected and status requests).
  78. func NewServerContext(tunnel *Tunnel, sessionId string) (*ServerContext, error) {
  79. // For legacy servers, set up psiphonHttpsClient for
  80. // accessing the Psiphon API via the web service.
  81. var psiphonHttpsClient *http.Client
  82. if !tunnel.serverEntry.SupportsSSHAPIRequests() {
  83. var err error
  84. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  85. if err != nil {
  86. return nil, common.ContextError(err)
  87. }
  88. }
  89. serverContext := &ServerContext{
  90. sessionId: sessionId,
  91. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  92. tunnel: tunnel,
  93. psiphonHttpsClient: psiphonHttpsClient,
  94. }
  95. err := serverContext.doHandshakeRequest()
  96. if err != nil {
  97. return nil, common.ContextError(err)
  98. }
  99. return serverContext, nil
  100. }
  101. // doHandshakeRequest performs the "handshake" API request. The handshake
  102. // returns upgrade info, newly discovered server entries -- which are
  103. // stored -- and sponsor info (home pages, stat regexes).
  104. func (serverContext *ServerContext) doHandshakeRequest() error {
  105. params := serverContext.getBaseParams()
  106. // *TODO*: this is obsolete?
  107. /*
  108. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  109. if err != nil {
  110. return common.ContextError(err)
  111. }
  112. // Submit a list of known servers -- this will be used for
  113. // discovery statistics.
  114. for _, ipAddress := range serverEntryIpAddresses {
  115. params = append(params, requestParam{"known_server", ipAddress})
  116. }
  117. */
  118. var response []byte
  119. if serverContext.psiphonHttpsClient == nil {
  120. request, err := makeSSHAPIRequestPayload(params)
  121. if err != nil {
  122. return common.ContextError(err)
  123. }
  124. response, err = serverContext.tunnel.SendAPIRequest(
  125. common.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  126. if err != nil {
  127. return common.ContextError(err)
  128. }
  129. } else {
  130. // Legacy web service API request
  131. responseBody, err := serverContext.doGetRequest(
  132. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  133. if err != nil {
  134. return common.ContextError(err)
  135. }
  136. // Skip legacy format lines and just parse the JSON config line
  137. configLinePrefix := []byte("Config: ")
  138. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  139. if bytes.HasPrefix(line, configLinePrefix) {
  140. response = line[len(configLinePrefix):]
  141. break
  142. }
  143. }
  144. if len(response) == 0 {
  145. return common.ContextError(errors.New("no config line found"))
  146. }
  147. }
  148. // Note:
  149. // - 'preemptive_reconnect_lifetime_milliseconds' is currently unused
  150. // - 'ssh_session_id' is ignored; client session ID is used instead
  151. var handshakeResponse struct {
  152. Homepages []string `json:"homepages"`
  153. UpgradeClientVersion string `json:"upgrade_client_version"`
  154. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  155. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  156. EncodedServerList []string `json:"encoded_server_list"`
  157. ClientRegion string `json:"client_region"`
  158. ServerTimestamp string `json:"server_timestamp"`
  159. }
  160. err := json.Unmarshal(response, &handshakeResponse)
  161. if err != nil {
  162. return common.ContextError(err)
  163. }
  164. serverContext.clientRegion = handshakeResponse.ClientRegion
  165. NoticeClientRegion(serverContext.clientRegion)
  166. var decodedServerEntries []*ServerEntry
  167. // Store discovered server entries
  168. // We use the server's time, as it's available here, for the server entry
  169. // timestamp since this is more reliable than the client time.
  170. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  171. serverEntry, err := DecodeServerEntry(
  172. encodedServerEntry,
  173. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  174. common.SERVER_ENTRY_SOURCE_DISCOVERY)
  175. if err != nil {
  176. return common.ContextError(err)
  177. }
  178. err = ValidateServerEntry(serverEntry)
  179. if err != nil {
  180. // Skip this entry and continue with the next one
  181. continue
  182. }
  183. decodedServerEntries = append(decodedServerEntries, serverEntry)
  184. }
  185. // The reason we are storing the entire array of server entries at once rather
  186. // than one at a time is that some desirable side-effects get triggered by
  187. // StoreServerEntries that don't get triggered by StoreServerEntry.
  188. err = StoreServerEntries(decodedServerEntries, true)
  189. if err != nil {
  190. return common.ContextError(err)
  191. }
  192. // TODO: formally communicate the sponsor and upgrade info to an
  193. // outer client via some control interface.
  194. for _, homepage := range handshakeResponse.Homepages {
  195. NoticeHomepage(homepage)
  196. }
  197. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  198. if handshakeResponse.UpgradeClientVersion != "" {
  199. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  200. } else {
  201. NoticeClientIsLatestVersion("")
  202. }
  203. var regexpsNotices []string
  204. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  205. handshakeResponse.PageViewRegexes,
  206. handshakeResponse.HttpsRequestRegexes)
  207. for _, notice := range regexpsNotices {
  208. NoticeAlert(notice)
  209. }
  210. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  211. return nil
  212. }
  213. // DoConnectedRequest performs the "connected" API request. This request is
  214. // used for statistics. The server returns a last_connected token for
  215. // the client to store and send next time it connects. This token is
  216. // a timestamp (using the server clock, and should be rounded to the
  217. // nearest hour) which is used to determine when a connection represents
  218. // a unique user for a time period.
  219. func (serverContext *ServerContext) DoConnectedRequest() error {
  220. params := serverContext.getBaseParams()
  221. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  222. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  223. if err != nil {
  224. return common.ContextError(err)
  225. }
  226. if lastConnected == "" {
  227. lastConnected = "None"
  228. }
  229. params["last_connected"] = lastConnected
  230. var response []byte
  231. if serverContext.psiphonHttpsClient == nil {
  232. request, err := makeSSHAPIRequestPayload(params)
  233. if err != nil {
  234. return common.ContextError(err)
  235. }
  236. response, err = serverContext.tunnel.SendAPIRequest(
  237. common.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  238. if err != nil {
  239. return common.ContextError(err)
  240. }
  241. } else {
  242. // Legacy web service API request
  243. response, err = serverContext.doGetRequest(
  244. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  245. if err != nil {
  246. return common.ContextError(err)
  247. }
  248. }
  249. var connectedResponse struct {
  250. ConnectedTimestamp string `json:"connected_timestamp"`
  251. }
  252. err = json.Unmarshal(response, &connectedResponse)
  253. if err != nil {
  254. return common.ContextError(err)
  255. }
  256. err = SetKeyValue(
  257. DATA_STORE_LAST_CONNECTED_KEY, connectedResponse.ConnectedTimestamp)
  258. if err != nil {
  259. return common.ContextError(err)
  260. }
  261. return nil
  262. }
  263. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  264. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  265. return serverContext.statsRegexps
  266. }
  267. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  268. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  269. params := serverContext.getStatusParams(true)
  270. // Note: ensure putBackStatusRequestPayload is called, to replace
  271. // payload for future attempt, in all failure cases.
  272. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  273. tunnel.serverEntry.IpAddress)
  274. if err != nil {
  275. return common.ContextError(err)
  276. }
  277. if serverContext.psiphonHttpsClient == nil {
  278. rawMessage := json.RawMessage(statusPayload)
  279. params["statusData"] = &rawMessage
  280. var request []byte
  281. request, err = makeSSHAPIRequestPayload(params)
  282. if err == nil {
  283. _, err = serverContext.tunnel.SendAPIRequest(
  284. common.PSIPHON_API_STATUS_REQUEST_NAME, request)
  285. }
  286. } else {
  287. // Legacy web service API request
  288. _, err = serverContext.doPostRequest(
  289. makeRequestUrl(serverContext.tunnel, "", "status", params),
  290. "application/json",
  291. bytes.NewReader(statusPayload))
  292. }
  293. if err != nil {
  294. // Resend the transfer stats and tunnel stats later
  295. // Note: potential duplicate reports if the server received and processed
  296. // the request but the client failed to receive the response.
  297. putBackStatusRequestPayload(statusPayloadInfo)
  298. return common.ContextError(err)
  299. }
  300. confirmStatusRequestPayload(statusPayloadInfo)
  301. return nil
  302. }
  303. func (serverContext *ServerContext) getStatusParams(isTunneled bool) requestJSONObject {
  304. params := serverContext.getBaseParams()
  305. // Add a random amount of padding to help prevent stats updates from being
  306. // a predictable size (which often happens when the connection is quiet).
  307. // TODO: base64 encoding of padding means the padding size is not exactly
  308. // [0, PADDING_MAX_BYTES].
  309. randomPadding, err := common.MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  310. if err != nil {
  311. NoticeAlert("MakeSecureRandomPadding failed: %s", err)
  312. // Proceed without random padding
  313. randomPadding = make([]byte, 0)
  314. }
  315. params["padding"] = base64.StdEncoding.EncodeToString(randomPadding)
  316. // Legacy clients set "connected" to "0" when disconnecting, and this value
  317. // is used to calculate session duration estimates. This is now superseded
  318. // by explicit tunnel stats duration reporting.
  319. // The legacy method of reconstructing session durations is not compatible
  320. // with this client's connected request retries and asynchronous final
  321. // status request attempts. So we simply set this "connected" flag to reflect
  322. // whether the request is sent tunneled or not.
  323. connected := "1"
  324. if !isTunneled {
  325. connected = "0"
  326. }
  327. params["connected"] = connected
  328. return params
  329. }
  330. // statusRequestPayloadInfo is a temporary structure for data used to
  331. // either "clear" or "put back" status request payload data depending
  332. // on whether or not the request succeeded.
  333. type statusRequestPayloadInfo struct {
  334. serverId string
  335. transferStats *transferstats.AccumulatedStats
  336. tunnelStats [][]byte
  337. }
  338. func makeStatusRequestPayload(
  339. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  340. transferStats := transferstats.TakeOutStatsForServer(serverId)
  341. tunnelStats, err := TakeOutUnreportedTunnelStats(
  342. PSIPHON_API_TUNNEL_STATS_MAX_COUNT)
  343. if err != nil {
  344. NoticeAlert(
  345. "TakeOutUnreportedTunnelStats failed: %s", common.ContextError(err))
  346. tunnelStats = nil
  347. // Proceed with transferStats only
  348. }
  349. payloadInfo := &statusRequestPayloadInfo{
  350. serverId, transferStats, tunnelStats}
  351. payload := make(map[string]interface{})
  352. hostBytes, bytesTransferred := transferStats.GetStatsForStatusRequest()
  353. payload["host_bytes"] = hostBytes
  354. payload["bytes_transferred"] = bytesTransferred
  355. // We're not recording these fields, but the server requires them.
  356. payload["page_views"] = make([]string, 0)
  357. payload["https_requests"] = make([]string, 0)
  358. // Tunnel stats records are already in JSON format
  359. jsonTunnelStats := make([]json.RawMessage, len(tunnelStats))
  360. for i, tunnelStatsRecord := range tunnelStats {
  361. jsonTunnelStats[i] = json.RawMessage(tunnelStatsRecord)
  362. }
  363. payload["tunnel_stats"] = jsonTunnelStats
  364. jsonPayload, err := json.Marshal(payload)
  365. if err != nil {
  366. // Send the transfer stats and tunnel stats later
  367. putBackStatusRequestPayload(payloadInfo)
  368. return nil, nil, common.ContextError(err)
  369. }
  370. return jsonPayload, payloadInfo, nil
  371. }
  372. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  373. transferstats.PutBackStatsForServer(
  374. payloadInfo.serverId, payloadInfo.transferStats)
  375. err := PutBackUnreportedTunnelStats(payloadInfo.tunnelStats)
  376. if err != nil {
  377. // These tunnel stats records won't be resent under after a
  378. // datastore re-initialization.
  379. NoticeAlert(
  380. "PutBackUnreportedTunnelStats failed: %s", common.ContextError(err))
  381. }
  382. }
  383. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  384. err := ClearReportedTunnelStats(payloadInfo.tunnelStats)
  385. if err != nil {
  386. // These tunnel stats records may be resent.
  387. NoticeAlert(
  388. "ClearReportedTunnelStats failed: %s", common.ContextError(err))
  389. }
  390. }
  391. // TryUntunneledStatusRequest makes direct connections to the specified
  392. // server (if supported) in an attempt to send useful bytes transferred
  393. // and tunnel duration stats after a tunnel has alreay failed.
  394. // The tunnel is assumed to be closed, but its config, protocol, and
  395. // context values must still be valid.
  396. // TryUntunneledStatusRequest emits notices detailing failed attempts.
  397. func (serverContext *ServerContext) TryUntunneledStatusRequest(isShutdown bool) error {
  398. for _, port := range serverContext.tunnel.serverEntry.GetUntunneledWebRequestPorts() {
  399. err := serverContext.doUntunneledStatusRequest(port, isShutdown)
  400. if err == nil {
  401. return nil
  402. }
  403. NoticeAlert("doUntunneledStatusRequest failed for %s:%s: %s",
  404. serverContext.tunnel.serverEntry.IpAddress, port, err)
  405. }
  406. return errors.New("all attempts failed")
  407. }
  408. // doUntunneledStatusRequest attempts an untunneled status request.
  409. func (serverContext *ServerContext) doUntunneledStatusRequest(
  410. port string, isShutdown bool) error {
  411. tunnel := serverContext.tunnel
  412. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  413. if err != nil {
  414. return common.ContextError(err)
  415. }
  416. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  417. dialConfig := tunnel.untunneledDialConfig
  418. if isShutdown {
  419. timeout = PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT
  420. // Use a copy of DialConfig without pendingConns. This ensures
  421. // this request isn't interrupted/canceled. This measure should
  422. // be used only with the very short PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT.
  423. dialConfig = new(DialConfig)
  424. *dialConfig = *tunnel.untunneledDialConfig
  425. }
  426. url := makeRequestUrl(tunnel, port, "status", serverContext.getStatusParams(false))
  427. httpClient, url, err := MakeUntunneledHttpsClient(
  428. dialConfig,
  429. certificate,
  430. url,
  431. timeout)
  432. if err != nil {
  433. return common.ContextError(err)
  434. }
  435. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  436. if err != nil {
  437. return common.ContextError(err)
  438. }
  439. bodyType := "application/json"
  440. body := bytes.NewReader(statusPayload)
  441. response, err := httpClient.Post(url, bodyType, body)
  442. if err == nil && response.StatusCode != http.StatusOK {
  443. response.Body.Close()
  444. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  445. }
  446. if err != nil {
  447. // Resend the transfer stats and tunnel stats later
  448. // Note: potential duplicate reports if the server received and processed
  449. // the request but the client failed to receive the response.
  450. putBackStatusRequestPayload(statusPayloadInfo)
  451. // Trim this error since it may include long URLs
  452. return common.ContextError(TrimError(err))
  453. }
  454. confirmStatusRequestPayload(statusPayloadInfo)
  455. response.Body.Close()
  456. return nil
  457. }
  458. // RecordTunnelStats records a tunnel duration and bytes
  459. // sent and received for subsequent reporting and quality
  460. // analysis.
  461. //
  462. // Tunnel durations are precisely measured client-side
  463. // and reported in status requests. As the duration is
  464. // not determined until the tunnel is closed, tunnel
  465. // stats records are stored in the persistent datastore
  466. // and reported via subsequent status requests sent to any
  467. // Psiphon server.
  468. //
  469. // Since the status request that reports a tunnel stats
  470. // record is not necessarily handled by the same server, the
  471. // tunnel stats records include the original server ID.
  472. //
  473. // Other fields that may change between tunnel stats recording
  474. // and reporting include client geo data, propagation channel,
  475. // sponsor ID, client version. These are not stored in the
  476. // datastore (client region, in particular, since that would
  477. // create an on-disk record of user location).
  478. // TODO: the server could encrypt, with a nonce and key unknown to
  479. // the client, a blob containing this data; return it in the
  480. // handshake response; and the client could store and later report
  481. // this blob with its tunnel stats records.
  482. //
  483. // Multiple "status" requests may be in flight at once (due
  484. // to multi-tunnel, asynchronous final status retry, and
  485. // aggressive status requests for pre-registered tunnels),
  486. // To avoid duplicate reporting, tunnel stats records are
  487. // "taken-out" by a status request and then "put back" in
  488. // case the request fails.
  489. //
  490. // Note: since tunnel stats records have a globally unique
  491. // identifier (sessionId + tunnelNumber), we could tolerate
  492. // duplicate reporting and filter our duplicates on the
  493. // server-side. Permitting duplicate reporting could increase
  494. // the velocity of reporting (for example, both the asynchronous
  495. // untunneled final status requests and the post-connected
  496. // immediate startus requests could try to report the same tunnel
  497. // stats).
  498. // Duplicate reporting may also occur when a server receives and
  499. // processes a status request but the client fails to receive
  500. // the response.
  501. func RecordTunnelStats(
  502. sessionId string,
  503. tunnelNumber int64,
  504. tunnelServerIpAddress string,
  505. establishmentDuration string,
  506. serverHandshakeTimestamp string,
  507. tunnelDuration string,
  508. totalBytesSent int64,
  509. totalBytesReceived int64) error {
  510. tunnelStats := struct {
  511. SessionId string `json:"session_id"`
  512. TunnelNumber int64 `json:"tunnel_number"`
  513. TunnelServerIpAddress string `json:"tunnel_server_ip_address"`
  514. EstablishmentDuration string `json:"establishment_duration"`
  515. ServerHandshakeTimestamp string `json:"server_handshake_timestamp"`
  516. Duration string `json:"duration"`
  517. TotalBytesSent int64 `json:"total_bytes_sent"`
  518. TotalBytesReceived int64 `json:"total_bytes_received"`
  519. }{
  520. sessionId,
  521. tunnelNumber,
  522. tunnelServerIpAddress,
  523. establishmentDuration,
  524. serverHandshakeTimestamp,
  525. tunnelDuration,
  526. totalBytesSent,
  527. totalBytesReceived,
  528. }
  529. tunnelStatsJson, err := json.Marshal(tunnelStats)
  530. if err != nil {
  531. return common.ContextError(err)
  532. }
  533. return StoreTunnelStats(tunnelStatsJson)
  534. }
  535. // DoClientVerificationRequest performs the "client_verification" API
  536. // request. This request is used to verify that the client is a valid
  537. // Psiphon client, which will determine how the server treats the client
  538. // traffic. The proof-of-validity is platform-specific and the payload
  539. // is opaque to this function but assumed to be JSON.
  540. func (serverContext *ServerContext) DoClientVerificationRequest(
  541. verificationPayload string, serverIP string) error {
  542. params := serverContext.getBaseParams()
  543. var response []byte
  544. var err error
  545. if serverContext.psiphonHttpsClient == nil {
  546. // Empty verification payload signals desire to
  547. // query the server for current TTL. This is
  548. // indicated to the server by the absense of the
  549. // verificationData field.
  550. if verificationPayload != "" {
  551. rawMessage := json.RawMessage(verificationPayload)
  552. params["verificationData"] = &rawMessage
  553. }
  554. request, err := makeSSHAPIRequestPayload(params)
  555. if err != nil {
  556. return common.ContextError(err)
  557. }
  558. response, err = serverContext.tunnel.SendAPIRequest(
  559. common.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME, request)
  560. if err != nil {
  561. return common.ContextError(err)
  562. }
  563. } else {
  564. // Legacy web service API request
  565. response, err = serverContext.doPostRequest(
  566. makeRequestUrl(serverContext.tunnel, "", "client_verification", params),
  567. "application/json",
  568. bytes.NewReader([]byte(verificationPayload)))
  569. if err != nil {
  570. return common.ContextError(err)
  571. }
  572. }
  573. // Server may request a new verification to be performed,
  574. // for example, if the payload timestamp is too old, etc.
  575. var clientVerificationResponse struct {
  576. ClientVerificationServerNonce string `json:"client_verification_server_nonce"`
  577. ClientVerificationTTLSeconds int `json:"client_verification_ttl_seconds"`
  578. ClientVerificationResetCache bool `json:"client_verification_reset_cache"`
  579. }
  580. // In case of empty response body the json.Unmarshal will fail
  581. // and clientVerificationResponse will be initialized with default values
  582. _ = json.Unmarshal(response, &clientVerificationResponse)
  583. if clientVerificationResponse.ClientVerificationTTLSeconds > 0 {
  584. NoticeClientVerificationRequired(
  585. clientVerificationResponse.ClientVerificationServerNonce,
  586. clientVerificationResponse.ClientVerificationTTLSeconds,
  587. clientVerificationResponse.ClientVerificationResetCache)
  588. } else {
  589. NoticeClientVerificationRequestCompleted(serverIP)
  590. }
  591. return nil
  592. }
  593. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  594. func (serverContext *ServerContext) doGetRequest(
  595. requestUrl string) (responseBody []byte, err error) {
  596. response, err := serverContext.psiphonHttpsClient.Get(requestUrl)
  597. if err == nil && response.StatusCode != http.StatusOK {
  598. response.Body.Close()
  599. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  600. }
  601. if err != nil {
  602. // Trim this error since it may include long URLs
  603. return nil, common.ContextError(TrimError(err))
  604. }
  605. defer response.Body.Close()
  606. body, err := ioutil.ReadAll(response.Body)
  607. if err != nil {
  608. return nil, common.ContextError(err)
  609. }
  610. return body, nil
  611. }
  612. // doPostRequest makes a tunneled HTTPS POST request.
  613. func (serverContext *ServerContext) doPostRequest(
  614. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  615. response, err := serverContext.psiphonHttpsClient.Post(requestUrl, bodyType, body)
  616. if err == nil && response.StatusCode != http.StatusOK {
  617. response.Body.Close()
  618. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  619. }
  620. if err != nil {
  621. // Trim this error since it may include long URLs
  622. return nil, common.ContextError(TrimError(err))
  623. }
  624. defer response.Body.Close()
  625. responseBody, err = ioutil.ReadAll(response.Body)
  626. if err != nil {
  627. return nil, common.ContextError(err)
  628. }
  629. return responseBody, nil
  630. }
  631. type requestJSONObject map[string]interface{}
  632. // getBaseParams returns all the common API parameters that are included
  633. // with each Psiphon API request. These common parameters are used for
  634. // statistics.
  635. func (serverContext *ServerContext) getBaseParams() requestJSONObject {
  636. params := make(requestJSONObject)
  637. tunnel := serverContext.tunnel
  638. params["session_id"] = serverContext.sessionId
  639. params["client_session_id"] = serverContext.sessionId
  640. params["server_secret"] = tunnel.serverEntry.WebServerSecret
  641. params["propagation_channel_id"] = tunnel.config.PropagationChannelId
  642. params["sponsor_id"] = tunnel.config.SponsorId
  643. params["client_version"] = tunnel.config.ClientVersion
  644. // TODO: client_tunnel_core_version?
  645. params["relay_protocol"] = tunnel.protocol
  646. params["client_platform"] = tunnel.config.ClientPlatform
  647. params["tunnel_whole_device"] = strconv.Itoa(tunnel.config.TunnelWholeDevice)
  648. // The following parameters may be blank and must
  649. // not be sent to the server if blank.
  650. if tunnel.config.DeviceRegion != "" {
  651. params["device_region"] = tunnel.config.DeviceRegion
  652. }
  653. if tunnel.dialStats != nil {
  654. if tunnel.dialStats.UpstreamProxyType != "" {
  655. params["upstream_proxy_type"] = tunnel.dialStats.UpstreamProxyType
  656. }
  657. if tunnel.dialStats.UpstreamProxyCustomHeaderNames != nil {
  658. params["upstream_proxy_custom_header_names"] = tunnel.dialStats.UpstreamProxyCustomHeaderNames
  659. }
  660. if tunnel.dialStats.MeekDialAddress != "" {
  661. params["meek_dial_address"] = tunnel.dialStats.MeekDialAddress
  662. }
  663. if tunnel.dialStats.MeekResolvedIPAddress != "" {
  664. params["meek_resolved_ip_address"] = tunnel.dialStats.MeekResolvedIPAddress
  665. }
  666. if tunnel.dialStats.MeekSNIServerName != "" {
  667. params["meek_sni_server_name"] = tunnel.dialStats.MeekSNIServerName
  668. }
  669. if tunnel.dialStats.MeekHostHeader != "" {
  670. params["meek_host_header"] = tunnel.dialStats.MeekHostHeader
  671. }
  672. transformedHostName := "0"
  673. if tunnel.dialStats.MeekTransformedHostName {
  674. transformedHostName = "1"
  675. }
  676. params["meek_transformed_host_name"] = transformedHostName
  677. }
  678. if tunnel.serverEntry.Region != "" {
  679. params["server_entry_region"] = tunnel.serverEntry.Region
  680. }
  681. if tunnel.serverEntry.LocalSource != "" {
  682. params["server_entry_source"] = tunnel.serverEntry.LocalSource
  683. }
  684. // As with last_connected, this timestamp stat, which may be
  685. // a precise handshake request server timestamp, is truncated
  686. // to hour granularity to avoid introducing a reconstructable
  687. // cross-session user trace into server logs.
  688. localServerEntryTimestamp := common.TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  689. if localServerEntryTimestamp != "" {
  690. params["server_entry_timestamp"] = localServerEntryTimestamp
  691. }
  692. return params
  693. }
  694. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  695. func makeSSHAPIRequestPayload(params requestJSONObject) ([]byte, error) {
  696. jsonPayload, err := json.Marshal(params)
  697. if err != nil {
  698. return nil, common.ContextError(err)
  699. }
  700. return jsonPayload, nil
  701. }
  702. // makeRequestUrl makes a URL for a web service API request.
  703. func makeRequestUrl(tunnel *Tunnel, port, path string, params requestJSONObject) string {
  704. var requestUrl bytes.Buffer
  705. if port == "" {
  706. port = tunnel.serverEntry.WebServerPort
  707. }
  708. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  709. // e.g., don't do this: requestUrl.WriteString("https://")
  710. requestUrl.WriteString("http://")
  711. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  712. requestUrl.WriteString(":")
  713. requestUrl.WriteString(port)
  714. requestUrl.WriteString("/")
  715. requestUrl.WriteString(path)
  716. if len(params) > 0 {
  717. queryParams := url.Values{}
  718. for name, value := range params {
  719. strValue := ""
  720. switch v := value.(type) {
  721. case string:
  722. strValue = v
  723. case []string:
  724. // String array param encoded as JSON
  725. jsonValue, err := json.Marshal(v)
  726. if err != nil {
  727. break
  728. }
  729. strValue = string(jsonValue)
  730. }
  731. queryParams.Set(name, strValue)
  732. }
  733. requestUrl.WriteString("?")
  734. requestUrl.WriteString(queryParams.Encode())
  735. }
  736. return requestUrl.String()
  737. }
  738. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  739. // requests and which validates the web server using the Psiphon server entry web server
  740. // certificate. This is not a general purpose HTTPS client.
  741. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  742. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  743. // handshake inside the explicit TLS session.
  744. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  745. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  746. if err != nil {
  747. return nil, common.ContextError(err)
  748. }
  749. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  750. // TODO: check tunnel.isClosed, and apply TUNNEL_PORT_FORWARD_DIAL_TIMEOUT as in Tunnel.Dial?
  751. return tunnel.sshClient.Dial("tcp", addr)
  752. }
  753. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  754. dialer := NewCustomTLSDialer(
  755. &CustomTLSConfig{
  756. Dial: tunneledDialer,
  757. Timeout: timeout,
  758. VerifyLegacyCertificate: certificate,
  759. })
  760. transport := &http.Transport{
  761. Dial: dialer,
  762. }
  763. return &http.Client{
  764. Transport: transport,
  765. Timeout: timeout,
  766. }, nil
  767. }