serverApi.go 29 KB

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