serverApi.go 37 KB

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