serverApi.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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, false)
  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. NoticeWarning("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 handshakeResponse.SteeringIP != "" {
  356. if serverContext.tunnel.dialParams.steeringIPCacheKey == "" {
  357. NoticeWarning("unexpected steering IP")
  358. } else {
  359. // Cache any received steering IP, which will also extend the TTL for
  360. // an existing entry.
  361. //
  362. // As typical tunnel duration is short and dialing can be challenging,
  363. // this established tunnel is retained and the steering IP will be
  364. // used on any subsequent dial to the same fronting provider,
  365. // assuming the TTL has not expired.
  366. //
  367. // Note: to avoid TTL expiry for long-lived tunnels, the TTL could be
  368. // set or extended at the end of the tunnel lifetime; however that
  369. // may result in unintended steering.
  370. IP := net.ParseIP(handshakeResponse.SteeringIP)
  371. if IP != nil && !common.IsBogon(IP) {
  372. serverContext.tunnel.dialParams.steeringIPCache.Set(
  373. serverContext.tunnel.dialParams.steeringIPCacheKey,
  374. handshakeResponse.SteeringIP,
  375. lrucache.DefaultExpiration)
  376. } else {
  377. NoticeWarning("ignoring invalid steering IP")
  378. }
  379. }
  380. }
  381. return nil
  382. }
  383. // DoConnectedRequest performs the "connected" API request. This request is
  384. // used for statistics, including unique user counting; reporting the full
  385. // tunnel establishment duration including the handshake request; and updated
  386. // fragmentor metrics.
  387. //
  388. // Users are not assigned identifiers. Instead, daily unique users are
  389. // calculated by having clients submit their last connected timestamp
  390. // (truncated to an hour, as a privacy measure). As client clocks are
  391. // unreliable, the server returns new last_connected values for the client to
  392. // store and send next time it connects.
  393. func (serverContext *ServerContext) DoConnectedRequest() error {
  394. // Limitation: as currently implemented, the last_connected exchange isn't a
  395. // distributed, atomic operation. When clients send the connected request,
  396. // the server may receive the request, count a unique user based on the
  397. // client's last_connected, and then the tunnel fails before the client
  398. // receives the response, so the client will not update its last_connected
  399. // value and submit the same one again, resulting in an inflated unique user
  400. // count.
  401. //
  402. // The SetInFlightConnectedRequest mechanism mitigates one class of connected
  403. // request interruption, a commanded shutdown in the middle of a connected
  404. // request, by allowing some time for the request to complete before
  405. // terminating the tunnel.
  406. //
  407. // TODO: consider extending the connected request protocol with additional
  408. // "acknowledgment" messages so that the server does not commit its unique
  409. // user count until after the client has acknowledged receipt and durable
  410. // storage of the new last_connected value.
  411. requestDone := make(chan struct{})
  412. defer close(requestDone)
  413. if !serverContext.tunnel.SetInFlightConnectedRequest(requestDone) {
  414. return errors.TraceNew("tunnel is closing")
  415. }
  416. defer serverContext.tunnel.SetInFlightConnectedRequest(nil)
  417. params := serverContext.getBaseAPIParameters(
  418. baseParametersOnlyUpstreamFragmentorDialParameters, false)
  419. lastConnected, err := getLastConnected()
  420. if err != nil {
  421. return errors.Trace(err)
  422. }
  423. params["last_connected"] = lastConnected
  424. // serverContext.tunnel.establishDuration is nanoseconds; report milliseconds
  425. params["establishment_duration"] =
  426. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/time.Millisecond)
  427. var response []byte
  428. if serverContext.psiphonHttpsClient == nil {
  429. request, err := serverContext.makeSSHAPIRequestPayload(params)
  430. if err != nil {
  431. return errors.Trace(err)
  432. }
  433. response, err = serverContext.tunnel.SendAPIRequest(
  434. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  435. if err != nil {
  436. return errors.Trace(err)
  437. }
  438. } else {
  439. // Legacy web service API request
  440. response, err = serverContext.doGetRequest(
  441. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  442. if err != nil {
  443. return errors.Trace(err)
  444. }
  445. }
  446. var connectedResponse protocol.ConnectedResponse
  447. err = json.Unmarshal(response, &connectedResponse)
  448. if err != nil {
  449. return errors.Trace(err)
  450. }
  451. err = SetKeyValue(
  452. datastoreLastConnectedKey, connectedResponse.ConnectedTimestamp)
  453. if err != nil {
  454. return errors.Trace(err)
  455. }
  456. return nil
  457. }
  458. func getLastConnected() (string, error) {
  459. lastConnected, err := GetKeyValue(datastoreLastConnectedKey)
  460. if err != nil {
  461. return "", errors.Trace(err)
  462. }
  463. if lastConnected == "" {
  464. lastConnected = "None"
  465. }
  466. return lastConnected, nil
  467. }
  468. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  469. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  470. return serverContext.statsRegexps
  471. }
  472. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  473. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  474. params := serverContext.getBaseAPIParameters(
  475. baseParametersNoDialParameters, false)
  476. // Note: ensure putBackStatusRequestPayload is called, to replace
  477. // payload for future attempt, in all failure cases.
  478. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  479. serverContext.tunnel.config,
  480. tunnel.dialParams.ServerEntry.IpAddress)
  481. if err != nil {
  482. return errors.Trace(err)
  483. }
  484. // Skip the request when there's no payload to send.
  485. if len(statusPayload) == 0 {
  486. return nil
  487. }
  488. var response []byte
  489. if serverContext.psiphonHttpsClient == nil {
  490. rawMessage := json.RawMessage(statusPayload)
  491. params["statusData"] = &rawMessage
  492. var request []byte
  493. request, err = serverContext.makeSSHAPIRequestPayload(params)
  494. if err == nil {
  495. response, err = serverContext.tunnel.SendAPIRequest(
  496. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  497. }
  498. } else {
  499. // Legacy web service API request
  500. response, err = serverContext.doPostRequest(
  501. makeRequestUrl(serverContext.tunnel, "", "status", params),
  502. "application/json",
  503. bytes.NewReader(statusPayload))
  504. }
  505. if err != nil {
  506. // Resend the transfer stats and tunnel stats later
  507. // Note: potential duplicate reports if the server received and processed
  508. // the request but the client failed to receive the response.
  509. putBackStatusRequestPayload(statusPayloadInfo)
  510. return errors.Trace(err)
  511. }
  512. confirmStatusRequestPayload(statusPayloadInfo)
  513. var statusResponse protocol.StatusResponse
  514. err = json.Unmarshal(response, &statusResponse)
  515. if err != nil {
  516. return errors.Trace(err)
  517. }
  518. for _, serverEntryTag := range statusResponse.InvalidServerEntryTags {
  519. PruneServerEntry(serverContext.tunnel.config, serverEntryTag)
  520. }
  521. return nil
  522. }
  523. // statusRequestPayloadInfo is a temporary structure for data used to
  524. // either "clear" or "put back" status request payload data depending
  525. // on whether or not the request succeeded.
  526. type statusRequestPayloadInfo struct {
  527. serverId string
  528. transferStats *transferstats.AccumulatedStats
  529. persistentStats map[string][][]byte
  530. }
  531. func makeStatusRequestPayload(
  532. config *Config,
  533. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  534. // The status request payload is always JSON encoded. As it is sent after
  535. // the initial handshake and is multiplexed with other tunnel traffic,
  536. // its size is less of a fingerprinting concern.
  537. //
  538. // TODO: pack and CBOR encode the status request payload.
  539. transferStats := transferstats.TakeOutStatsForServer(serverId)
  540. hostBytes := transferStats.GetStatsForStatusRequest()
  541. persistentStats, err := TakeOutUnreportedPersistentStats(config)
  542. if err != nil {
  543. NoticeWarning(
  544. "TakeOutUnreportedPersistentStats failed: %s", errors.Trace(err))
  545. persistentStats = nil
  546. // Proceed with transferStats only
  547. }
  548. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  549. // There is no payload to send.
  550. return nil, nil, nil
  551. }
  552. payloadInfo := &statusRequestPayloadInfo{
  553. serverId, transferStats, persistentStats}
  554. payload := make(map[string]interface{})
  555. payload["host_bytes"] = hostBytes
  556. // We're not recording these fields, but legacy servers require them.
  557. payload["bytes_transferred"] = 0
  558. payload["page_views"] = make([]string, 0)
  559. payload["https_requests"] = make([]string, 0)
  560. persistentStatPayloadNames := make(map[string]string)
  561. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  562. persistentStatPayloadNames[datastorePersistentStatTypeFailedTunnel] = "failed_tunnel_stats"
  563. for statType, stats := range persistentStats {
  564. // Persistent stats records are already in JSON format
  565. jsonStats := make([]json.RawMessage, len(stats))
  566. for i, stat := range stats {
  567. jsonStats[i] = json.RawMessage(stat)
  568. }
  569. payload[persistentStatPayloadNames[statType]] = jsonStats
  570. }
  571. jsonPayload, err := json.Marshal(payload)
  572. if err != nil {
  573. // Send the transfer stats and tunnel stats later
  574. putBackStatusRequestPayload(payloadInfo)
  575. return nil, nil, errors.Trace(err)
  576. }
  577. return jsonPayload, payloadInfo, nil
  578. }
  579. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  580. transferstats.PutBackStatsForServer(
  581. payloadInfo.serverId, payloadInfo.transferStats)
  582. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  583. if err != nil {
  584. // These persistent stats records won't be resent until after a
  585. // datastore re-initialization.
  586. NoticeWarning(
  587. "PutBackUnreportedPersistentStats failed: %s", errors.Trace(err))
  588. }
  589. }
  590. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  591. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  592. if err != nil {
  593. // These persistent stats records may be resent.
  594. NoticeWarning(
  595. "ClearReportedPersistentStats failed: %s", errors.Trace(err))
  596. }
  597. }
  598. // RecordRemoteServerListStat records a completed common or OSL remote server
  599. // list resource download.
  600. //
  601. // The RSL download event could occur when the client is unable to immediately
  602. // send a status request to a server, so these records are stored in the
  603. // persistent datastore and reported via subsequent status requests sent to
  604. // any Psiphon server.
  605. //
  606. // Note that some common event field values may change between the stat
  607. // recording and reporting, including client geolocation and host_id.
  608. //
  609. // The bytes/duration fields reflect the size and download time for the _last
  610. // chunk only_ in the case of a resumed download. The purpose of these fields
  611. // is to calculate rough data transfer rates. Both bytes and duration are
  612. // included in the log, to allow for filtering out of small transfers which
  613. // may not produce accurate rate numbers.
  614. //
  615. // Multiple "status" requests may be in flight at once (due to multi-tunnel,
  616. // asynchronous final status retry, and aggressive status requests for
  617. // pre-registered tunnels), To avoid duplicate reporting, persistent stats
  618. // records are "taken-out" by a status request and then "put back" in case the
  619. // request fails.
  620. //
  621. // Duplicate reporting may also occur when a server receives and processes a
  622. // status request but the client fails to receive the response.
  623. func RecordRemoteServerListStat(
  624. config *Config,
  625. tunneled bool,
  626. url string,
  627. etag string,
  628. bytes int64,
  629. duration time.Duration,
  630. authenticated bool,
  631. additionalParameters common.APIParameters) error {
  632. if !config.GetParameters().Get().WeightedCoinFlip(
  633. parameters.RecordRemoteServerListPersistentStatsProbability) {
  634. return nil
  635. }
  636. params := make(common.APIParameters)
  637. params["session_id"] = config.SessionID
  638. params["propagation_channel_id"] = config.PropagationChannelId
  639. params["sponsor_id"] = config.GetSponsorID()
  640. params["client_version"] = config.ClientVersion
  641. params["client_platform"] = config.ClientPlatform
  642. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  643. if config.DeviceRegion != "" {
  644. params["device_region"] = config.DeviceRegion
  645. }
  646. if config.DeviceLocation != "" {
  647. params["device_location"] = config.DeviceLocation
  648. }
  649. params["client_download_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  650. tunneledStr := "0"
  651. if tunneled {
  652. tunneledStr = "1"
  653. }
  654. params["tunneled"] = tunneledStr
  655. params["url"] = url
  656. params["etag"] = etag
  657. params["bytes"] = fmt.Sprintf("%d", bytes)
  658. // duration is nanoseconds; report milliseconds
  659. params["duration"] = fmt.Sprintf("%d", duration/time.Millisecond)
  660. authenticatedStr := "0"
  661. if authenticated {
  662. authenticatedStr = "1"
  663. }
  664. params["authenticated"] = authenticatedStr
  665. for k, v := range additionalParameters {
  666. params[k] = v
  667. }
  668. remoteServerListStatJson, err := json.Marshal(params)
  669. if err != nil {
  670. return errors.Trace(err)
  671. }
  672. return StorePersistentStat(
  673. config, datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  674. }
  675. // RecordFailedTunnelStat records metrics for a failed tunnel dial, including
  676. // dial parameters and error condition (tunnelErr). No record is created when
  677. // tunnelErr is nil.
  678. //
  679. // This uses the same reporting facility, with the same caveats, as
  680. // RecordRemoteServerListStat.
  681. func RecordFailedTunnelStat(
  682. config *Config,
  683. dialParams *DialParameters,
  684. livenessTestMetrics *livenessTestMetrics,
  685. bytesUp int64,
  686. bytesDown int64,
  687. tunnelErr error) error {
  688. probability := config.GetParameters().Get().Float(
  689. parameters.RecordFailedTunnelPersistentStatsProbability)
  690. if !prng.FlipWeightedCoin(probability) {
  691. return nil
  692. }
  693. // Callers should not call RecordFailedTunnelStat with a nil tunnelErr, as
  694. // this is not a useful stat and it results in a nil pointer dereference.
  695. // This check catches potential bug cases. An example edge case, now
  696. // fixed, is deferred error handlers, such as the ones in in
  697. // dialTunnel/tunnel.Activate, which may be invoked in the case of a
  698. // panic, which can occur before any error value is returned.
  699. if tunnelErr == nil {
  700. return errors.TraceNew("no error")
  701. }
  702. lastConnected, err := getLastConnected()
  703. if err != nil {
  704. return errors.Trace(err)
  705. }
  706. params := getBaseAPIParameters(baseParametersAll, true, config, dialParams)
  707. delete(params, "server_secret")
  708. params["server_entry_tag"] = dialParams.ServerEntry.Tag
  709. params["last_connected"] = lastConnected
  710. params["client_failed_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  711. if livenessTestMetrics != nil {
  712. params["liveness_test_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.UpstreamBytes)
  713. params["liveness_test_sent_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.SentUpstreamBytes)
  714. params["liveness_test_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.DownstreamBytes)
  715. params["liveness_test_received_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.ReceivedDownstreamBytes)
  716. }
  717. if bytesUp >= 0 {
  718. params["bytes_up"] = fmt.Sprintf("%d", bytesUp)
  719. }
  720. if bytesDown >= 0 {
  721. params["bytes_down"] = fmt.Sprintf("%d", bytesDown)
  722. }
  723. // Log RecordFailedTunnelPersistentStatsProbability to indicate the
  724. // proportion of failed tunnel events being recorded at the time of
  725. // this log event.
  726. params["record_probability"] = fmt.Sprintf("%f", probability)
  727. // Ensure direct server IPs are not exposed in logs. The "net" package, and
  728. // possibly other 3rd party packages, will include destination addresses in
  729. // I/O error messages.
  730. tunnelError := common.RedactIPAddressesString(tunnelErr.Error())
  731. params["tunnel_error"] = tunnelError
  732. failedTunnelStatJson, err := json.Marshal(params)
  733. if err != nil {
  734. return errors.Trace(err)
  735. }
  736. return StorePersistentStat(
  737. config, datastorePersistentStatTypeFailedTunnel, failedTunnelStatJson)
  738. }
  739. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  740. func (serverContext *ServerContext) doGetRequest(
  741. requestUrl string) (responseBody []byte, err error) {
  742. request, err := http.NewRequest("GET", requestUrl, nil)
  743. if err != nil {
  744. return nil, errors.Trace(err)
  745. }
  746. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  747. response, err := serverContext.psiphonHttpsClient.Do(request)
  748. if err == nil && response.StatusCode != http.StatusOK {
  749. response.Body.Close()
  750. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  751. }
  752. if err != nil {
  753. // Trim this error since it may include long URLs
  754. return nil, errors.Trace(TrimError(err))
  755. }
  756. defer response.Body.Close()
  757. body, err := ioutil.ReadAll(response.Body)
  758. if err != nil {
  759. return nil, errors.Trace(err)
  760. }
  761. return body, nil
  762. }
  763. // doPostRequest makes a tunneled HTTPS POST request.
  764. func (serverContext *ServerContext) doPostRequest(
  765. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  766. request, err := http.NewRequest("POST", requestUrl, body)
  767. if err != nil {
  768. return nil, errors.Trace(err)
  769. }
  770. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  771. request.Header.Set("Content-Type", bodyType)
  772. response, err := serverContext.psiphonHttpsClient.Do(request)
  773. if err == nil && response.StatusCode != http.StatusOK {
  774. response.Body.Close()
  775. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  776. }
  777. if err != nil {
  778. // Trim this error since it may include long URLs
  779. return nil, errors.Trace(TrimError(err))
  780. }
  781. defer response.Body.Close()
  782. responseBody, err = ioutil.ReadAll(response.Body)
  783. if err != nil {
  784. return nil, errors.Trace(err)
  785. }
  786. return responseBody, nil
  787. }
  788. // makeSSHAPIRequestPayload makes an encoded payload for an SSH API request.
  789. func (serverContext *ServerContext) makeSSHAPIRequestPayload(
  790. params common.APIParameters) ([]byte, error) {
  791. // CBOR encoding is the default and is preferred as its smaller size gives
  792. // more space for variable padding to mitigate potential fingerprinting
  793. // based on API message sizes.
  794. if !serverContext.tunnel.dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  795. serverContext.tunnel.config.TargetAPIEncoding == protocol.PSIPHON_API_ENCODING_JSON {
  796. jsonPayload, err := json.Marshal(params)
  797. if err != nil {
  798. return nil, errors.Trace(err)
  799. }
  800. return jsonPayload, nil
  801. }
  802. payload, err := protocol.MakePackedAPIParametersRequestPayload(params)
  803. if err != nil {
  804. return nil, errors.Trace(err)
  805. }
  806. return payload, nil
  807. }
  808. type baseParametersFilter int
  809. const (
  810. baseParametersAll baseParametersFilter = iota
  811. baseParametersOnlyUpstreamFragmentorDialParameters
  812. baseParametersNoDialParameters
  813. )
  814. func (serverContext *ServerContext) getBaseAPIParameters(
  815. filter baseParametersFilter,
  816. includeSessionID bool) common.APIParameters {
  817. params := getBaseAPIParameters(
  818. filter,
  819. includeSessionID,
  820. serverContext.tunnel.config,
  821. serverContext.tunnel.dialParams)
  822. // Add a random amount of padding to defend against API call traffic size
  823. // fingerprints. The "pad_response" field instructs the server to pad its
  824. // response accordingly.
  825. p := serverContext.tunnel.config.GetParameters().Get()
  826. minUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMinBytes)
  827. maxUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMaxBytes)
  828. minDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMinBytes)
  829. maxDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMaxBytes)
  830. if maxUpstreamPadding > 0 {
  831. size := serverContext.paddingPRNG.Range(minUpstreamPadding, maxUpstreamPadding)
  832. params["padding"] = strings.Repeat(" ", size)
  833. }
  834. if maxDownstreamPadding > 0 {
  835. size := serverContext.paddingPRNG.Range(minDownstreamPadding, maxDownstreamPadding)
  836. params["pad_response"] = strconv.Itoa(size)
  837. }
  838. return params
  839. }
  840. // getBaseAPIParameters returns all the common API parameters that are
  841. // included with each Psiphon API request. These common parameters are used
  842. // for metrics.
  843. //
  844. // The input dialPatrams may be nil when the filter has
  845. // baseParametersNoDialParameters.
  846. func getBaseAPIParameters(
  847. filter baseParametersFilter,
  848. includeSessionID bool,
  849. config *Config,
  850. dialParams *DialParameters) common.APIParameters {
  851. params := make(common.APIParameters)
  852. if includeSessionID {
  853. // The session ID is included in non-SSH API requests only. For SSH
  854. // API requests, the Psiphon server already has the client's session ID.
  855. params["session_id"] = config.SessionID
  856. }
  857. params["propagation_channel_id"] = config.PropagationChannelId
  858. params["sponsor_id"] = config.GetSponsorID()
  859. params["client_version"] = config.ClientVersion
  860. params["client_platform"] = config.ClientPlatform
  861. params["client_features"] = config.clientFeatures
  862. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  863. if dialParams != nil {
  864. // Prefer the dialParams network ID snapshot if available.
  865. params["network_type"] = dialParams.GetNetworkType()
  866. } else {
  867. params["network_type"] = GetNetworkType(config.GetNetworkID())
  868. }
  869. // TODO: snapshot tactics tag used when dialParams initialized.
  870. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] =
  871. config.GetParameters().Get().Tag()
  872. // The server secret is deprecated and included only in legacy JSON
  873. // encoded API messages for backwards compatibility. SSH login proves
  874. // client possession of the server entry; the server secret was for the
  875. // legacy web API with no SSH login. Note that we can't check
  876. // dialParams.ServerEntry in the baseParametersNoDialParameters case, but
  877. // that case is used by in-proxy dials, which implies support.
  878. if dialParams != nil {
  879. if !dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  880. config.TargetAPIEncoding == protocol.PSIPHON_API_ENCODING_JSON {
  881. params["server_secret"] = dialParams.ServerEntry.WebServerSecret
  882. }
  883. }
  884. // Blank parameters must be omitted.
  885. if config.DeviceRegion != "" {
  886. params["device_region"] = config.DeviceRegion
  887. }
  888. if config.DeviceLocation != "" {
  889. params["device_location"] = config.DeviceLocation
  890. }
  891. if filter == baseParametersAll {
  892. if protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  893. inproxyConn := dialParams.inproxyConn.Load()
  894. if inproxyConn != nil {
  895. params["inproxy_connection_id"] =
  896. inproxyConn.(*inproxy.ClientConn).GetConnectionID()
  897. }
  898. }
  899. params["relay_protocol"] = dialParams.TunnelProtocol
  900. if dialParams.BPFProgramName != "" {
  901. params["client_bpf"] = dialParams.BPFProgramName
  902. }
  903. if dialParams.SelectedSSHClientVersion {
  904. params["ssh_client_version"] = dialParams.SSHClientVersion
  905. }
  906. if dialParams.UpstreamProxyType != "" {
  907. params["upstream_proxy_type"] = dialParams.UpstreamProxyType
  908. }
  909. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  910. params["upstream_proxy_custom_header_names"] = dialParams.UpstreamProxyCustomHeaderNames
  911. }
  912. if dialParams.FrontingProviderID != "" {
  913. params["fronting_provider_id"] = dialParams.FrontingProviderID
  914. }
  915. if dialParams.MeekDialAddress != "" {
  916. params["meek_dial_address"] = dialParams.MeekDialAddress
  917. }
  918. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  919. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  920. if meekResolvedIPAddress != "" {
  921. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  922. }
  923. }
  924. if dialParams.MeekSNIServerName != "" {
  925. params["meek_sni_server_name"] = dialParams.MeekSNIServerName
  926. }
  927. if dialParams.MeekHostHeader != "" {
  928. params["meek_host_header"] = dialParams.MeekHostHeader
  929. }
  930. // MeekTransformedHostName is meaningful when meek is used, which is when
  931. // MeekDialAddress != ""
  932. if dialParams.MeekDialAddress != "" {
  933. transformedHostName := "0"
  934. if dialParams.MeekTransformedHostName {
  935. transformedHostName = "1"
  936. }
  937. params["meek_transformed_host_name"] = transformedHostName
  938. }
  939. if dialParams.TLSOSSHSNIServerName != "" {
  940. params["tls_ossh_sni_server_name"] = dialParams.TLSOSSHSNIServerName
  941. }
  942. if dialParams.TLSOSSHTransformedSNIServerName {
  943. params["tls_ossh_transformed_host_name"] = "1"
  944. }
  945. if dialParams.TLSFragmentClientHello {
  946. params["tls_fragmented"] = "1"
  947. }
  948. if dialParams.SelectedUserAgent {
  949. params["user_agent"] = dialParams.UserAgent
  950. }
  951. if dialParams.SelectedTLSProfile {
  952. params["tls_profile"] = dialParams.TLSProfile
  953. params["tls_version"] = dialParams.GetTLSVersionForMetrics()
  954. }
  955. if dialParams.ServerEntry.Region != "" {
  956. params["server_entry_region"] = dialParams.ServerEntry.Region
  957. }
  958. if dialParams.ServerEntry.LocalSource != "" {
  959. params["server_entry_source"] = dialParams.ServerEntry.LocalSource
  960. }
  961. // As with last_connected, this timestamp stat, which may be a precise
  962. // handshake request server timestamp, is truncated to hour granularity to
  963. // avoid introducing a reconstructable cross-session user trace into server
  964. // logs.
  965. localServerEntryTimestamp := common.TruncateTimestampToHour(
  966. dialParams.ServerEntry.LocalTimestamp)
  967. if localServerEntryTimestamp != "" {
  968. params["server_entry_timestamp"] = localServerEntryTimestamp
  969. }
  970. if dialParams.DialPortNumber != "" {
  971. params["dial_port_number"] = dialParams.DialPortNumber
  972. }
  973. if dialParams.QUICVersion != "" {
  974. params["quic_version"] = dialParams.QUICVersion
  975. }
  976. if dialParams.QUICDialSNIAddress != "" {
  977. params["quic_dial_sni_address"] = dialParams.QUICDialSNIAddress
  978. }
  979. if dialParams.QUICDisablePathMTUDiscovery {
  980. params["quic_disable_client_path_mtu_discovery"] = "1"
  981. }
  982. isReplay := "0"
  983. if dialParams.IsReplay {
  984. isReplay = "1"
  985. }
  986. params["is_replay"] = isReplay
  987. if config.EgressRegion != "" {
  988. params["egress_region"] = config.EgressRegion
  989. }
  990. // dialParams.DialDuration is nanoseconds; report milliseconds
  991. params["dial_duration"] = fmt.Sprintf("%d", dialParams.DialDuration/time.Millisecond)
  992. params["candidate_number"] = strconv.Itoa(dialParams.CandidateNumber)
  993. params["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  994. if dialParams.NetworkLatencyMultiplier != 0.0 {
  995. params["network_latency_multiplier"] =
  996. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  997. }
  998. if dialParams.ConjureTransport != "" {
  999. params["conjure_transport"] = dialParams.ConjureTransport
  1000. }
  1001. usedSteeringIP := false
  1002. if dialParams.SteeringIP != "" {
  1003. params["steering_ip"] = dialParams.SteeringIP
  1004. usedSteeringIP = true
  1005. }
  1006. if dialParams.ResolveParameters != nil && !usedSteeringIP {
  1007. // Log enough information to distinguish several successful or
  1008. // failed circumvention cases of interest, including preferring
  1009. // alternate servers and/or using DNS protocol transforms, and
  1010. // appropriate for both handshake and failed_tunnel logging:
  1011. //
  1012. // - The initial attempt made by Resolver.ResolveIP,
  1013. // preferring an alternate DNS server and/or using a
  1014. // protocol transform succeeds (dns_result = 0, the initial
  1015. // attempt, 0, got the first result).
  1016. //
  1017. // - A second attempt may be used, still preferring an
  1018. // alternate DNS server but no longer using the protocol
  1019. // transform, which presumably failed (dns_result = 1, the
  1020. // second attempt, 1, got the first result).
  1021. //
  1022. // - Subsequent attempts will use the system DNS server and no
  1023. // protocol transforms (dns_result > 2).
  1024. //
  1025. // Due to the design of Resolver.ResolveIP, the notion
  1026. // of "success" is approximate; for example a successful
  1027. // response may arrive after a subsequent attempt succeeds,
  1028. // simply due to slow network conditions. It's also possible
  1029. // that, for a given attemp, only one of the two concurrent
  1030. // requests (A and AAAA) succeeded.
  1031. //
  1032. // Note that ResolveParameters.GetFirstAttemptWithAnswer
  1033. // semantics assume that dialParams.ResolveParameters wasn't
  1034. // used by or modified by any other dial.
  1035. //
  1036. // Some protocols may use both preresolved DNS as well as actual
  1037. // DNS requests, such as Conjure with the DTLS transport, which
  1038. // may resolve STUN server domains while using preresolved DNS
  1039. // for fronted API registration.
  1040. if dialParams.ResolveParameters.PreresolvedIPAddress != "" {
  1041. meekDialDomain, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  1042. if dialParams.ResolveParameters.PreresolvedDomain == meekDialDomain {
  1043. params["dns_preresolved"] = dialParams.ResolveParameters.PreresolvedIPAddress
  1044. }
  1045. }
  1046. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  1047. params["dns_preferred"] = dialParams.ResolveParameters.AlternateDNSServer
  1048. }
  1049. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  1050. params["dns_transform"] = dialParams.ResolveParameters.ProtocolTransformName
  1051. }
  1052. params["dns_attempt"] = strconv.Itoa(
  1053. dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  1054. }
  1055. if dialParams.HTTPTransformerParameters != nil {
  1056. if dialParams.HTTPTransformerParameters.ProtocolTransformSpec != nil {
  1057. params["http_transform"] = dialParams.HTTPTransformerParameters.ProtocolTransformName
  1058. }
  1059. }
  1060. if dialParams.OSSHObfuscatorSeedTransformerParameters != nil {
  1061. if dialParams.OSSHObfuscatorSeedTransformerParameters.TransformSpec != nil {
  1062. params["seed_transform"] = dialParams.OSSHObfuscatorSeedTransformerParameters.TransformName
  1063. }
  1064. }
  1065. if dialParams.ObfuscatedQUICNonceTransformerParameters != nil {
  1066. if dialParams.ObfuscatedQUICNonceTransformerParameters.TransformSpec != nil {
  1067. params["seed_transform"] = dialParams.ObfuscatedQUICNonceTransformerParameters.TransformName
  1068. }
  1069. }
  1070. if dialParams.OSSHPrefixSpec != nil {
  1071. if dialParams.OSSHPrefixSpec.Spec != nil {
  1072. params["ossh_prefix"] = dialParams.OSSHPrefixSpec.Name
  1073. }
  1074. }
  1075. if dialParams.DialConnMetrics != nil {
  1076. metrics := dialParams.DialConnMetrics.GetMetrics()
  1077. for name, value := range metrics {
  1078. params[name] = fmt.Sprintf("%v", value)
  1079. }
  1080. }
  1081. if dialParams.ObfuscatedSSHConnMetrics != nil {
  1082. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  1083. for name, value := range metrics {
  1084. params[name] = fmt.Sprintf("%v", value)
  1085. }
  1086. }
  1087. if protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  1088. metrics := dialParams.GetInproxyMetrics()
  1089. for name, value := range metrics {
  1090. params[name] = fmt.Sprintf("%v", value)
  1091. }
  1092. }
  1093. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  1094. if dialParams.DialConnMetrics != nil {
  1095. names := fragmentor.GetUpstreamMetricsNames()
  1096. metrics := dialParams.DialConnMetrics.GetMetrics()
  1097. for name, value := range metrics {
  1098. if common.Contains(names, name) {
  1099. params[name] = fmt.Sprintf("%v", value)
  1100. }
  1101. }
  1102. }
  1103. }
  1104. return params
  1105. }
  1106. // makeRequestUrl makes a URL for a web service API request.
  1107. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  1108. var requestUrl bytes.Buffer
  1109. if port == "" {
  1110. port = tunnel.dialParams.ServerEntry.WebServerPort
  1111. }
  1112. requestUrl.WriteString("https://")
  1113. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  1114. requestUrl.WriteString(":")
  1115. requestUrl.WriteString(port)
  1116. requestUrl.WriteString("/")
  1117. requestUrl.WriteString(path)
  1118. if len(params) > 0 {
  1119. queryParams := url.Values{}
  1120. for name, value := range params {
  1121. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  1122. // parameter, which has a different type. This parameter is not recognized
  1123. // by legacy servers.
  1124. switch v := value.(type) {
  1125. case string:
  1126. queryParams.Set(name, v)
  1127. case []string:
  1128. // String array param encoded as JSON
  1129. jsonValue, err := json.Marshal(v)
  1130. if err != nil {
  1131. break
  1132. }
  1133. queryParams.Set(name, string(jsonValue))
  1134. }
  1135. }
  1136. requestUrl.WriteString("?")
  1137. requestUrl.WriteString(queryParams.Encode())
  1138. }
  1139. return requestUrl.String()
  1140. }
  1141. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  1142. // requests and which validates the web server using the Psiphon server entry web server
  1143. // certificate.
  1144. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  1145. certificate, err := DecodeCertificate(
  1146. tunnel.dialParams.ServerEntry.WebServerCertificate)
  1147. if err != nil {
  1148. return nil, errors.Trace(err)
  1149. }
  1150. tunneledDialer := func(_ context.Context, _, addr string) (net.Conn, error) {
  1151. // This case bypasses tunnel.Dial, to avoid its check that the tunnel is
  1152. // already active (it won't be pre-handshake). This bypass won't handle the
  1153. // server rejecting the port forward due to split tunnel classification, but
  1154. // we know that the server won't classify the web API destination as
  1155. // untunneled.
  1156. return tunnel.sshClient.Dial("tcp", addr)
  1157. }
  1158. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  1159. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  1160. // the request. While it's possible to add a timeout here, we leave it with no explicit
  1161. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  1162. // alives will cause the tunnel to close.
  1163. dialer := NewCustomTLSDialer(
  1164. &CustomTLSConfig{
  1165. Parameters: tunnel.config.GetParameters(),
  1166. Dial: tunneledDialer,
  1167. VerifyLegacyCertificate: certificate,
  1168. })
  1169. transport := &http.Transport{
  1170. DialTLS: func(network, addr string) (net.Conn, error) {
  1171. return dialer(context.Background(), network, addr)
  1172. },
  1173. Dial: func(network, addr string) (net.Conn, error) {
  1174. return nil, errors.TraceNew("HTTP not supported")
  1175. },
  1176. }
  1177. return &http.Client{
  1178. Transport: transport,
  1179. }, nil
  1180. }
  1181. func HandleServerRequest(
  1182. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) {
  1183. var err error
  1184. switch request.Type {
  1185. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  1186. err = HandleOSLRequest(tunnelOwner, tunnel, request)
  1187. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  1188. err = HandleAlertRequest(tunnelOwner, tunnel, request)
  1189. default:
  1190. err = errors.Tracef("invalid request name")
  1191. }
  1192. if err != nil {
  1193. NoticeWarning(
  1194. "HandleServerRequest for %s failed: %s", request.Type, errors.Trace(err))
  1195. }
  1196. }
  1197. func HandleOSLRequest(
  1198. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1199. defer func() {
  1200. if retErr != nil {
  1201. request.Reply(false, nil)
  1202. }
  1203. }()
  1204. var oslRequest protocol.OSLRequest
  1205. err := json.Unmarshal(request.Payload, &oslRequest)
  1206. if err != nil {
  1207. return errors.Trace(err)
  1208. }
  1209. if oslRequest.ClearLocalSLOKs {
  1210. DeleteSLOKs()
  1211. }
  1212. seededNewSLOK := false
  1213. for _, slok := range oslRequest.SeedPayload.SLOKs {
  1214. duplicate, err := SetSLOK(slok.ID, slok.Key)
  1215. if err != nil {
  1216. // TODO: return error to trigger retry?
  1217. NoticeWarning("SetSLOK failed: %s", errors.Trace(err))
  1218. } else if !duplicate {
  1219. seededNewSLOK = true
  1220. }
  1221. if tunnel.config.EmitSLOKs {
  1222. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  1223. }
  1224. }
  1225. if seededNewSLOK {
  1226. tunnelOwner.SignalSeededNewSLOK()
  1227. }
  1228. request.Reply(true, nil)
  1229. return nil
  1230. }
  1231. func HandleAlertRequest(
  1232. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1233. defer func() {
  1234. if retErr != nil {
  1235. request.Reply(false, nil)
  1236. }
  1237. }()
  1238. var alertRequest protocol.AlertRequest
  1239. err := json.Unmarshal(request.Payload, &alertRequest)
  1240. if err != nil {
  1241. return errors.Trace(err)
  1242. }
  1243. if tunnel.config.EmitServerAlerts {
  1244. NoticeServerAlert(alertRequest)
  1245. }
  1246. request.Reply(true, nil)
  1247. return nil
  1248. }