serverApi.go 54 KB

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