serverApi.go 29 KB

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