serverApi.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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, HoldOffDirectTunnelProviderRegions,
  130. // RestrictInproxyProviderRegions, and HoldOffInproxyTunnelProviderRegions
  131. // tactics.
  132. //
  133. // The server entry will be included in handshakeResponse.EncodedServerList,
  134. // along side discovery servers.
  135. requestedMissingProviderID := false
  136. if !serverContext.tunnel.dialParams.ServerEntry.HasProviderID() {
  137. requestedMissingProviderID = true
  138. params["missing_server_entry_provider_id"] =
  139. serverContext.tunnel.dialParams.ServerEntry.Tag
  140. }
  141. doTactics := !serverContext.tunnel.config.DisableTactics
  142. networkID := ""
  143. if doTactics {
  144. // Limitation: it is assumed that the network ID obtained here is the
  145. // one that is active when the handshake request is received by the
  146. // server. However, it is remotely possible to switch networks
  147. // immediately after invoking the GetNetworkID callback and initiating
  148. // the handshake, if the tunnel protocol is meek.
  149. //
  150. // The response handling code below calls GetNetworkID again and ignores
  151. // any tactics payload if the network ID is not the same. While this
  152. // doesn't detect all cases of changing networks, it reduces the already
  153. // narrow window.
  154. networkID = serverContext.tunnel.config.GetNetworkID()
  155. err := tactics.SetTacticsAPIParameters(
  156. GetTacticsStorer(serverContext.tunnel.config),
  157. networkID,
  158. params)
  159. if err != nil {
  160. return errors.Trace(err)
  161. }
  162. }
  163. // When split tunnel mode is enabled, indicate this to the server. When
  164. // indicated, the server will perform split tunnel classifications on TCP
  165. // port forwards and reject, with a distinct response, port forwards which
  166. // the client should connect to directly, untunneled.
  167. if serverContext.tunnel.config.SplitTunnelOwnRegion {
  168. params["split_tunnel"] = "1"
  169. }
  170. // While regular split tunnel mode makes untunneled connections to
  171. // destinations in the client's own country, selected split tunnel mode
  172. // allows the client to specify a list of untunneled countries. Either or
  173. // both modes may be enabled.
  174. if len(serverContext.tunnel.config.SplitTunnelRegions) > 0 {
  175. params["split_tunnel_regions"] = serverContext.tunnel.config.SplitTunnelRegions
  176. }
  177. // Add the in-proxy broker/server relay packet, which contains either the
  178. // immediate broker report payload, for established sessions, or a new
  179. // session handshake packet. The broker report securely relays the
  180. // original client IP and the relaying proxy ID to the Psiphon server.
  181. // inproxy_relay_packet is a required field for in-proxy tunnel protocols.
  182. if protocol.TunnelProtocolUsesInproxy(serverContext.tunnel.dialParams.TunnelProtocol) {
  183. inproxyConn := serverContext.tunnel.dialParams.inproxyConn.Load()
  184. if inproxyConn != nil {
  185. packet := base64.RawStdEncoding.EncodeToString(
  186. inproxyConn.(*inproxy.ClientConn).InitialRelayPacket())
  187. params["inproxy_relay_packet"] = packet
  188. }
  189. }
  190. var response []byte
  191. if serverContext.psiphonHttpsClient == nil {
  192. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] =
  193. serverContext.tunnel.config.GetAuthorizations()
  194. request, err := serverContext.makeSSHAPIRequestPayload(params)
  195. if err != nil {
  196. return errors.Trace(err)
  197. }
  198. response, err = serverContext.tunnel.SendAPIRequest(
  199. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  200. if err != nil {
  201. return errors.Trace(err)
  202. }
  203. } else {
  204. // Legacy web service API request
  205. responseBody, err := serverContext.doGetRequest(
  206. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  207. if err != nil {
  208. return errors.Trace(err)
  209. }
  210. // Skip legacy format lines and just parse the JSON config line
  211. configLinePrefix := []byte("Config: ")
  212. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  213. if bytes.HasPrefix(line, configLinePrefix) {
  214. response = line[len(configLinePrefix):]
  215. break
  216. }
  217. }
  218. if len(response) == 0 {
  219. return errors.TraceNew("no config line found")
  220. }
  221. }
  222. // Legacy fields:
  223. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  224. // - 'ssh_session_id' is ignored; client session ID is used instead
  225. var handshakeResponse protocol.HandshakeResponse
  226. // Initialize these fields to distinguish between psiphond omitting values in
  227. // the response and the zero value, which means unlimited rate.
  228. handshakeResponse.UpstreamBytesPerSecond = -1
  229. handshakeResponse.DownstreamBytesPerSecond = -1
  230. err := json.Unmarshal(response, &handshakeResponse)
  231. if err != nil {
  232. return errors.Trace(err)
  233. }
  234. // Limitation: ClientAddress is not supported for in-proxy tunnel
  235. // protocols; see comment in server.handshakeAPIRequestHandler.
  236. if serverContext.tunnel.config.EmitClientAddress &&
  237. !protocol.TunnelProtocolUsesInproxy(serverContext.tunnel.dialParams.TunnelProtocol) {
  238. NoticeClientAddress(handshakeResponse.ClientAddress)
  239. }
  240. NoticeClientRegion(handshakeResponse.ClientRegion)
  241. // Emit a SplitTunnelRegions notice indicating active split tunnel region.
  242. // For SplitTunnelOwnRegion, the handshake ClientRegion is the split
  243. // tunnel region and this region is always listed first.
  244. splitTunnelRegions := []string{}
  245. if serverContext.tunnel.config.SplitTunnelOwnRegion {
  246. splitTunnelRegions = []string{handshakeResponse.ClientRegion}
  247. }
  248. for _, region := range serverContext.tunnel.config.SplitTunnelRegions {
  249. if !serverContext.tunnel.config.SplitTunnelOwnRegion ||
  250. region != handshakeResponse.ClientRegion {
  251. splitTunnelRegions = append(splitTunnelRegions, region)
  252. }
  253. }
  254. if len(splitTunnelRegions) > 0 {
  255. NoticeSplitTunnelRegions(splitTunnelRegions)
  256. }
  257. var serverEntries []protocol.ServerEntryFields
  258. // Store discovered server entries
  259. // We use the server's time, as it's available here, for the server entry
  260. // timestamp since this is more reliable than the client time.
  261. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  262. serverEntryFields, err := protocol.DecodeServerEntryFields(
  263. encodedServerEntry,
  264. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  265. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  266. if err != nil {
  267. return errors.Trace(err)
  268. }
  269. // Retain the original timestamp and source in the
  270. // requestedMissingSignature and requestedMissingProviderID
  271. // cases, as this server entry was not discovered here.
  272. //
  273. // Limitation: there is a transient edge case where
  274. // requestedMissingSignature and/or requestedMissingProviderID will be
  275. // set for a discovery server entry that _is_ also discovered here.
  276. if requestedMissingSignature || requestedMissingProviderID &&
  277. serverEntryFields.GetIPAddress() == serverContext.tunnel.dialParams.ServerEntry.IpAddress {
  278. serverEntryFields.SetLocalTimestamp(serverContext.tunnel.dialParams.ServerEntry.LocalTimestamp)
  279. serverEntryFields.SetLocalSource(serverContext.tunnel.dialParams.ServerEntry.LocalSource)
  280. }
  281. err = protocol.ValidateServerEntryFields(serverEntryFields)
  282. if err != nil {
  283. // Skip this entry and continue with the next one
  284. NoticeWarning("invalid handshake server entry: %s", err)
  285. continue
  286. }
  287. serverEntries = append(serverEntries, serverEntryFields)
  288. }
  289. err = StoreServerEntries(
  290. serverContext.tunnel.config,
  291. serverEntries,
  292. true)
  293. if err != nil {
  294. return errors.Trace(err)
  295. }
  296. NoticeHomepages(handshakeResponse.Homepages)
  297. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  298. if handshakeResponse.UpgradeClientVersion != "" {
  299. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  300. } else {
  301. NoticeClientIsLatestVersion("")
  302. }
  303. if !ignoreStatsRegexps {
  304. // The handshake returns page_view_regexes and https_request_regexes.
  305. // page_view_regexes is obsolete and not used. https_request_regexes, which
  306. // are actually host/domain name regexes, are used for host/domain name
  307. // bytes transferred metrics: tunneled traffic TLS SNI server names and HTTP
  308. // Host header host names are matched against these regexes to select flows
  309. // for bytes transferred counting.
  310. var regexpsNotices []string
  311. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  312. handshakeResponse.HttpsRequestRegexes)
  313. for _, notice := range regexpsNotices {
  314. NoticeWarning(notice)
  315. }
  316. }
  317. diagnosticID := serverContext.tunnel.dialParams.ServerEntry.GetDiagnosticID()
  318. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  319. NoticeServerTimestamp(diagnosticID, serverContext.serverHandshakeTimestamp)
  320. NoticeActiveAuthorizationIDs(diagnosticID, handshakeResponse.ActiveAuthorizationIDs)
  321. NoticeTrafficRateLimits(
  322. diagnosticID,
  323. handshakeResponse.UpstreamBytesPerSecond,
  324. handshakeResponse.DownstreamBytesPerSecond)
  325. if doTactics && handshakeResponse.TacticsPayload != nil &&
  326. networkID == serverContext.tunnel.config.GetNetworkID() {
  327. var payload *tactics.Payload
  328. err := json.Unmarshal(handshakeResponse.TacticsPayload, &payload)
  329. if err != nil {
  330. return errors.Trace(err)
  331. }
  332. // handshakeResponse.TacticsPayload may be "null", and payload
  333. // will successfully unmarshal as nil. As a result, the previous
  334. // handshakeResponse.TacticsPayload != nil test is insufficient.
  335. if payload != nil {
  336. tacticsRecord, err := tactics.HandleTacticsPayload(
  337. GetTacticsStorer(serverContext.tunnel.config),
  338. networkID,
  339. payload)
  340. if err != nil {
  341. return errors.Trace(err)
  342. }
  343. if tacticsRecord != nil {
  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() 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. serverContext.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. // Confirm the payload now that the server response is received. For
  513. // persistentStats and transferStats, this clears the reported data as it
  514. // is now delivered and doesn't need to be resent.
  515. confirmStatusRequestPayload(statusPayloadInfo)
  516. var statusResponse protocol.StatusResponse
  517. err = json.Unmarshal(response, &statusResponse)
  518. if err != nil {
  519. return errors.Trace(err)
  520. }
  521. // Prune all server entries flagged by either the failed_tunnel mechanism
  522. // or the prune check. Note that server entries that are too new, as
  523. // determined by ServerEntryMinimumAgeForPruning, are not pruned, and
  524. // this is reflected in pruneCount.
  525. pruneCount := 0
  526. for _, serverEntryTag := range statusResponse.InvalidServerEntryTags {
  527. if PruneServerEntry(serverContext.tunnel.config, serverEntryTag) {
  528. pruneCount++
  529. }
  530. }
  531. if pruneCount > 0 {
  532. NoticeInfo("Pruned server entries: %d", pruneCount)
  533. }
  534. if statusPayloadInfo.checkServerEntryTagCount > 0 {
  535. // Schedule the next prune check, now that all pruning is complete. By
  536. // design, if the process dies before the end of the prune loop, the
  537. // previous due time will be retained.
  538. //
  539. // UpdateCheckServerEntryTagsEndTime may leave the next prune check
  540. // due immediately based on the ratio of server entries checked and
  541. // server entries pruned: if many checked server entries were invalid
  542. // and pruned, check again and prune more.
  543. //
  544. // Limitation: the prune count may include failed_tunnel prunes which
  545. // aren't in the check count; if this occurs, it will increase the
  546. // ratio and make an immediate re-check more likely, which makes sense.
  547. UpdateCheckServerEntryTagsEndTime(
  548. serverContext.tunnel.config,
  549. statusPayloadInfo.checkServerEntryTagCount,
  550. pruneCount)
  551. }
  552. return nil
  553. }
  554. // statusRequestPayloadInfo is a temporary structure for data used to
  555. // either "clear" or "put back" status request payload data depending
  556. // on whether or not the request succeeded.
  557. type statusRequestPayloadInfo struct {
  558. serverId string
  559. transferStats *transferstats.AccumulatedStats
  560. persistentStats map[string][][]byte
  561. checkServerEntryTagCount int
  562. }
  563. func makeStatusRequestPayload(
  564. config *Config,
  565. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  566. // The status request payload is always JSON encoded. As it is sent after
  567. // the initial handshake and is multiplexed with other tunnel traffic,
  568. // its size is less of a fingerprinting concern.
  569. //
  570. // TODO: pack and CBOR encode the status request payload.
  571. // GetCheckServerEntryTags returns a randomly selected set of server entry
  572. // tags to be checked for pruning, or an empty list if a check is not yet
  573. // due.
  574. //
  575. // Both persistentStats and prune check data have a max payload size
  576. // allowance, and the allowance for persistentStats is reduced by the
  577. // size of the prune check data, if any.
  578. checkServerEntryTags, tagsSize, err := GetCheckServerEntryTags(config)
  579. if err != nil {
  580. NoticeWarning(
  581. "GetCheckServerEntryTags failed: %s", errors.Trace(err))
  582. checkServerEntryTags = nil
  583. // Proceed with persistentStats/transferStats only
  584. }
  585. transferStats := transferstats.TakeOutStatsForServer(serverId)
  586. hostBytes := transferStats.GetStatsForStatusRequest()
  587. persistentStats, statsSize, err := TakeOutUnreportedPersistentStats(config, tagsSize)
  588. if err != nil {
  589. NoticeWarning(
  590. "TakeOutUnreportedPersistentStats failed: %s", errors.Trace(err))
  591. persistentStats = nil
  592. // Proceed with transferStats only
  593. }
  594. if len(checkServerEntryTags) == 0 && len(hostBytes) == 0 && len(persistentStats) == 0 {
  595. // There is no payload to send.
  596. return nil, nil, nil
  597. }
  598. payloadInfo := &statusRequestPayloadInfo{
  599. serverId,
  600. transferStats,
  601. persistentStats,
  602. len(checkServerEntryTags),
  603. }
  604. payload := make(map[string]interface{})
  605. payload["host_bytes"] = hostBytes
  606. // We're not recording these fields, but legacy servers require them.
  607. payload["bytes_transferred"] = 0
  608. payload["page_views"] = make([]string, 0)
  609. payload["https_requests"] = make([]string, 0)
  610. persistentStatPayloadNames := make(map[string]string)
  611. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  612. persistentStatPayloadNames[datastorePersistentStatTypeFailedTunnel] = "failed_tunnel_stats"
  613. for statType, stats := range persistentStats {
  614. // Persistent stats records are already in JSON format
  615. jsonStats := make([]json.RawMessage, len(stats))
  616. for i, stat := range stats {
  617. jsonStats[i] = json.RawMessage(stat)
  618. }
  619. payload[persistentStatPayloadNames[statType]] = jsonStats
  620. }
  621. payload["check_server_entry_tags"] = checkServerEntryTags
  622. jsonPayload, err := json.Marshal(payload)
  623. if err != nil {
  624. // Send the transfer stats and tunnel stats later
  625. putBackStatusRequestPayload(payloadInfo)
  626. return nil, nil, errors.Trace(err)
  627. }
  628. NoticeInfo(
  629. "StatusRequestPayload: %d total bytes, %d stats bytes, %d tag bytes",
  630. len(jsonPayload), statsSize, tagsSize)
  631. return jsonPayload, payloadInfo, nil
  632. }
  633. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  634. transferstats.PutBackStatsForServer(
  635. payloadInfo.serverId, payloadInfo.transferStats)
  636. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  637. if err != nil {
  638. // These persistent stats records won't be resent until after a
  639. // datastore re-initialization.
  640. NoticeWarning(
  641. "PutBackUnreportedPersistentStats failed: %s", errors.Trace(err))
  642. }
  643. }
  644. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  645. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  646. if err != nil {
  647. // These persistent stats records may be resent.
  648. NoticeWarning(
  649. "ClearReportedPersistentStats failed: %s", errors.Trace(err))
  650. }
  651. }
  652. // RecordRemoteServerListStat records a completed common or OSL remote server
  653. // list resource download.
  654. //
  655. // The RSL download event could occur when the client is unable to immediately
  656. // send a status request to a server, so these records are stored in the
  657. // persistent datastore and reported via subsequent status requests sent to
  658. // any Psiphon server.
  659. //
  660. // Note that some common event field values may change between the stat
  661. // recording and reporting, including client geolocation and host_id.
  662. //
  663. // The bytes/duration fields reflect the size and download time for the _last
  664. // chunk only_ in the case of a resumed download. The purpose of these fields
  665. // is to calculate rough data transfer rates. Both bytes and duration are
  666. // included in the log, to allow for filtering out of small transfers which
  667. // may not produce accurate rate numbers.
  668. //
  669. // Multiple "status" requests may be in flight at once (due to multi-tunnel,
  670. // asynchronous final status retry, and aggressive status requests for
  671. // pre-registered tunnels), To avoid duplicate reporting, persistent stats
  672. // records are "taken-out" by a status request and then "put back" in case the
  673. // request fails.
  674. //
  675. // Duplicate reporting may also occur when a server receives and processes a
  676. // status request but the client fails to receive the response.
  677. func RecordRemoteServerListStat(
  678. config *Config,
  679. tunneled bool,
  680. url string,
  681. etag string,
  682. bytes int64,
  683. duration time.Duration,
  684. authenticated bool,
  685. additionalParameters common.APIParameters) error {
  686. if !config.GetParameters().Get().WeightedCoinFlip(
  687. parameters.RecordRemoteServerListPersistentStatsProbability) {
  688. return nil
  689. }
  690. params := make(common.APIParameters)
  691. params["session_id"] = config.SessionID
  692. params["propagation_channel_id"] = config.PropagationChannelId
  693. params["sponsor_id"] = config.GetSponsorID()
  694. params["client_version"] = config.ClientVersion
  695. params["client_platform"] = config.ClientPlatform
  696. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  697. if config.DeviceRegion != "" {
  698. params["device_region"] = config.DeviceRegion
  699. }
  700. if config.DeviceLocation != "" {
  701. params["device_location"] = config.DeviceLocation
  702. }
  703. params["client_download_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  704. tunneledStr := "0"
  705. if tunneled {
  706. tunneledStr = "1"
  707. }
  708. params["tunneled"] = tunneledStr
  709. params["url"] = url
  710. params["etag"] = etag
  711. params["bytes"] = fmt.Sprintf("%d", bytes)
  712. // duration is nanoseconds; report milliseconds
  713. params["duration"] = fmt.Sprintf("%d", duration/time.Millisecond)
  714. authenticatedStr := "0"
  715. if authenticated {
  716. authenticatedStr = "1"
  717. }
  718. params["authenticated"] = authenticatedStr
  719. for k, v := range additionalParameters {
  720. params[k] = v
  721. }
  722. remoteServerListStatJson, err := json.Marshal(params)
  723. if err != nil {
  724. return errors.Trace(err)
  725. }
  726. return StorePersistentStat(
  727. config, datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  728. }
  729. // RecordFailedTunnelStat records metrics for a failed tunnel dial, including
  730. // dial parameters and error condition (tunnelErr). No record is created when
  731. // tunnelErr is nil.
  732. //
  733. // This uses the same reporting facility, with the same caveats, as
  734. // RecordRemoteServerListStat.
  735. func RecordFailedTunnelStat(
  736. config *Config,
  737. dialParams *DialParameters,
  738. livenessTestMetrics *livenessTestMetrics,
  739. bytesUp int64,
  740. bytesDown int64,
  741. tunnelErr error) error {
  742. probability := config.GetParameters().Get().Float(
  743. parameters.RecordFailedTunnelPersistentStatsProbability)
  744. if !prng.FlipWeightedCoin(probability) {
  745. return nil
  746. }
  747. // Callers should not call RecordFailedTunnelStat with a nil tunnelErr, as
  748. // this is not a useful stat and it results in a nil pointer dereference.
  749. // This check catches potential bug cases. An example edge case, now
  750. // fixed, is deferred error handlers, such as the ones in in
  751. // dialTunnel/tunnel.Activate, which may be invoked in the case of a
  752. // panic, which can occur before any error value is returned.
  753. if tunnelErr == nil {
  754. return errors.TraceNew("no error")
  755. }
  756. lastConnected, err := getLastConnected()
  757. if err != nil {
  758. return errors.Trace(err)
  759. }
  760. params := getBaseAPIParameters(baseParametersAll, true, config, dialParams)
  761. delete(params, "server_secret")
  762. params["server_entry_tag"] = dialParams.ServerEntry.Tag
  763. params["last_connected"] = lastConnected
  764. params["client_failed_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  765. if livenessTestMetrics != nil {
  766. params["liveness_test_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.UpstreamBytes)
  767. params["liveness_test_sent_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.SentUpstreamBytes)
  768. params["liveness_test_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.DownstreamBytes)
  769. params["liveness_test_received_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.ReceivedDownstreamBytes)
  770. }
  771. if bytesUp >= 0 {
  772. params["bytes_up"] = fmt.Sprintf("%d", bytesUp)
  773. }
  774. if bytesDown >= 0 {
  775. params["bytes_down"] = fmt.Sprintf("%d", bytesDown)
  776. }
  777. // Log RecordFailedTunnelPersistentStatsProbability to indicate the
  778. // proportion of failed tunnel events being recorded at the time of
  779. // this log event.
  780. params["record_probability"] = fmt.Sprintf("%f", probability)
  781. // Ensure direct server IPs are not exposed in logs. The "net" package, and
  782. // possibly other 3rd party packages, will include destination addresses in
  783. // I/O error messages.
  784. tunnelError := common.RedactIPAddressesString(tunnelErr.Error())
  785. params["tunnel_error"] = tunnelError
  786. failedTunnelStatJson, err := json.Marshal(params)
  787. if err != nil {
  788. return errors.Trace(err)
  789. }
  790. return StorePersistentStat(
  791. config, datastorePersistentStatTypeFailedTunnel, failedTunnelStatJson)
  792. }
  793. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  794. func (serverContext *ServerContext) doGetRequest(
  795. requestUrl string) (responseBody []byte, err error) {
  796. request, err := http.NewRequest("GET", requestUrl, nil)
  797. if err != nil {
  798. return nil, errors.Trace(err)
  799. }
  800. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  801. response, err := serverContext.psiphonHttpsClient.Do(request)
  802. if err == nil && response.StatusCode != http.StatusOK {
  803. response.Body.Close()
  804. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  805. }
  806. if err != nil {
  807. // Trim this error since it may include long URLs
  808. return nil, errors.Trace(TrimError(err))
  809. }
  810. defer response.Body.Close()
  811. body, err := ioutil.ReadAll(response.Body)
  812. if err != nil {
  813. return nil, errors.Trace(err)
  814. }
  815. return body, nil
  816. }
  817. // doPostRequest makes a tunneled HTTPS POST request.
  818. func (serverContext *ServerContext) doPostRequest(
  819. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  820. request, err := http.NewRequest("POST", requestUrl, body)
  821. if err != nil {
  822. return nil, errors.Trace(err)
  823. }
  824. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  825. request.Header.Set("Content-Type", bodyType)
  826. response, err := serverContext.psiphonHttpsClient.Do(request)
  827. if err == nil && response.StatusCode != http.StatusOK {
  828. response.Body.Close()
  829. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  830. }
  831. if err != nil {
  832. // Trim this error since it may include long URLs
  833. return nil, errors.Trace(TrimError(err))
  834. }
  835. defer response.Body.Close()
  836. responseBody, err = ioutil.ReadAll(response.Body)
  837. if err != nil {
  838. return nil, errors.Trace(err)
  839. }
  840. return responseBody, nil
  841. }
  842. // makeSSHAPIRequestPayload makes an encoded payload for an SSH API request.
  843. func (serverContext *ServerContext) makeSSHAPIRequestPayload(
  844. params common.APIParameters) ([]byte, error) {
  845. // CBOR encoding is the default and is preferred as its smaller size gives
  846. // more space for variable padding to mitigate potential fingerprinting
  847. // based on API message sizes.
  848. if !serverContext.tunnel.dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  849. serverContext.tunnel.config.TargetAPIEncoding == protocol.PSIPHON_API_ENCODING_JSON {
  850. jsonPayload, err := json.Marshal(params)
  851. if err != nil {
  852. return nil, errors.Trace(err)
  853. }
  854. return jsonPayload, nil
  855. }
  856. payload, err := protocol.MakePackedAPIParametersRequestPayload(params)
  857. if err != nil {
  858. return nil, errors.Trace(err)
  859. }
  860. return payload, nil
  861. }
  862. type baseParametersFilter int
  863. const (
  864. baseParametersAll baseParametersFilter = iota
  865. baseParametersOnlyUpstreamFragmentorDialParameters
  866. baseParametersNoDialParameters
  867. )
  868. func (serverContext *ServerContext) getBaseAPIParameters(
  869. filter baseParametersFilter,
  870. includeSessionID bool) common.APIParameters {
  871. params := getBaseAPIParameters(
  872. filter,
  873. includeSessionID,
  874. serverContext.tunnel.config,
  875. serverContext.tunnel.dialParams)
  876. // Add a random amount of padding to defend against API call traffic size
  877. // fingerprints. The "pad_response" field instructs the server to pad its
  878. // response accordingly.
  879. p := serverContext.tunnel.config.GetParameters().Get()
  880. minUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMinBytes)
  881. maxUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMaxBytes)
  882. minDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMinBytes)
  883. maxDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMaxBytes)
  884. if maxUpstreamPadding > 0 {
  885. size := serverContext.paddingPRNG.Range(minUpstreamPadding, maxUpstreamPadding)
  886. params["padding"] = strings.Repeat(" ", size)
  887. }
  888. if maxDownstreamPadding > 0 {
  889. size := serverContext.paddingPRNG.Range(minDownstreamPadding, maxDownstreamPadding)
  890. params["pad_response"] = strconv.Itoa(size)
  891. }
  892. return params
  893. }
  894. // getBaseAPIParameters returns all the common API parameters that are
  895. // included with each Psiphon API request. These common parameters are used
  896. // for metrics.
  897. //
  898. // The input dialParams may be nil when the filter has
  899. // baseParametersNoDialParameters.
  900. func getBaseAPIParameters(
  901. filter baseParametersFilter,
  902. includeSessionID bool,
  903. config *Config,
  904. dialParams *DialParameters) common.APIParameters {
  905. params := make(common.APIParameters)
  906. // Temporary measure: unconditionally include legacy session_id and
  907. // client_session_id fields for compatibility with existing servers used
  908. // in CI.
  909. //
  910. // TODO: remove once necessary servers are upgraded
  911. params["session_id"] = config.SessionID
  912. params["client_session_id"] = config.SessionID
  913. if includeSessionID {
  914. // The session ID is included in non-SSH API requests only. For SSH
  915. // API requests, the Psiphon server already has the client's session ID.
  916. params["session_id"] = config.SessionID
  917. }
  918. params["propagation_channel_id"] = config.PropagationChannelId
  919. params["sponsor_id"] = config.GetSponsorID()
  920. params["client_version"] = config.ClientVersion
  921. params["client_platform"] = config.ClientPlatform
  922. params["client_features"] = config.clientFeatures
  923. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  924. if dialParams != nil {
  925. // Prefer the dialParams network ID snapshot if available.
  926. params["network_type"] = dialParams.GetNetworkType()
  927. } else {
  928. params["network_type"] = GetNetworkType(config.GetNetworkID())
  929. }
  930. // TODO: snapshot tactics tag used when dialParams initialized.
  931. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] =
  932. config.GetParameters().Get().Tag()
  933. // The server secret is deprecated and included only in legacy JSON
  934. // encoded API messages for backwards compatibility. SSH login proves
  935. // client possession of the server entry; the server secret was for the
  936. // legacy web API with no SSH login. Note that we can't check
  937. // dialParams.ServerEntry in the baseParametersNoDialParameters case, but
  938. // that case is used by in-proxy dials, which implies support.
  939. if dialParams != nil {
  940. if !dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  941. config.TargetAPIEncoding == protocol.PSIPHON_API_ENCODING_JSON {
  942. params["server_secret"] = dialParams.ServerEntry.WebServerSecret
  943. }
  944. }
  945. // Blank parameters must be omitted.
  946. if config.DeviceRegion != "" {
  947. params["device_region"] = config.DeviceRegion
  948. }
  949. if config.DeviceLocation != "" {
  950. params["device_location"] = config.DeviceLocation
  951. }
  952. if filter == baseParametersAll {
  953. if protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  954. inproxyConn := dialParams.inproxyConn.Load()
  955. if inproxyConn != nil {
  956. params["inproxy_connection_id"] =
  957. inproxyConn.(*inproxy.ClientConn).GetConnectionID()
  958. }
  959. }
  960. params["relay_protocol"] = dialParams.TunnelProtocol
  961. if dialParams.BPFProgramName != "" {
  962. params["client_bpf"] = dialParams.BPFProgramName
  963. }
  964. if dialParams.SelectedSSHClientVersion {
  965. params["ssh_client_version"] = dialParams.SSHClientVersion
  966. }
  967. if dialParams.UpstreamProxyType != "" {
  968. params["upstream_proxy_type"] = dialParams.UpstreamProxyType
  969. }
  970. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  971. params["upstream_proxy_custom_header_names"] = dialParams.UpstreamProxyCustomHeaderNames
  972. }
  973. if dialParams.FrontingProviderID != "" {
  974. params["fronting_provider_id"] = dialParams.FrontingProviderID
  975. }
  976. if dialParams.MeekDialAddress != "" {
  977. params["meek_dial_address"] = dialParams.MeekDialAddress
  978. }
  979. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  980. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  981. if meekResolvedIPAddress != "" {
  982. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  983. }
  984. }
  985. if dialParams.MeekSNIServerName != "" {
  986. params["meek_sni_server_name"] = dialParams.MeekSNIServerName
  987. }
  988. if dialParams.MeekHostHeader != "" {
  989. params["meek_host_header"] = dialParams.MeekHostHeader
  990. }
  991. // MeekTransformedHostName is meaningful when meek is used, which is when
  992. // MeekDialAddress != ""
  993. if dialParams.MeekDialAddress != "" {
  994. transformedHostName := "0"
  995. if dialParams.MeekTransformedHostName {
  996. transformedHostName = "1"
  997. }
  998. params["meek_transformed_host_name"] = transformedHostName
  999. }
  1000. if dialParams.TLSOSSHSNIServerName != "" {
  1001. params["tls_ossh_sni_server_name"] = dialParams.TLSOSSHSNIServerName
  1002. }
  1003. if dialParams.TLSOSSHTransformedSNIServerName {
  1004. params["tls_ossh_transformed_host_name"] = "1"
  1005. }
  1006. if dialParams.TLSFragmentClientHello {
  1007. params["tls_fragmented"] = "1"
  1008. }
  1009. if dialParams.SelectedUserAgent {
  1010. params["user_agent"] = dialParams.UserAgent
  1011. }
  1012. if dialParams.SelectedTLSProfile {
  1013. params["tls_profile"] = dialParams.TLSProfile
  1014. params["tls_version"] = dialParams.GetTLSVersionForMetrics()
  1015. }
  1016. if dialParams.ServerEntry.Region != "" {
  1017. params["server_entry_region"] = dialParams.ServerEntry.Region
  1018. }
  1019. if dialParams.ServerEntry.LocalSource != "" {
  1020. params["server_entry_source"] = dialParams.ServerEntry.LocalSource
  1021. }
  1022. // As with last_connected, this timestamp stat, which may be a precise
  1023. // handshake request server timestamp, is truncated to hour granularity to
  1024. // avoid introducing a reconstructable cross-session user trace into server
  1025. // logs.
  1026. localServerEntryTimestamp := common.TruncateTimestampToHour(
  1027. dialParams.ServerEntry.LocalTimestamp)
  1028. if localServerEntryTimestamp != "" {
  1029. params["server_entry_timestamp"] = localServerEntryTimestamp
  1030. }
  1031. if dialParams.DialPortNumber != "" {
  1032. params["dial_port_number"] = dialParams.DialPortNumber
  1033. }
  1034. if dialParams.QUICVersion != "" {
  1035. params["quic_version"] = dialParams.QUICVersion
  1036. }
  1037. if dialParams.QUICDialSNIAddress != "" {
  1038. params["quic_dial_sni_address"] = dialParams.QUICDialSNIAddress
  1039. }
  1040. if dialParams.QUICDisablePathMTUDiscovery {
  1041. params["quic_disable_client_path_mtu_discovery"] = "1"
  1042. }
  1043. isReplay := "0"
  1044. if dialParams.IsReplay {
  1045. isReplay = "1"
  1046. }
  1047. params["is_replay"] = isReplay
  1048. if config.EgressRegion != "" {
  1049. params["egress_region"] = config.EgressRegion
  1050. }
  1051. // dialParams.DialDuration is nanoseconds; report milliseconds
  1052. params["dial_duration"] = fmt.Sprintf("%d", dialParams.DialDuration/time.Millisecond)
  1053. params["candidate_number"] = strconv.Itoa(dialParams.CandidateNumber)
  1054. params["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  1055. if dialParams.NetworkLatencyMultiplier != 0.0 {
  1056. params["network_latency_multiplier"] =
  1057. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  1058. }
  1059. if dialParams.ConjureTransport != "" {
  1060. params["conjure_transport"] = dialParams.ConjureTransport
  1061. }
  1062. usedSteeringIP := false
  1063. if dialParams.SteeringIP != "" {
  1064. params["steering_ip"] = dialParams.SteeringIP
  1065. usedSteeringIP = true
  1066. }
  1067. if dialParams.ResolveParameters != nil && !usedSteeringIP {
  1068. // Log enough information to distinguish several successful or
  1069. // failed circumvention cases of interest, including preferring
  1070. // alternate servers and/or using DNS protocol transforms, and
  1071. // appropriate for both handshake and failed_tunnel logging:
  1072. //
  1073. // - The initial attempt made by Resolver.ResolveIP,
  1074. // preferring an alternate DNS server and/or using a
  1075. // protocol transform succeeds (dns_result = 0, the initial
  1076. // attempt, 0, got the first result).
  1077. //
  1078. // - A second attempt may be used, still preferring an
  1079. // alternate DNS server but no longer using the protocol
  1080. // transform, which presumably failed (dns_result = 1, the
  1081. // second attempt, 1, got the first result).
  1082. //
  1083. // - Subsequent attempts will use the system DNS server and no
  1084. // protocol transforms (dns_result > 2).
  1085. //
  1086. // Due to the design of Resolver.ResolveIP, the notion
  1087. // of "success" is approximate; for example a successful
  1088. // response may arrive after a subsequent attempt succeeds,
  1089. // simply due to slow network conditions. It's also possible
  1090. // that, for a given attemp, only one of the two concurrent
  1091. // requests (A and AAAA) succeeded.
  1092. //
  1093. // Note that ResolveParameters.GetFirstAttemptWithAnswer
  1094. // semantics assume that dialParams.ResolveParameters wasn't
  1095. // used by or modified by any other dial.
  1096. //
  1097. // Some protocols may use both preresolved DNS as well as actual
  1098. // DNS requests, such as Conjure with the DTLS transport, which
  1099. // may resolve STUN server domains while using preresolved DNS
  1100. // for fronted API registration.
  1101. if dialParams.ResolveParameters.PreresolvedIPAddress != "" {
  1102. meekDialDomain, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  1103. if dialParams.ResolveParameters.PreresolvedDomain == meekDialDomain {
  1104. params["dns_preresolved"] = dialParams.ResolveParameters.PreresolvedIPAddress
  1105. }
  1106. }
  1107. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  1108. params["dns_preferred"] = dialParams.ResolveParameters.AlternateDNSServer
  1109. }
  1110. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  1111. params["dns_transform"] = dialParams.ResolveParameters.ProtocolTransformName
  1112. }
  1113. if dialParams.ResolveParameters.RandomQNameCasingSeed != nil {
  1114. params["dns_qname_random_casing"] = "1"
  1115. }
  1116. if dialParams.ResolveParameters.ResponseQNameMustMatch {
  1117. params["dns_qname_must_match"] = "1"
  1118. }
  1119. params["dns_qname_mismatches"] = strconv.Itoa(
  1120. dialParams.ResolveParameters.GetQNameMismatches())
  1121. params["dns_attempt"] = strconv.Itoa(
  1122. dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  1123. }
  1124. if dialParams.HTTPTransformerParameters != nil {
  1125. if dialParams.HTTPTransformerParameters.ProtocolTransformSpec != nil {
  1126. params["http_transform"] = dialParams.HTTPTransformerParameters.ProtocolTransformName
  1127. }
  1128. }
  1129. if dialParams.OSSHObfuscatorSeedTransformerParameters != nil {
  1130. if dialParams.OSSHObfuscatorSeedTransformerParameters.TransformSpec != nil {
  1131. params["seed_transform"] = dialParams.OSSHObfuscatorSeedTransformerParameters.TransformName
  1132. }
  1133. }
  1134. if dialParams.ObfuscatedQUICNonceTransformerParameters != nil {
  1135. if dialParams.ObfuscatedQUICNonceTransformerParameters.TransformSpec != nil {
  1136. params["seed_transform"] = dialParams.ObfuscatedQUICNonceTransformerParameters.TransformName
  1137. }
  1138. }
  1139. if dialParams.OSSHPrefixSpec != nil {
  1140. if dialParams.OSSHPrefixSpec.Spec != nil {
  1141. params["ossh_prefix"] = dialParams.OSSHPrefixSpec.Name
  1142. }
  1143. }
  1144. if dialParams.ShadowsocksPrefixSpec != nil {
  1145. if dialParams.ShadowsocksPrefixSpec.Spec != nil {
  1146. params["shadowsocks_prefix"] = dialParams.ShadowsocksPrefixSpec.Name
  1147. }
  1148. }
  1149. if dialParams.DialConnMetrics != nil {
  1150. metrics := dialParams.DialConnMetrics.GetMetrics()
  1151. for name, value := range metrics {
  1152. params[name] = fmt.Sprintf("%v", value)
  1153. }
  1154. }
  1155. if dialParams.ObfuscatedSSHConnMetrics != nil {
  1156. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  1157. for name, value := range metrics {
  1158. params[name] = fmt.Sprintf("%v", value)
  1159. }
  1160. }
  1161. if protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  1162. metrics := dialParams.GetInproxyMetrics()
  1163. for name, value := range metrics {
  1164. params[name] = fmt.Sprintf("%v", value)
  1165. }
  1166. }
  1167. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  1168. if dialParams.DialConnMetrics != nil {
  1169. names := fragmentor.GetUpstreamMetricsNames()
  1170. metrics := dialParams.DialConnMetrics.GetMetrics()
  1171. for name, value := range metrics {
  1172. if common.Contains(names, name) {
  1173. params[name] = fmt.Sprintf("%v", value)
  1174. }
  1175. }
  1176. }
  1177. }
  1178. return params
  1179. }
  1180. // makeRequestUrl makes a URL for a web service API request.
  1181. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  1182. var requestUrl bytes.Buffer
  1183. if port == "" {
  1184. port = tunnel.dialParams.ServerEntry.WebServerPort
  1185. }
  1186. requestUrl.WriteString("https://")
  1187. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  1188. requestUrl.WriteString(":")
  1189. requestUrl.WriteString(port)
  1190. requestUrl.WriteString("/")
  1191. requestUrl.WriteString(path)
  1192. if len(params) > 0 {
  1193. queryParams := url.Values{}
  1194. for name, value := range params {
  1195. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  1196. // parameter, which has a different type. This parameter is not recognized
  1197. // by legacy servers.
  1198. switch v := value.(type) {
  1199. case string:
  1200. queryParams.Set(name, v)
  1201. case []string:
  1202. // String array param encoded as JSON
  1203. jsonValue, err := json.Marshal(v)
  1204. if err != nil {
  1205. break
  1206. }
  1207. queryParams.Set(name, string(jsonValue))
  1208. }
  1209. }
  1210. requestUrl.WriteString("?")
  1211. requestUrl.WriteString(queryParams.Encode())
  1212. }
  1213. return requestUrl.String()
  1214. }
  1215. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  1216. // requests and which validates the web server using the Psiphon server entry web server
  1217. // certificate.
  1218. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  1219. certificate, err := DecodeCertificate(
  1220. tunnel.dialParams.ServerEntry.WebServerCertificate)
  1221. if err != nil {
  1222. return nil, errors.Trace(err)
  1223. }
  1224. tunneledDialer := func(_ context.Context, _, addr string) (net.Conn, error) {
  1225. // This case bypasses tunnel.Dial, to avoid its check that the tunnel is
  1226. // already active (it won't be pre-handshake). This bypass won't handle the
  1227. // server rejecting the port forward due to split tunnel classification, but
  1228. // we know that the server won't classify the web API destination as
  1229. // untunneled.
  1230. return tunnel.sshClient.Dial("tcp", addr)
  1231. }
  1232. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  1233. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  1234. // the request. While it's possible to add a timeout here, we leave it with no explicit
  1235. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  1236. // alives will cause the tunnel to close.
  1237. dialer := NewCustomTLSDialer(
  1238. &CustomTLSConfig{
  1239. Parameters: tunnel.config.GetParameters(),
  1240. Dial: tunneledDialer,
  1241. VerifyLegacyCertificate: certificate,
  1242. })
  1243. transport := &http.Transport{
  1244. DialTLS: func(network, addr string) (net.Conn, error) {
  1245. return dialer(context.Background(), network, addr)
  1246. },
  1247. Dial: func(network, addr string) (net.Conn, error) {
  1248. return nil, errors.TraceNew("HTTP not supported")
  1249. },
  1250. }
  1251. return &http.Client{
  1252. Transport: transport,
  1253. }, nil
  1254. }
  1255. func HandleServerRequest(
  1256. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) {
  1257. var err error
  1258. switch request.Type {
  1259. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  1260. err = HandleOSLRequest(tunnelOwner, tunnel, request)
  1261. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  1262. err = HandleAlertRequest(tunnelOwner, tunnel, request)
  1263. default:
  1264. err = errors.Tracef("invalid request name")
  1265. }
  1266. if err != nil {
  1267. NoticeWarning(
  1268. "HandleServerRequest for %s failed: %s", request.Type, errors.Trace(err))
  1269. }
  1270. }
  1271. func HandleOSLRequest(
  1272. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1273. defer func() {
  1274. if retErr != nil {
  1275. _ = request.Reply(false, nil)
  1276. }
  1277. }()
  1278. var oslRequest protocol.OSLRequest
  1279. err := json.Unmarshal(request.Payload, &oslRequest)
  1280. if err != nil {
  1281. return errors.Trace(err)
  1282. }
  1283. if oslRequest.ClearLocalSLOKs {
  1284. err := DeleteSLOKs()
  1285. if err != nil {
  1286. NoticeWarning("DeleteSLOKs failed: %v", errors.Trace(err))
  1287. // Continue
  1288. }
  1289. }
  1290. seededNewSLOK := false
  1291. for _, slok := range oslRequest.SeedPayload.SLOKs {
  1292. duplicate, err := SetSLOK(slok.ID, slok.Key)
  1293. if err != nil {
  1294. // TODO: return error to trigger retry?
  1295. NoticeWarning("SetSLOK failed: %v", errors.Trace(err))
  1296. } else if !duplicate {
  1297. seededNewSLOK = true
  1298. }
  1299. if tunnel.config.EmitSLOKs {
  1300. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  1301. }
  1302. }
  1303. if seededNewSLOK {
  1304. tunnelOwner.SignalSeededNewSLOK()
  1305. }
  1306. err = request.Reply(true, nil)
  1307. if err != nil {
  1308. return errors.Trace(err)
  1309. }
  1310. return nil
  1311. }
  1312. func HandleAlertRequest(
  1313. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1314. defer func() {
  1315. if retErr != nil {
  1316. _ = request.Reply(false, nil)
  1317. }
  1318. }()
  1319. var alertRequest protocol.AlertRequest
  1320. err := json.Unmarshal(request.Payload, &alertRequest)
  1321. if err != nil {
  1322. return errors.Trace(err)
  1323. }
  1324. if tunnel.config.EmitServerAlerts {
  1325. NoticeServerAlert(alertRequest)
  1326. }
  1327. err = request.Reply(true, nil)
  1328. if err != nil {
  1329. return errors.Trace(err)
  1330. }
  1331. return nil
  1332. }