serverApi.go 30 KB

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