serverApi.go 42 KB

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