serverApi.go 38 KB

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