serverApi.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644
  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["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  1072. if dialParams.NetworkLatencyMultiplier != 0.0 {
  1073. params["network_latency_multiplier"] =
  1074. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  1075. }
  1076. if dialParams.ConjureTransport != "" {
  1077. params["conjure_transport"] = dialParams.ConjureTransport
  1078. }
  1079. usedSteeringIP := false
  1080. if dialParams.SteeringIP != "" {
  1081. params["steering_ip"] = dialParams.SteeringIP
  1082. usedSteeringIP = true
  1083. }
  1084. if dialParams.ResolveParameters != nil && !usedSteeringIP {
  1085. // Log enough information to distinguish several successful or
  1086. // failed circumvention cases of interest, including preferring
  1087. // alternate servers and/or using DNS protocol transforms, and
  1088. // appropriate for both handshake and failed_tunnel logging:
  1089. //
  1090. // - The initial attempt made by Resolver.ResolveIP,
  1091. // preferring an alternate DNS server and/or using a
  1092. // protocol transform succeeds (dns_result = 0, the initial
  1093. // attempt, 0, got the first result).
  1094. //
  1095. // - A second attempt may be used, still preferring an
  1096. // alternate DNS server but no longer using the protocol
  1097. // transform, which presumably failed (dns_result = 1, the
  1098. // second attempt, 1, got the first result).
  1099. //
  1100. // - Subsequent attempts will use the system DNS server and no
  1101. // protocol transforms (dns_result > 2).
  1102. //
  1103. // Due to the design of Resolver.ResolveIP, the notion
  1104. // of "success" is approximate; for example a successful
  1105. // response may arrive after a subsequent attempt succeeds,
  1106. // simply due to slow network conditions. It's also possible
  1107. // that, for a given attemp, only one of the two concurrent
  1108. // requests (A and AAAA) succeeded.
  1109. //
  1110. // Note that ResolveParameters.GetFirstAttemptWithAnswer
  1111. // semantics assume that dialParams.ResolveParameters wasn't
  1112. // used by or modified by any other dial.
  1113. //
  1114. // Some protocols may use both preresolved DNS as well as actual
  1115. // DNS requests, such as Conjure with the DTLS transport, which
  1116. // may resolve STUN server domains while using preresolved DNS
  1117. // for fronted API registration.
  1118. if dialParams.ResolveParameters.PreresolvedIPAddress != "" {
  1119. meekDialDomain, _, _ := net.SplitHostPort(dialParams.MeekDialAddress)
  1120. if dialParams.ResolveParameters.PreresolvedDomain == meekDialDomain {
  1121. params["dns_preresolved"] = dialParams.ResolveParameters.PreresolvedIPAddress
  1122. }
  1123. }
  1124. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  1125. params["dns_preferred"] = dialParams.ResolveParameters.AlternateDNSServer
  1126. }
  1127. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  1128. params["dns_transform"] = dialParams.ResolveParameters.ProtocolTransformName
  1129. }
  1130. if dialParams.ResolveParameters.RandomQNameCasingSeed != nil {
  1131. params["dns_qname_random_casing"] = "1"
  1132. }
  1133. if dialParams.ResolveParameters.ResponseQNameMustMatch {
  1134. params["dns_qname_must_match"] = "1"
  1135. }
  1136. params["dns_qname_mismatches"] = strconv.Itoa(
  1137. dialParams.ResolveParameters.GetQNameMismatches())
  1138. params["dns_attempt"] = strconv.Itoa(
  1139. dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  1140. }
  1141. if dialParams.HTTPTransformerParameters != nil {
  1142. if dialParams.HTTPTransformerParameters.ProtocolTransformSpec != nil {
  1143. params["http_transform"] = dialParams.HTTPTransformerParameters.ProtocolTransformName
  1144. }
  1145. }
  1146. if dialParams.OSSHObfuscatorSeedTransformerParameters != nil {
  1147. if dialParams.OSSHObfuscatorSeedTransformerParameters.TransformSpec != nil {
  1148. params["seed_transform"] = dialParams.OSSHObfuscatorSeedTransformerParameters.TransformName
  1149. }
  1150. }
  1151. if dialParams.ObfuscatedQUICNonceTransformerParameters != nil {
  1152. if dialParams.ObfuscatedQUICNonceTransformerParameters.TransformSpec != nil {
  1153. params["seed_transform"] = dialParams.ObfuscatedQUICNonceTransformerParameters.TransformName
  1154. }
  1155. }
  1156. if dialParams.OSSHPrefixSpec != nil {
  1157. if dialParams.OSSHPrefixSpec.Spec != nil {
  1158. params["ossh_prefix"] = dialParams.OSSHPrefixSpec.Name
  1159. }
  1160. }
  1161. if dialParams.ShadowsocksPrefixSpec != nil {
  1162. if dialParams.ShadowsocksPrefixSpec.Spec != nil {
  1163. params["shadowsocks_prefix"] = dialParams.ShadowsocksPrefixSpec.Name
  1164. }
  1165. }
  1166. if dialParams.DialConnMetrics != nil {
  1167. metrics := dialParams.DialConnMetrics.GetMetrics()
  1168. for name, value := range metrics {
  1169. params[name] = fmt.Sprintf("%v", value)
  1170. }
  1171. }
  1172. if dialParams.ObfuscatedSSHConnMetrics != nil {
  1173. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  1174. for name, value := range metrics {
  1175. params[name] = fmt.Sprintf("%v", value)
  1176. }
  1177. }
  1178. if protocol.TunnelProtocolUsesInproxy(dialParams.TunnelProtocol) {
  1179. metrics := dialParams.GetInproxyMetrics()
  1180. for name, value := range metrics {
  1181. params[name] = fmt.Sprintf("%v", value)
  1182. }
  1183. }
  1184. serverEntryCount := GetLastServerEntryCount()
  1185. if serverEntryCount >= 0 {
  1186. params["server_entry_count"] = strconv.Itoa(serverEntryCount)
  1187. }
  1188. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  1189. if dialParams.DialConnMetrics != nil {
  1190. names := fragmentor.GetUpstreamMetricsNames()
  1191. metrics := dialParams.DialConnMetrics.GetMetrics()
  1192. for name, value := range metrics {
  1193. if common.Contains(names, name) {
  1194. params[name] = fmt.Sprintf("%v", value)
  1195. }
  1196. }
  1197. }
  1198. }
  1199. return params
  1200. }
  1201. // makeRequestUrl makes a URL for a web service API request.
  1202. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  1203. var requestUrl bytes.Buffer
  1204. if port == "" {
  1205. port = tunnel.dialParams.ServerEntry.WebServerPort
  1206. }
  1207. requestUrl.WriteString("https://")
  1208. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  1209. requestUrl.WriteString(":")
  1210. requestUrl.WriteString(port)
  1211. requestUrl.WriteString("/")
  1212. requestUrl.WriteString(path)
  1213. if len(params) > 0 {
  1214. queryParams := url.Values{}
  1215. for name, value := range params {
  1216. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  1217. // parameter, which has a different type. This parameter is not recognized
  1218. // by legacy servers.
  1219. switch v := value.(type) {
  1220. case string:
  1221. queryParams.Set(name, v)
  1222. case []string:
  1223. // String array param encoded as JSON
  1224. jsonValue, err := json.Marshal(v)
  1225. if err != nil {
  1226. break
  1227. }
  1228. queryParams.Set(name, string(jsonValue))
  1229. }
  1230. }
  1231. requestUrl.WriteString("?")
  1232. requestUrl.WriteString(queryParams.Encode())
  1233. }
  1234. return requestUrl.String()
  1235. }
  1236. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  1237. // requests and which validates the web server using the Psiphon server entry web server
  1238. // certificate.
  1239. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  1240. certificate, err := DecodeCertificate(
  1241. tunnel.dialParams.ServerEntry.WebServerCertificate)
  1242. if err != nil {
  1243. return nil, errors.Trace(err)
  1244. }
  1245. tunneledDialer := func(_ context.Context, _, addr string) (net.Conn, error) {
  1246. // This case bypasses tunnel.Dial, to avoid its check that the tunnel is
  1247. // already active (it won't be pre-handshake). This bypass won't handle the
  1248. // server rejecting the port forward due to split tunnel classification, but
  1249. // we know that the server won't classify the web API destination as
  1250. // untunneled.
  1251. return tunnel.sshClient.Dial("tcp", addr)
  1252. }
  1253. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  1254. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  1255. // the request. While it's possible to add a timeout here, we leave it with no explicit
  1256. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  1257. // alives will cause the tunnel to close.
  1258. dialer := NewCustomTLSDialer(
  1259. &CustomTLSConfig{
  1260. Parameters: tunnel.config.GetParameters(),
  1261. Dial: tunneledDialer,
  1262. VerifyLegacyCertificate: certificate,
  1263. })
  1264. transport := &http.Transport{
  1265. DialTLS: func(network, addr string) (net.Conn, error) {
  1266. return dialer(context.Background(), network, addr)
  1267. },
  1268. Dial: func(network, addr string) (net.Conn, error) {
  1269. return nil, errors.TraceNew("HTTP not supported")
  1270. },
  1271. }
  1272. return &http.Client{
  1273. Transport: transport,
  1274. }, nil
  1275. }
  1276. func HandleServerRequest(
  1277. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) {
  1278. var err error
  1279. switch request.Type {
  1280. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  1281. err = HandleOSLRequest(tunnelOwner, tunnel, request)
  1282. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  1283. err = HandleAlertRequest(tunnelOwner, tunnel, request)
  1284. default:
  1285. err = errors.Tracef("invalid request name")
  1286. }
  1287. if err != nil {
  1288. NoticeWarning(
  1289. "HandleServerRequest for %s failed: %s", request.Type, errors.Trace(err))
  1290. }
  1291. }
  1292. func HandleOSLRequest(
  1293. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1294. defer func() {
  1295. if retErr != nil {
  1296. _ = request.Reply(false, nil)
  1297. }
  1298. }()
  1299. var oslRequest protocol.OSLRequest
  1300. err := json.Unmarshal(request.Payload, &oslRequest)
  1301. if err != nil {
  1302. return errors.Trace(err)
  1303. }
  1304. if oslRequest.ClearLocalSLOKs {
  1305. err := DeleteSLOKs()
  1306. if err != nil {
  1307. NoticeWarning("DeleteSLOKs failed: %v", errors.Trace(err))
  1308. // Continue
  1309. }
  1310. }
  1311. seededNewSLOK := false
  1312. for _, slok := range oslRequest.SeedPayload.SLOKs {
  1313. duplicate, err := SetSLOK(slok.ID, slok.Key)
  1314. if err != nil {
  1315. // TODO: return error to trigger retry?
  1316. NoticeWarning("SetSLOK failed: %v", errors.Trace(err))
  1317. } else if !duplicate {
  1318. seededNewSLOK = true
  1319. }
  1320. if tunnel.config.EmitSLOKs {
  1321. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  1322. }
  1323. }
  1324. if seededNewSLOK {
  1325. tunnelOwner.SignalSeededNewSLOK()
  1326. }
  1327. err = request.Reply(true, nil)
  1328. if err != nil {
  1329. return errors.Trace(err)
  1330. }
  1331. return nil
  1332. }
  1333. func HandleAlertRequest(
  1334. tunnelOwner TunnelOwner, tunnel *Tunnel, request *ssh.Request) (retErr error) {
  1335. defer func() {
  1336. if retErr != nil {
  1337. _ = request.Reply(false, nil)
  1338. }
  1339. }()
  1340. var alertRequest protocol.AlertRequest
  1341. err := json.Unmarshal(request.Payload, &alertRequest)
  1342. if err != nil {
  1343. return errors.Trace(err)
  1344. }
  1345. if tunnel.config.EmitServerAlerts {
  1346. NoticeServerAlert(alertRequest)
  1347. }
  1348. err = request.Reply(true, nil)
  1349. if err != nil {
  1350. return errors.Trace(err)
  1351. }
  1352. return nil
  1353. }