serverApi.go 49 KB

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