serverApi.go 30 KB

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