serverApi.go 53 KB

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