serverApi.go 37 KB

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