serverApi.go 44 KB

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