serverApi.go 45 KB

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