serverApi.go 49 KB

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