serverApi.go 43 KB

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