serverApi.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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. "context"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "encoding/json"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "net/url"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  44. )
  45. // ServerContext is a utility struct which holds all of the data associated
  46. // with a Psiphon server connection. In addition to the established tunnel, this
  47. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  48. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  49. // API through SSH requests made directly through the tunnel's SSH client.
  50. type ServerContext struct {
  51. tunnel *Tunnel
  52. psiphonHttpsClient *http.Client
  53. statsRegexps *transferstats.Regexps
  54. clientUpgradeVersion string
  55. serverHandshakeTimestamp string
  56. paddingPRNG *prng.PRNG
  57. }
  58. // MakeSessionId creates a new session ID. The same session ID is used across
  59. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  60. // instance.
  61. // In server-side stats, we now consider a "session" to be the lifetime of the
  62. // Controller (e.g., the user's commanded start and stop) and we measure this
  63. // duration as well as the duration of each tunnel within the session.
  64. func MakeSessionId() (string, error) {
  65. randomId, err := common.MakeSecureRandomBytes(protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  66. if err != nil {
  67. return "", errors.Trace(err)
  68. }
  69. return hex.EncodeToString(randomId), nil
  70. }
  71. // NewServerContext makes the tunneled handshake request to the Psiphon server
  72. // and returns a ServerContext struct for use with subsequent Psiphon server API
  73. // requests (e.g., periodic connected and status requests).
  74. func NewServerContext(tunnel *Tunnel) (*ServerContext, error) {
  75. // For legacy servers, set up psiphonHttpsClient for
  76. // accessing the Psiphon API via the web service.
  77. var psiphonHttpsClient *http.Client
  78. if !tunnel.dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  79. tunnel.config.TargetApiProtocol == protocol.PSIPHON_WEB_API_PROTOCOL {
  80. var err error
  81. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  82. if err != nil {
  83. return nil, errors.Trace(err)
  84. }
  85. }
  86. serverContext := &ServerContext{
  87. tunnel: tunnel,
  88. psiphonHttpsClient: psiphonHttpsClient,
  89. paddingPRNG: prng.NewPRNGWithSeed(tunnel.dialParams.APIRequestPaddingSeed),
  90. }
  91. ignoreRegexps := tunnel.config.GetParameters().Get().Bool(
  92. parameters.IgnoreHandshakeStatsRegexps)
  93. err := serverContext.doHandshakeRequest(ignoreRegexps)
  94. if err != nil {
  95. return nil, errors.Trace(err)
  96. }
  97. return serverContext, nil
  98. }
  99. // doHandshakeRequest performs the "handshake" API request. The handshake
  100. // returns upgrade info, newly discovered server entries -- which are
  101. // stored -- and sponsor info (home pages, stat regexes).
  102. func (serverContext *ServerContext) doHandshakeRequest(
  103. ignoreStatsRegexps bool) error {
  104. params := serverContext.getBaseAPIParameters(baseParametersAll)
  105. // The server will return a signed copy of its own server entry when the
  106. // client specifies this 'missing_server_entry_signature' parameter.
  107. //
  108. // The purpose of this mechanism is to rapidly upgrade client local storage
  109. // from unsigned to signed server entries, and to ensure that the client has
  110. // a signed server entry for its currently connected server as required for
  111. // the client-to-client exchange feature.
  112. //
  113. // The server entry will be included in handshakeResponse.EncodedServerList,
  114. // along side discovery servers.
  115. requestedMissingSignature := false
  116. if !serverContext.tunnel.dialParams.ServerEntry.HasSignature() {
  117. requestedMissingSignature = true
  118. params["missing_server_entry_signature"] =
  119. serverContext.tunnel.dialParams.ServerEntry.Tag
  120. }
  121. doTactics := !serverContext.tunnel.config.DisableTactics
  122. networkID := ""
  123. if doTactics {
  124. // Limitation: it is assumed that the network ID obtained here is the
  125. // one that is active when the handshake request is received by the
  126. // server. However, it is remotely possible to switch networks
  127. // immediately after invoking the GetNetworkID callback and initiating
  128. // the handshake, if the tunnel protocol is meek.
  129. //
  130. // The response handling code below calls GetNetworkID again and ignores
  131. // any tactics payload if the network ID is not the same. While this
  132. // doesn't detect all cases of changing networks, it reduces the already
  133. // narrow window.
  134. networkID = serverContext.tunnel.config.GetNetworkID()
  135. err := tactics.SetTacticsAPIParameters(
  136. GetTacticsStorer(serverContext.tunnel.config),
  137. networkID,
  138. params)
  139. if err != nil {
  140. return errors.Trace(err)
  141. }
  142. }
  143. // When split tunnel mode is enabled, indicate this to the server. When
  144. // indicated, the server will perform split tunnel classifications on TCP
  145. // port forwards and reject, with a distinct response, port forwards which
  146. // the client should connect to directly, untunneled.
  147. if serverContext.tunnel.config.EnableSplitTunnel {
  148. params["split_tunnel"] = "1"
  149. }
  150. var response []byte
  151. if serverContext.psiphonHttpsClient == nil {
  152. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] =
  153. serverContext.tunnel.config.GetAuthorizations()
  154. request, err := serverContext.makeSSHAPIRequestPayload(params)
  155. if err != nil {
  156. return errors.Trace(err)
  157. }
  158. response, err = serverContext.tunnel.SendAPIRequest(
  159. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  160. if err != nil {
  161. return errors.Trace(err)
  162. }
  163. } else {
  164. // Legacy web service API request
  165. responseBody, err := serverContext.doGetRequest(
  166. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  167. if err != nil {
  168. return errors.Trace(err)
  169. }
  170. // Skip legacy format lines and just parse the JSON config line
  171. configLinePrefix := []byte("Config: ")
  172. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  173. if bytes.HasPrefix(line, configLinePrefix) {
  174. response = line[len(configLinePrefix):]
  175. break
  176. }
  177. }
  178. if len(response) == 0 {
  179. return errors.TraceNew("no config line found")
  180. }
  181. }
  182. // Legacy fields:
  183. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  184. // - 'ssh_session_id' is ignored; client session ID is used instead
  185. var handshakeResponse protocol.HandshakeResponse
  186. // Initialize these fields to distinguish between psiphond omitting values in
  187. // the response and the zero value, which means unlimited rate.
  188. handshakeResponse.UpstreamBytesPerSecond = -1
  189. handshakeResponse.DownstreamBytesPerSecond = -1
  190. err := json.Unmarshal(response, &handshakeResponse)
  191. if err != nil {
  192. return errors.Trace(err)
  193. }
  194. if serverContext.tunnel.config.EmitClientAddress {
  195. NoticeClientAddress(handshakeResponse.ClientAddress)
  196. }
  197. NoticeClientRegion(handshakeResponse.ClientRegion)
  198. var serverEntries []protocol.ServerEntryFields
  199. // Store discovered server entries
  200. // We use the server's time, as it's available here, for the server entry
  201. // timestamp since this is more reliable than the client time.
  202. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  203. serverEntryFields, err := protocol.DecodeServerEntryFields(
  204. encodedServerEntry,
  205. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  206. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  207. if err != nil {
  208. return errors.Trace(err)
  209. }
  210. // Retain the original timestamp and source in the requestedMissingSignature
  211. // case, as this server entry was not discovered here.
  212. //
  213. // Limitation: there is a transient edge case where
  214. // requestedMissingSignature will be set for a discovery server entry that
  215. // _is_ also discovered here.
  216. if requestedMissingSignature &&
  217. serverEntryFields.GetIPAddress() == serverContext.tunnel.dialParams.ServerEntry.IpAddress {
  218. serverEntryFields.SetLocalTimestamp(serverContext.tunnel.dialParams.ServerEntry.LocalTimestamp)
  219. serverEntryFields.SetLocalSource(serverContext.tunnel.dialParams.ServerEntry.LocalSource)
  220. }
  221. err = protocol.ValidateServerEntryFields(serverEntryFields)
  222. if err != nil {
  223. // Skip this entry and continue with the next one
  224. NoticeWarning("invalid handshake server entry: %s", err)
  225. continue
  226. }
  227. serverEntries = append(serverEntries, serverEntryFields)
  228. }
  229. err = StoreServerEntries(
  230. serverContext.tunnel.config,
  231. serverEntries,
  232. true)
  233. if err != nil {
  234. return errors.Trace(err)
  235. }
  236. NoticeHomepages(handshakeResponse.Homepages)
  237. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  238. if handshakeResponse.UpgradeClientVersion != "" {
  239. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  240. } else {
  241. NoticeClientIsLatestVersion("")
  242. }
  243. if !ignoreStatsRegexps {
  244. // The handshake returns page_view_regexes and https_request_regexes.
  245. // page_view_regexes is obsolete and not used. https_request_regexes, which
  246. // are actually host/domain name regexes, are used for host/domain name
  247. // bytes transferred metrics: tunneled traffic TLS SNI server names and HTTP
  248. // Host header host names are matched against these regexes to select flows
  249. // for bytes transferred counting.
  250. var regexpsNotices []string
  251. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  252. handshakeResponse.HttpsRequestRegexes)
  253. for _, notice := range regexpsNotices {
  254. NoticeWarning(notice)
  255. }
  256. }
  257. diagnosticID := serverContext.tunnel.dialParams.ServerEntry.GetDiagnosticID()
  258. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  259. NoticeServerTimestamp(diagnosticID, serverContext.serverHandshakeTimestamp)
  260. NoticeActiveAuthorizationIDs(diagnosticID, handshakeResponse.ActiveAuthorizationIDs)
  261. NoticeTrafficRateLimits(
  262. diagnosticID,
  263. handshakeResponse.UpstreamBytesPerSecond,
  264. handshakeResponse.DownstreamBytesPerSecond)
  265. if doTactics && handshakeResponse.TacticsPayload != nil &&
  266. networkID == serverContext.tunnel.config.GetNetworkID() {
  267. var payload *tactics.Payload
  268. err := json.Unmarshal(handshakeResponse.TacticsPayload, &payload)
  269. if err != nil {
  270. return errors.Trace(err)
  271. }
  272. // handshakeResponse.TacticsPayload may be "null", and payload
  273. // will successfully unmarshal as nil. As a result, the previous
  274. // handshakeResponse.TacticsPayload != nil test is insufficient.
  275. if payload != nil {
  276. tacticsRecord, err := tactics.HandleTacticsPayload(
  277. GetTacticsStorer(serverContext.tunnel.config),
  278. networkID,
  279. payload)
  280. if err != nil {
  281. return errors.Trace(err)
  282. }
  283. if tacticsRecord != nil &&
  284. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  285. err := serverContext.tunnel.config.SetParameters(
  286. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  287. if err != nil {
  288. NoticeInfo("apply handshake tactics failed: %s", err)
  289. }
  290. // The error will be due to invalid tactics values
  291. // from the server. When SetParameters fails, all
  292. // previous tactics values are left in place.
  293. }
  294. }
  295. }
  296. return nil
  297. }
  298. // DoConnectedRequest performs the "connected" API request. This request is
  299. // used for statistics, including unique user counting; reporting the full
  300. // tunnel establishment duration including the handshake request; and updated
  301. // fragmentor metrics.
  302. //
  303. // Users are not assigned identifiers. Instead, daily unique users are
  304. // calculated by having clients submit their last connected timestamp
  305. // (truncated to an hour, as a privacy measure). As client clocks are
  306. // unreliable, the server returns new last_connected values for the client to
  307. // store and send next time it connects.
  308. func (serverContext *ServerContext) DoConnectedRequest() error {
  309. // Limitation: as currently implemented, the last_connected exchange isn't a
  310. // distributed, atomic operation. When clients send the connected request,
  311. // the server may receive the request, count a unique user based on the
  312. // client's last_connected, and then the tunnel fails before the client
  313. // receives the response, so the client will not update its last_connected
  314. // value and submit the same one again, resulting in an inflated unique user
  315. // count.
  316. //
  317. // The SetInFlightConnectedRequest mechanism mitigates one class of connected
  318. // request interruption, a commanded shutdown in the middle of a connected
  319. // request, by allowing some time for the request to complete before
  320. // terminating the tunnel.
  321. //
  322. // TODO: consider extending the connected request protocol with additional
  323. // "acknowledgment" messages so that the server does not commit its unique
  324. // user count until after the client has acknowledged receipt and durable
  325. // storage of the new last_connected value.
  326. requestDone := make(chan struct{})
  327. defer close(requestDone)
  328. if !serverContext.tunnel.SetInFlightConnectedRequest(requestDone) {
  329. return errors.TraceNew("tunnel is closing")
  330. }
  331. defer serverContext.tunnel.SetInFlightConnectedRequest(nil)
  332. params := serverContext.getBaseAPIParameters(
  333. baseParametersOnlyUpstreamFragmentorDialParameters)
  334. lastConnected, err := getLastConnected()
  335. if err != nil {
  336. return errors.Trace(err)
  337. }
  338. params["last_connected"] = lastConnected
  339. // serverContext.tunnel.establishDuration is nanoseconds; report milliseconds
  340. params["establishment_duration"] =
  341. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/time.Millisecond)
  342. var response []byte
  343. if serverContext.psiphonHttpsClient == nil {
  344. request, err := serverContext.makeSSHAPIRequestPayload(params)
  345. if err != nil {
  346. return errors.Trace(err)
  347. }
  348. response, err = serverContext.tunnel.SendAPIRequest(
  349. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  350. if err != nil {
  351. return errors.Trace(err)
  352. }
  353. } else {
  354. // Legacy web service API request
  355. response, err = serverContext.doGetRequest(
  356. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  357. if err != nil {
  358. return errors.Trace(err)
  359. }
  360. }
  361. var connectedResponse protocol.ConnectedResponse
  362. err = json.Unmarshal(response, &connectedResponse)
  363. if err != nil {
  364. return errors.Trace(err)
  365. }
  366. err = SetKeyValue(
  367. datastoreLastConnectedKey, connectedResponse.ConnectedTimestamp)
  368. if err != nil {
  369. return errors.Trace(err)
  370. }
  371. return nil
  372. }
  373. func getLastConnected() (string, error) {
  374. lastConnected, err := GetKeyValue(datastoreLastConnectedKey)
  375. if err != nil {
  376. return "", errors.Trace(err)
  377. }
  378. if lastConnected == "" {
  379. lastConnected = "None"
  380. }
  381. return lastConnected, nil
  382. }
  383. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  384. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  385. return serverContext.statsRegexps
  386. }
  387. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  388. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  389. params := serverContext.getBaseAPIParameters(baseParametersNoDialParameters)
  390. // Note: ensure putBackStatusRequestPayload is called, to replace
  391. // payload for future attempt, in all failure cases.
  392. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  393. serverContext.tunnel.config,
  394. tunnel.dialParams.ServerEntry.IpAddress)
  395. if err != nil {
  396. return errors.Trace(err)
  397. }
  398. // Skip the request when there's no payload to send.
  399. if len(statusPayload) == 0 {
  400. return nil
  401. }
  402. var response []byte
  403. if serverContext.psiphonHttpsClient == nil {
  404. rawMessage := json.RawMessage(statusPayload)
  405. params["statusData"] = &rawMessage
  406. var request []byte
  407. request, err = serverContext.makeSSHAPIRequestPayload(params)
  408. if err == nil {
  409. response, err = serverContext.tunnel.SendAPIRequest(
  410. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  411. }
  412. } else {
  413. // Legacy web service API request
  414. response, err = serverContext.doPostRequest(
  415. makeRequestUrl(serverContext.tunnel, "", "status", params),
  416. "application/json",
  417. bytes.NewReader(statusPayload))
  418. }
  419. if err != nil {
  420. // Resend the transfer stats and tunnel stats later
  421. // Note: potential duplicate reports if the server received and processed
  422. // the request but the client failed to receive the response.
  423. putBackStatusRequestPayload(statusPayloadInfo)
  424. return errors.Trace(err)
  425. }
  426. confirmStatusRequestPayload(statusPayloadInfo)
  427. var statusResponse protocol.StatusResponse
  428. err = json.Unmarshal(response, &statusResponse)
  429. if err != nil {
  430. return errors.Trace(err)
  431. }
  432. for _, serverEntryTag := range statusResponse.InvalidServerEntryTags {
  433. PruneServerEntry(serverContext.tunnel.config, serverEntryTag)
  434. }
  435. return nil
  436. }
  437. // statusRequestPayloadInfo is a temporary structure for data used to
  438. // either "clear" or "put back" status request payload data depending
  439. // on whether or not the request succeeded.
  440. type statusRequestPayloadInfo struct {
  441. serverId string
  442. transferStats *transferstats.AccumulatedStats
  443. persistentStats map[string][][]byte
  444. }
  445. func makeStatusRequestPayload(
  446. config *Config,
  447. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  448. transferStats := transferstats.TakeOutStatsForServer(serverId)
  449. hostBytes := transferStats.GetStatsForStatusRequest()
  450. persistentStats, err := TakeOutUnreportedPersistentStats(config)
  451. if err != nil {
  452. NoticeWarning(
  453. "TakeOutUnreportedPersistentStats failed: %s", errors.Trace(err))
  454. persistentStats = nil
  455. // Proceed with transferStats only
  456. }
  457. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  458. // There is no payload to send.
  459. return nil, nil, nil
  460. }
  461. payloadInfo := &statusRequestPayloadInfo{
  462. serverId, transferStats, persistentStats}
  463. payload := make(map[string]interface{})
  464. payload["host_bytes"] = hostBytes
  465. // We're not recording these fields, but legacy servers require them.
  466. payload["bytes_transferred"] = 0
  467. payload["page_views"] = make([]string, 0)
  468. payload["https_requests"] = make([]string, 0)
  469. persistentStatPayloadNames := make(map[string]string)
  470. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  471. persistentStatPayloadNames[datastorePersistentStatTypeFailedTunnel] = "failed_tunnel_stats"
  472. for statType, stats := range persistentStats {
  473. // Persistent stats records are already in JSON format
  474. jsonStats := make([]json.RawMessage, len(stats))
  475. for i, stat := range stats {
  476. jsonStats[i] = json.RawMessage(stat)
  477. }
  478. payload[persistentStatPayloadNames[statType]] = jsonStats
  479. }
  480. jsonPayload, err := json.Marshal(payload)
  481. if err != nil {
  482. // Send the transfer stats and tunnel stats later
  483. putBackStatusRequestPayload(payloadInfo)
  484. return nil, nil, errors.Trace(err)
  485. }
  486. return jsonPayload, payloadInfo, nil
  487. }
  488. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  489. transferstats.PutBackStatsForServer(
  490. payloadInfo.serverId, payloadInfo.transferStats)
  491. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  492. if err != nil {
  493. // These persistent stats records won't be resent until after a
  494. // datastore re-initialization.
  495. NoticeWarning(
  496. "PutBackUnreportedPersistentStats failed: %s", errors.Trace(err))
  497. }
  498. }
  499. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  500. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  501. if err != nil {
  502. // These persistent stats records may be resent.
  503. NoticeWarning(
  504. "ClearReportedPersistentStats failed: %s", errors.Trace(err))
  505. }
  506. }
  507. // RecordRemoteServerListStat records a completed common or OSL remote server
  508. // list resource download.
  509. //
  510. // The RSL download event could occur when the client is unable to immediately
  511. // send a status request to a server, so these records are stored in the
  512. // persistent datastore and reported via subsequent status requests sent to
  513. // any Psiphon server.
  514. //
  515. // Note that some common event field values may change between the stat
  516. // recording and reporting, including client geolocation and host_id.
  517. //
  518. // The bytes/duration fields reflect the size and download time for the _last
  519. // chunk only_ in the case of a resumed download. The purpose of these fields
  520. // is to calculate rough data transfer rates. Both bytes and duration are
  521. // included in the log, to allow for filtering out of small transfers which
  522. // may not produce accurate rate numbers.
  523. //
  524. // Multiple "status" requests may be in flight at once (due to multi-tunnel,
  525. // asynchronous final status retry, and aggressive status requests for
  526. // pre-registered tunnels), To avoid duplicate reporting, persistent stats
  527. // records are "taken-out" by a status request and then "put back" in case the
  528. // request fails.
  529. //
  530. // Duplicate reporting may also occur when a server receives and processes a
  531. // status request but the client fails to receive the response.
  532. func RecordRemoteServerListStat(
  533. config *Config,
  534. tunneled bool,
  535. url string,
  536. etag string,
  537. bytes int64,
  538. duration time.Duration,
  539. authenticated bool) error {
  540. if !config.GetParameters().Get().WeightedCoinFlip(
  541. parameters.RecordRemoteServerListPersistentStatsProbability) {
  542. return nil
  543. }
  544. params := make(common.APIParameters)
  545. params["session_id"] = config.SessionID
  546. params["propagation_channel_id"] = config.PropagationChannelId
  547. params["sponsor_id"] = config.GetSponsorID()
  548. params["client_version"] = config.ClientVersion
  549. params["client_platform"] = config.ClientPlatform
  550. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  551. if config.DeviceRegion != "" {
  552. params["device_region"] = config.DeviceRegion
  553. }
  554. params["client_download_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  555. tunneledStr := "0"
  556. if tunneled {
  557. tunneledStr = "1"
  558. }
  559. params["tunneled"] = tunneledStr
  560. params["url"] = url
  561. params["etag"] = etag
  562. params["bytes"] = fmt.Sprintf("%d", bytes)
  563. // duration is nanoseconds; report milliseconds
  564. params["duration"] = fmt.Sprintf("%d", duration/time.Millisecond)
  565. authenticatedStr := "0"
  566. if authenticated {
  567. authenticatedStr = "1"
  568. }
  569. params["authenticated"] = authenticatedStr
  570. remoteServerListStatJson, err := json.Marshal(params)
  571. if err != nil {
  572. return errors.Trace(err)
  573. }
  574. return StorePersistentStat(
  575. config, datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  576. }
  577. // RecordFailedTunnelStat records metrics for a failed tunnel dial, including
  578. // dial parameters and error condition (tunnelErr).
  579. //
  580. // This uses the same reporting facility, with the same caveats, as
  581. // RecordRemoteServerListStat.
  582. func RecordFailedTunnelStat(
  583. config *Config,
  584. dialParams *DialParameters,
  585. livenessTestMetrics *livenessTestMetrics,
  586. bytesUp int64,
  587. bytesDown int64,
  588. tunnelErr error) error {
  589. if !config.GetParameters().Get().WeightedCoinFlip(
  590. parameters.RecordFailedTunnelPersistentStatsProbability) {
  591. return nil
  592. }
  593. lastConnected, err := getLastConnected()
  594. if err != nil {
  595. return errors.Trace(err)
  596. }
  597. params := getBaseAPIParameters(baseParametersAll, config, dialParams)
  598. delete(params, "server_secret")
  599. params["server_entry_tag"] = dialParams.ServerEntry.Tag
  600. params["last_connected"] = lastConnected
  601. params["client_failed_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  602. if livenessTestMetrics != nil {
  603. params["liveness_test_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.UpstreamBytes)
  604. params["liveness_test_sent_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.SentUpstreamBytes)
  605. params["liveness_test_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.DownstreamBytes)
  606. params["liveness_test_received_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.ReceivedDownstreamBytes)
  607. }
  608. if bytesUp >= 0 {
  609. params["bytes_up"] = fmt.Sprintf("%d", bytesUp)
  610. }
  611. if bytesDown >= 0 {
  612. params["bytes_down"] = fmt.Sprintf("%d", bytesDown)
  613. }
  614. // Ensure direct server IPs are not exposed in logs. The "net" package, and
  615. // possibly other 3rd party packages, will include destination addresses in
  616. // I/O error messages.
  617. tunnelError := StripIPAddressesString(tunnelErr.Error())
  618. params["tunnel_error"] = tunnelError
  619. failedTunnelStatJson, err := json.Marshal(params)
  620. if err != nil {
  621. return errors.Trace(err)
  622. }
  623. return StorePersistentStat(
  624. config, datastorePersistentStatTypeFailedTunnel, failedTunnelStatJson)
  625. }
  626. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  627. func (serverContext *ServerContext) doGetRequest(
  628. requestUrl string) (responseBody []byte, err error) {
  629. request, err := http.NewRequest("GET", requestUrl, nil)
  630. if err != nil {
  631. return nil, errors.Trace(err)
  632. }
  633. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  634. response, err := serverContext.psiphonHttpsClient.Do(request)
  635. if err == nil && response.StatusCode != http.StatusOK {
  636. response.Body.Close()
  637. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  638. }
  639. if err != nil {
  640. // Trim this error since it may include long URLs
  641. return nil, errors.Trace(TrimError(err))
  642. }
  643. defer response.Body.Close()
  644. body, err := ioutil.ReadAll(response.Body)
  645. if err != nil {
  646. return nil, errors.Trace(err)
  647. }
  648. return body, nil
  649. }
  650. // doPostRequest makes a tunneled HTTPS POST request.
  651. func (serverContext *ServerContext) doPostRequest(
  652. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  653. request, err := http.NewRequest("POST", requestUrl, body)
  654. if err != nil {
  655. return nil, errors.Trace(err)
  656. }
  657. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  658. request.Header.Set("Content-Type", bodyType)
  659. response, err := serverContext.psiphonHttpsClient.Do(request)
  660. if err == nil && response.StatusCode != http.StatusOK {
  661. response.Body.Close()
  662. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  663. }
  664. if err != nil {
  665. // Trim this error since it may include long URLs
  666. return nil, errors.Trace(TrimError(err))
  667. }
  668. defer response.Body.Close()
  669. responseBody, err = ioutil.ReadAll(response.Body)
  670. if err != nil {
  671. return nil, errors.Trace(err)
  672. }
  673. return responseBody, nil
  674. }
  675. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  676. func (serverContext *ServerContext) makeSSHAPIRequestPayload(
  677. params common.APIParameters) ([]byte, error) {
  678. jsonPayload, err := json.Marshal(params)
  679. if err != nil {
  680. return nil, errors.Trace(err)
  681. }
  682. return jsonPayload, nil
  683. }
  684. type baseParametersFilter int
  685. const (
  686. baseParametersAll baseParametersFilter = iota
  687. baseParametersOnlyUpstreamFragmentorDialParameters
  688. baseParametersNoDialParameters
  689. )
  690. func (serverContext *ServerContext) getBaseAPIParameters(
  691. filter baseParametersFilter) common.APIParameters {
  692. params := getBaseAPIParameters(
  693. filter,
  694. serverContext.tunnel.config,
  695. serverContext.tunnel.dialParams)
  696. // Add a random amount of padding to defend against API call traffic size
  697. // fingerprints. The "pad_response" field instructs the server to pad its
  698. // response accordingly.
  699. p := serverContext.tunnel.config.GetParameters().Get()
  700. minUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMinBytes)
  701. maxUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMaxBytes)
  702. minDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMinBytes)
  703. maxDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMaxBytes)
  704. if maxUpstreamPadding > 0 {
  705. size := serverContext.paddingPRNG.Range(minUpstreamPadding, maxUpstreamPadding)
  706. params["padding"] = strings.Repeat(" ", size)
  707. }
  708. if maxDownstreamPadding > 0 {
  709. size := serverContext.paddingPRNG.Range(minDownstreamPadding, maxDownstreamPadding)
  710. params["pad_response"] = strconv.Itoa(size)
  711. }
  712. return params
  713. }
  714. // getBaseAPIParameters returns all the common API parameters that are
  715. // included with each Psiphon API request. These common parameters are used
  716. // for metrics.
  717. func getBaseAPIParameters(
  718. filter baseParametersFilter,
  719. config *Config,
  720. dialParams *DialParameters) common.APIParameters {
  721. params := make(common.APIParameters)
  722. params["session_id"] = config.SessionID
  723. params["client_session_id"] = config.SessionID
  724. params["server_secret"] = dialParams.ServerEntry.WebServerSecret
  725. params["propagation_channel_id"] = config.PropagationChannelId
  726. params["sponsor_id"] = config.GetSponsorID()
  727. params["client_version"] = config.ClientVersion
  728. params["client_platform"] = config.ClientPlatform
  729. params["client_features"] = config.clientFeatures
  730. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  731. // Blank parameters must be omitted.
  732. if config.DeviceRegion != "" {
  733. params["device_region"] = config.DeviceRegion
  734. }
  735. if filter == baseParametersAll {
  736. params["relay_protocol"] = dialParams.TunnelProtocol
  737. params["network_type"] = dialParams.GetNetworkType()
  738. if dialParams.BPFProgramName != "" {
  739. params["client_bpf"] = dialParams.BPFProgramName
  740. }
  741. if dialParams.SelectedSSHClientVersion {
  742. params["ssh_client_version"] = dialParams.SSHClientVersion
  743. }
  744. if dialParams.UpstreamProxyType != "" {
  745. params["upstream_proxy_type"] = dialParams.UpstreamProxyType
  746. }
  747. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  748. params["upstream_proxy_custom_header_names"] = dialParams.UpstreamProxyCustomHeaderNames
  749. }
  750. if dialParams.FrontingProviderID != "" {
  751. params["fronting_provider_id"] = dialParams.FrontingProviderID
  752. }
  753. if dialParams.MeekDialAddress != "" {
  754. params["meek_dial_address"] = dialParams.MeekDialAddress
  755. }
  756. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  757. if meekResolvedIPAddress != "" {
  758. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  759. }
  760. if dialParams.MeekSNIServerName != "" {
  761. params["meek_sni_server_name"] = dialParams.MeekSNIServerName
  762. }
  763. if dialParams.MeekHostHeader != "" {
  764. params["meek_host_header"] = dialParams.MeekHostHeader
  765. }
  766. // MeekTransformedHostName is meaningful when meek is used, which is when
  767. // MeekDialAddress != ""
  768. if dialParams.MeekDialAddress != "" {
  769. transformedHostName := "0"
  770. if dialParams.MeekTransformedHostName {
  771. transformedHostName = "1"
  772. }
  773. params["meek_transformed_host_name"] = transformedHostName
  774. }
  775. if dialParams.SelectedUserAgent {
  776. params["user_agent"] = dialParams.UserAgent
  777. }
  778. if dialParams.SelectedTLSProfile {
  779. params["tls_profile"] = dialParams.TLSProfile
  780. params["tls_version"] = dialParams.GetTLSVersionForMetrics()
  781. }
  782. if dialParams.ServerEntry.Region != "" {
  783. params["server_entry_region"] = dialParams.ServerEntry.Region
  784. }
  785. if dialParams.ServerEntry.LocalSource != "" {
  786. params["server_entry_source"] = dialParams.ServerEntry.LocalSource
  787. }
  788. // As with last_connected, this timestamp stat, which may be a precise
  789. // handshake request server timestamp, is truncated to hour granularity to
  790. // avoid introducing a reconstructable cross-session user trace into server
  791. // logs.
  792. localServerEntryTimestamp := common.TruncateTimestampToHour(
  793. dialParams.ServerEntry.LocalTimestamp)
  794. if localServerEntryTimestamp != "" {
  795. params["server_entry_timestamp"] = localServerEntryTimestamp
  796. }
  797. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] =
  798. config.GetParameters().Get().Tag()
  799. if dialParams.DialPortNumber != "" {
  800. params["dial_port_number"] = dialParams.DialPortNumber
  801. }
  802. if dialParams.QUICVersion != "" {
  803. params["quic_version"] = dialParams.QUICVersion
  804. }
  805. if dialParams.QUICDialSNIAddress != "" {
  806. params["quic_dial_sni_address"] = dialParams.QUICDialSNIAddress
  807. }
  808. isReplay := "0"
  809. if dialParams.IsReplay {
  810. isReplay = "1"
  811. }
  812. params["is_replay"] = isReplay
  813. if config.EgressRegion != "" {
  814. params["egress_region"] = config.EgressRegion
  815. }
  816. // dialParams.DialDuration is nanoseconds; report milliseconds
  817. params["dial_duration"] = fmt.Sprintf("%d", dialParams.DialDuration/time.Millisecond)
  818. params["candidate_number"] = strconv.Itoa(dialParams.CandidateNumber)
  819. params["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  820. if dialParams.NetworkLatencyMultiplier != 0.0 {
  821. params["network_latency_multiplier"] =
  822. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  823. }
  824. if dialParams.ConjureTransport != "" {
  825. params["conjure_transport"] = dialParams.ConjureTransport
  826. }
  827. if dialParams.DialConnMetrics != nil {
  828. metrics := dialParams.DialConnMetrics.GetMetrics()
  829. for name, value := range metrics {
  830. params[name] = fmt.Sprintf("%v", value)
  831. }
  832. }
  833. if dialParams.ObfuscatedSSHConnMetrics != nil {
  834. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  835. for name, value := range metrics {
  836. params[name] = fmt.Sprintf("%v", value)
  837. }
  838. }
  839. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  840. if dialParams.DialConnMetrics != nil {
  841. names := fragmentor.GetUpstreamMetricsNames()
  842. metrics := dialParams.DialConnMetrics.GetMetrics()
  843. for name, value := range metrics {
  844. if common.Contains(names, name) {
  845. params[name] = fmt.Sprintf("%v", value)
  846. }
  847. }
  848. }
  849. }
  850. return params
  851. }
  852. // makeRequestUrl makes a URL for a web service API request.
  853. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  854. var requestUrl bytes.Buffer
  855. if port == "" {
  856. port = tunnel.dialParams.ServerEntry.WebServerPort
  857. }
  858. requestUrl.WriteString("https://")
  859. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  860. requestUrl.WriteString(":")
  861. requestUrl.WriteString(port)
  862. requestUrl.WriteString("/")
  863. requestUrl.WriteString(path)
  864. if len(params) > 0 {
  865. queryParams := url.Values{}
  866. for name, value := range params {
  867. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  868. // parameter, which has a different type. This parameter is not recognized
  869. // by legacy servers.
  870. switch v := value.(type) {
  871. case string:
  872. queryParams.Set(name, v)
  873. case []string:
  874. // String array param encoded as JSON
  875. jsonValue, err := json.Marshal(v)
  876. if err != nil {
  877. break
  878. }
  879. queryParams.Set(name, string(jsonValue))
  880. }
  881. }
  882. requestUrl.WriteString("?")
  883. requestUrl.WriteString(queryParams.Encode())
  884. }
  885. return requestUrl.String()
  886. }
  887. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  888. // requests and which validates the web server using the Psiphon server entry web server
  889. // certificate.
  890. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  891. certificate, err := DecodeCertificate(
  892. tunnel.dialParams.ServerEntry.WebServerCertificate)
  893. if err != nil {
  894. return nil, errors.Trace(err)
  895. }
  896. tunneledDialer := func(_ context.Context, _, addr string) (net.Conn, error) {
  897. // This case bypasses tunnel.Dial, to avoid its check that the tunnel is
  898. // already active (it won't be pre-handshake). This bypass won't handle the
  899. // server rejecting the port forward due to split tunnel classification, but
  900. // we know that the server won't classify the web API destination as
  901. // untunneled.
  902. return tunnel.sshClient.Dial("tcp", addr)
  903. }
  904. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  905. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  906. // the request. While it's possible to add a timeout here, we leave it with no explicit
  907. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  908. // alives will cause the tunnel to close.
  909. dialer := NewCustomTLSDialer(
  910. &CustomTLSConfig{
  911. Parameters: tunnel.config.GetParameters(),
  912. Dial: tunneledDialer,
  913. VerifyLegacyCertificate: certificate,
  914. })
  915. transport := &http.Transport{
  916. DialTLS: func(network, addr string) (net.Conn, error) {
  917. return dialer(context.Background(), network, addr)
  918. },
  919. Dial: func(network, addr string) (net.Conn, error) {
  920. return nil, errors.TraceNew("HTTP not supported")
  921. },
  922. }
  923. return &http.Client{
  924. Transport: transport,
  925. }, nil
  926. }
  927. func HandleServerRequest(
  928. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  929. switch name {
  930. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  931. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  932. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  933. return HandleAlertRequest(tunnelOwner, tunnel, payload)
  934. }
  935. return errors.Tracef("invalid request name: %s", name)
  936. }
  937. func HandleOSLRequest(
  938. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  939. var oslRequest protocol.OSLRequest
  940. err := json.Unmarshal(payload, &oslRequest)
  941. if err != nil {
  942. return errors.Trace(err)
  943. }
  944. if oslRequest.ClearLocalSLOKs {
  945. DeleteSLOKs()
  946. }
  947. seededNewSLOK := false
  948. for _, slok := range oslRequest.SeedPayload.SLOKs {
  949. duplicate, err := SetSLOK(slok.ID, slok.Key)
  950. if err != nil {
  951. // TODO: return error to trigger retry?
  952. NoticeWarning("SetSLOK failed: %s", errors.Trace(err))
  953. } else if !duplicate {
  954. seededNewSLOK = true
  955. }
  956. if tunnel.config.EmitSLOKs {
  957. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  958. }
  959. }
  960. if seededNewSLOK {
  961. tunnelOwner.SignalSeededNewSLOK()
  962. }
  963. return nil
  964. }
  965. func HandleAlertRequest(
  966. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  967. var alertRequest protocol.AlertRequest
  968. err := json.Unmarshal(payload, &alertRequest)
  969. if err != nil {
  970. return errors.Trace(err)
  971. }
  972. if tunnel.config.EmitServerAlerts {
  973. NoticeServerAlert(alertRequest)
  974. }
  975. return nil
  976. }