serverApi.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  44. )
  45. // ServerContext is a utility struct which holds all of the data associated
  46. // with a Psiphon server connection. In addition to the established tunnel, this
  47. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  48. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  49. // API through SSH requests made directly through the tunnel's SSH client.
  50. type ServerContext struct {
  51. tunnel *Tunnel
  52. psiphonHttpsClient *http.Client
  53. statsRegexps *transferstats.Regexps
  54. clientRegion string
  55. clientUpgradeVersion string
  56. serverHandshakeTimestamp string
  57. paddingPRNG *prng.PRNG
  58. }
  59. // MakeSessionId creates a new session ID. The same session ID is used across
  60. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  61. // instance.
  62. // In server-side stats, we now consider a "session" to be the lifetime of the
  63. // Controller (e.g., the user's commanded start and stop) and we measure this
  64. // duration as well as the duration of each tunnel within the session.
  65. func MakeSessionId() (string, error) {
  66. randomId, err := common.MakeSecureRandomBytes(protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  67. if err != nil {
  68. return "", errors.Trace(err)
  69. }
  70. return hex.EncodeToString(randomId), nil
  71. }
  72. // NewServerContext makes the tunneled handshake request to the Psiphon server
  73. // and returns a ServerContext struct for use with subsequent Psiphon server API
  74. // requests (e.g., periodic connected and status requests).
  75. func NewServerContext(tunnel *Tunnel) (*ServerContext, error) {
  76. // For legacy servers, set up psiphonHttpsClient for
  77. // accessing the Psiphon API via the web service.
  78. var psiphonHttpsClient *http.Client
  79. if !tunnel.dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  80. tunnel.config.TargetApiProtocol == protocol.PSIPHON_WEB_API_PROTOCOL {
  81. var err error
  82. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  83. if err != nil {
  84. return nil, errors.Trace(err)
  85. }
  86. }
  87. serverContext := &ServerContext{
  88. tunnel: tunnel,
  89. psiphonHttpsClient: psiphonHttpsClient,
  90. paddingPRNG: prng.NewPRNGWithSeed(tunnel.dialParams.APIRequestPaddingSeed),
  91. }
  92. ignoreRegexps := tunnel.config.GetClientParameters().Get().Bool(
  93. parameters.IgnoreHandshakeStatsRegexps)
  94. err := serverContext.doHandshakeRequest(ignoreRegexps)
  95. if err != nil {
  96. return nil, errors.Trace(err)
  97. }
  98. return serverContext, nil
  99. }
  100. // doHandshakeRequest performs the "handshake" API request. The handshake
  101. // returns upgrade info, newly discovered server entries -- which are
  102. // stored -- and sponsor info (home pages, stat regexes).
  103. func (serverContext *ServerContext) doHandshakeRequest(
  104. ignoreStatsRegexps bool) error {
  105. params := serverContext.getBaseAPIParameters(baseParametersAll)
  106. // The server will return a signed copy of its own server entry when the
  107. // client specifies this 'missing_server_entry_signature' parameter.
  108. //
  109. // The purpose of this mechanism is to rapidly upgrade client local storage
  110. // from unsigned to signed server entries, and to ensure that the client has
  111. // a signed server entry for its currently connected server as required for
  112. // the client-to-client exchange feature.
  113. //
  114. // The server entry will be included in handshakeResponse.EncodedServerList,
  115. // along side discovery servers.
  116. requestedMissingSignature := false
  117. if !serverContext.tunnel.dialParams.ServerEntry.HasSignature() {
  118. requestedMissingSignature = true
  119. params["missing_server_entry_signature"] =
  120. serverContext.tunnel.dialParams.ServerEntry.Tag
  121. }
  122. doTactics := !serverContext.tunnel.config.DisableTactics
  123. networkID := ""
  124. if doTactics {
  125. // Limitation: it is assumed that the network ID obtained here is the
  126. // one that is active when the handshake request is received by the
  127. // server. However, it is remotely possible to switch networks
  128. // immediately after invoking the GetNetworkID callback and initiating
  129. // the handshake, if the tunnel protocol is meek.
  130. //
  131. // The response handling code below calls GetNetworkID again and ignores
  132. // any tactics payload if the network ID is not the same. While this
  133. // doesn't detect all cases of changing networks, it reduces the already
  134. // narrow window.
  135. networkID = serverContext.tunnel.config.GetNetworkID()
  136. err := tactics.SetTacticsAPIParameters(
  137. serverContext.tunnel.config.clientParameters,
  138. GetTacticsStorer(serverContext.tunnel.config),
  139. networkID,
  140. params)
  141. if err != nil {
  142. return errors.Trace(err)
  143. }
  144. }
  145. var response []byte
  146. if serverContext.psiphonHttpsClient == nil {
  147. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] =
  148. serverContext.tunnel.config.GetAuthorizations()
  149. request, err := serverContext.makeSSHAPIRequestPayload(params)
  150. if err != nil {
  151. return errors.Trace(err)
  152. }
  153. response, err = serverContext.tunnel.SendAPIRequest(
  154. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  155. if err != nil {
  156. return errors.Trace(err)
  157. }
  158. } else {
  159. // Legacy web service API request
  160. responseBody, err := serverContext.doGetRequest(
  161. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  162. if err != nil {
  163. return errors.Trace(err)
  164. }
  165. // Skip legacy format lines and just parse the JSON config line
  166. configLinePrefix := []byte("Config: ")
  167. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  168. if bytes.HasPrefix(line, configLinePrefix) {
  169. response = line[len(configLinePrefix):]
  170. break
  171. }
  172. }
  173. if len(response) == 0 {
  174. return errors.TraceNew("no config line found")
  175. }
  176. }
  177. // Legacy fields:
  178. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  179. // - 'ssh_session_id' is ignored; client session ID is used instead
  180. var handshakeResponse protocol.HandshakeResponse
  181. // Initialize these fields to distinguish between psiphond omitting values in
  182. // the response and the zero value, which means unlimited rate.
  183. handshakeResponse.UpstreamBytesPerSecond = -1
  184. handshakeResponse.DownstreamBytesPerSecond = -1
  185. err := json.Unmarshal(response, &handshakeResponse)
  186. if err != nil {
  187. return errors.Trace(err)
  188. }
  189. serverContext.clientRegion = handshakeResponse.ClientRegion
  190. NoticeClientRegion(serverContext.clientRegion)
  191. var serverEntries []protocol.ServerEntryFields
  192. // Store discovered server entries
  193. // We use the server's time, as it's available here, for the server entry
  194. // timestamp since this is more reliable than the client time.
  195. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  196. serverEntryFields, err := protocol.DecodeServerEntryFields(
  197. encodedServerEntry,
  198. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  199. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  200. if err != nil {
  201. return errors.Trace(err)
  202. }
  203. // Retain the original timestamp and source in the requestedMissingSignature
  204. // case, as this server entry was not discovered here.
  205. //
  206. // Limitation: there is a transient edge case where
  207. // requestedMissingSignature will be set for a discovery server entry that
  208. // _is_ also discovered here.
  209. if requestedMissingSignature &&
  210. serverEntryFields.GetIPAddress() == serverContext.tunnel.dialParams.ServerEntry.IpAddress {
  211. serverEntryFields.SetLocalTimestamp(serverContext.tunnel.dialParams.ServerEntry.LocalTimestamp)
  212. serverEntryFields.SetLocalSource(serverContext.tunnel.dialParams.ServerEntry.LocalSource)
  213. }
  214. err = protocol.ValidateServerEntryFields(serverEntryFields)
  215. if err != nil {
  216. // Skip this entry and continue with the next one
  217. NoticeWarning("invalid handshake server entry: %s", err)
  218. continue
  219. }
  220. serverEntries = append(serverEntries, serverEntryFields)
  221. }
  222. err = StoreServerEntries(
  223. serverContext.tunnel.config,
  224. serverEntries,
  225. true)
  226. if err != nil {
  227. return errors.Trace(err)
  228. }
  229. NoticeHomepages(handshakeResponse.Homepages)
  230. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  231. if handshakeResponse.UpgradeClientVersion != "" {
  232. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  233. } else {
  234. NoticeClientIsLatestVersion("")
  235. }
  236. if !ignoreStatsRegexps {
  237. // The handshake returns page_view_regexes and https_request_regexes.
  238. // page_view_regexes is obsolete and not used. https_request_regexes, which
  239. // are actually host/domain name regexes, are used for host/domain name
  240. // bytes transferred metrics: tunneled traffic TLS SNI server names and HTTP
  241. // Host header host names are matched against these regexes to select flows
  242. // for bytes transferred counting.
  243. var regexpsNotices []string
  244. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  245. handshakeResponse.HttpsRequestRegexes)
  246. for _, notice := range regexpsNotices {
  247. NoticeWarning(notice)
  248. }
  249. }
  250. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  251. NoticeServerTimestamp(serverContext.serverHandshakeTimestamp)
  252. NoticeActiveAuthorizationIDs(handshakeResponse.ActiveAuthorizationIDs)
  253. NoticeTrafficRateLimits(
  254. handshakeResponse.UpstreamBytesPerSecond, handshakeResponse.DownstreamBytesPerSecond)
  255. if doTactics && handshakeResponse.TacticsPayload != nil &&
  256. networkID == serverContext.tunnel.config.GetNetworkID() {
  257. var payload *tactics.Payload
  258. err := json.Unmarshal(handshakeResponse.TacticsPayload, &payload)
  259. if err != nil {
  260. return errors.Trace(err)
  261. }
  262. // handshakeResponse.TacticsPayload may be "null", and payload
  263. // will successfully unmarshal as nil. As a result, the previous
  264. // handshakeResponse.TacticsPayload != nil test is insufficient.
  265. if payload != nil {
  266. tacticsRecord, err := tactics.HandleTacticsPayload(
  267. GetTacticsStorer(serverContext.tunnel.config),
  268. networkID,
  269. payload)
  270. if err != nil {
  271. return errors.Trace(err)
  272. }
  273. if tacticsRecord != nil &&
  274. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  275. err := serverContext.tunnel.config.SetClientParameters(
  276. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  277. if err != nil {
  278. NoticeInfo("apply handshake tactics failed: %s", err)
  279. }
  280. // The error will be due to invalid tactics values from
  281. // the server. When ApplyClientParameters fails, all
  282. // previous tactics values are left in place.
  283. }
  284. }
  285. }
  286. return nil
  287. }
  288. // DoConnectedRequest performs the "connected" API request. This request is
  289. // used for statistics, including unique user counting; reporting the full
  290. // tunnel establishment duration including the handshake request; and updated
  291. // fragmentor metrics.
  292. //
  293. // Users are not assigned identifiers. Instead, daily unique users are
  294. // calculated by having clients submit their last connected timestamp
  295. // (truncated to an hour, as a privacy measure). As client clocks are
  296. // unreliable, the server returns new last_connected values for the client to
  297. // store and send next time it connects.
  298. func (serverContext *ServerContext) DoConnectedRequest() error {
  299. // Limitation: as currently implemented, the last_connected exchange isn't a
  300. // distributed, atomic operation. When clients send the connected request,
  301. // the server may receive the request, count a unique user based on the
  302. // client's last_connected, and then the tunnel fails before the client
  303. // receives the response, so the client will not update its last_connected
  304. // value and submit the same one again, resulting in an inflated unique user
  305. // count.
  306. //
  307. // The SetInFlightConnectedRequest mechanism mitigates one class of connected
  308. // request interruption, a commanded shutdown in the middle of a connected
  309. // request, by allowing some time for the request to complete before
  310. // terminating the tunnel.
  311. //
  312. // TODO: consider extending the connected request protocol with additional
  313. // "acknowledgment" messages so that the server does not commit its unique
  314. // user count until after the client has acknowledged receipt and durable
  315. // storage of the new last_connected value.
  316. requestDone := make(chan struct{})
  317. defer close(requestDone)
  318. if !serverContext.tunnel.SetInFlightConnectedRequest(requestDone) {
  319. return errors.TraceNew("tunnel is closing")
  320. }
  321. defer serverContext.tunnel.SetInFlightConnectedRequest(nil)
  322. params := serverContext.getBaseAPIParameters(
  323. baseParametersOnlyUpstreamFragmentorDialParameters)
  324. lastConnected, err := getLastConnected()
  325. if err != nil {
  326. return errors.Trace(err)
  327. }
  328. params["last_connected"] = lastConnected
  329. // serverContext.tunnel.establishDuration is nanoseconds; report milliseconds
  330. params["establishment_duration"] =
  331. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/time.Millisecond)
  332. var response []byte
  333. if serverContext.psiphonHttpsClient == nil {
  334. request, err := serverContext.makeSSHAPIRequestPayload(params)
  335. if err != nil {
  336. return errors.Trace(err)
  337. }
  338. response, err = serverContext.tunnel.SendAPIRequest(
  339. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  340. if err != nil {
  341. return errors.Trace(err)
  342. }
  343. } else {
  344. // Legacy web service API request
  345. response, err = serverContext.doGetRequest(
  346. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  347. if err != nil {
  348. return errors.Trace(err)
  349. }
  350. }
  351. var connectedResponse protocol.ConnectedResponse
  352. err = json.Unmarshal(response, &connectedResponse)
  353. if err != nil {
  354. return errors.Trace(err)
  355. }
  356. err = SetKeyValue(
  357. datastoreLastConnectedKey, connectedResponse.ConnectedTimestamp)
  358. if err != nil {
  359. return errors.Trace(err)
  360. }
  361. return nil
  362. }
  363. func getLastConnected() (string, error) {
  364. lastConnected, err := GetKeyValue(datastoreLastConnectedKey)
  365. if err != nil {
  366. return "", errors.Trace(err)
  367. }
  368. if lastConnected == "" {
  369. lastConnected = "None"
  370. }
  371. return lastConnected, nil
  372. }
  373. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  374. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  375. return serverContext.statsRegexps
  376. }
  377. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  378. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  379. params := serverContext.getBaseAPIParameters(baseParametersNoDialParameters)
  380. // Note: ensure putBackStatusRequestPayload is called, to replace
  381. // payload for future attempt, in all failure cases.
  382. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  383. serverContext.tunnel.config,
  384. tunnel.dialParams.ServerEntry.IpAddress)
  385. if err != nil {
  386. return errors.Trace(err)
  387. }
  388. // Skip the request when there's no payload to send.
  389. if len(statusPayload) == 0 {
  390. return nil
  391. }
  392. var response []byte
  393. if serverContext.psiphonHttpsClient == nil {
  394. rawMessage := json.RawMessage(statusPayload)
  395. params["statusData"] = &rawMessage
  396. var request []byte
  397. request, err = serverContext.makeSSHAPIRequestPayload(params)
  398. if err == nil {
  399. response, err = serverContext.tunnel.SendAPIRequest(
  400. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  401. }
  402. } else {
  403. // Legacy web service API request
  404. response, err = serverContext.doPostRequest(
  405. makeRequestUrl(serverContext.tunnel, "", "status", params),
  406. "application/json",
  407. bytes.NewReader(statusPayload))
  408. }
  409. if err != nil {
  410. // Resend the transfer stats and tunnel stats later
  411. // Note: potential duplicate reports if the server received and processed
  412. // the request but the client failed to receive the response.
  413. putBackStatusRequestPayload(statusPayloadInfo)
  414. return errors.Trace(err)
  415. }
  416. confirmStatusRequestPayload(statusPayloadInfo)
  417. var statusResponse protocol.StatusResponse
  418. err = json.Unmarshal(response, &statusResponse)
  419. if err != nil {
  420. return errors.Trace(err)
  421. }
  422. for _, serverEntryTag := range statusResponse.InvalidServerEntryTags {
  423. PruneServerEntry(serverContext.tunnel.config, serverEntryTag)
  424. }
  425. return nil
  426. }
  427. // statusRequestPayloadInfo is a temporary structure for data used to
  428. // either "clear" or "put back" status request payload data depending
  429. // on whether or not the request succeeded.
  430. type statusRequestPayloadInfo struct {
  431. serverId string
  432. transferStats *transferstats.AccumulatedStats
  433. persistentStats map[string][][]byte
  434. }
  435. func makeStatusRequestPayload(
  436. config *Config,
  437. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  438. transferStats := transferstats.TakeOutStatsForServer(serverId)
  439. hostBytes := transferStats.GetStatsForStatusRequest()
  440. persistentStats, err := TakeOutUnreportedPersistentStats(config)
  441. if err != nil {
  442. NoticeWarning(
  443. "TakeOutUnreportedPersistentStats failed: %s", errors.Trace(err))
  444. persistentStats = nil
  445. // Proceed with transferStats only
  446. }
  447. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  448. // There is no payload to send.
  449. return nil, nil, nil
  450. }
  451. payloadInfo := &statusRequestPayloadInfo{
  452. serverId, transferStats, persistentStats}
  453. payload := make(map[string]interface{})
  454. payload["host_bytes"] = hostBytes
  455. // We're not recording these fields, but legacy servers require them.
  456. payload["bytes_transferred"] = 0
  457. payload["page_views"] = make([]string, 0)
  458. payload["https_requests"] = make([]string, 0)
  459. persistentStatPayloadNames := make(map[string]string)
  460. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  461. persistentStatPayloadNames[datastorePersistentStatTypeFailedTunnel] = "failed_tunnel_stats"
  462. for statType, stats := range persistentStats {
  463. // Persistent stats records are already in JSON format
  464. jsonStats := make([]json.RawMessage, len(stats))
  465. for i, stat := range stats {
  466. jsonStats[i] = json.RawMessage(stat)
  467. }
  468. payload[persistentStatPayloadNames[statType]] = jsonStats
  469. }
  470. jsonPayload, err := json.Marshal(payload)
  471. if err != nil {
  472. // Send the transfer stats and tunnel stats later
  473. putBackStatusRequestPayload(payloadInfo)
  474. return nil, nil, errors.Trace(err)
  475. }
  476. return jsonPayload, payloadInfo, nil
  477. }
  478. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  479. transferstats.PutBackStatsForServer(
  480. payloadInfo.serverId, payloadInfo.transferStats)
  481. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  482. if err != nil {
  483. // These persistent stats records won't be resent until after a
  484. // datastore re-initialization.
  485. NoticeWarning(
  486. "PutBackUnreportedPersistentStats failed: %s", errors.Trace(err))
  487. }
  488. }
  489. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  490. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  491. if err != nil {
  492. // These persistent stats records may be resent.
  493. NoticeWarning(
  494. "ClearReportedPersistentStats failed: %s", errors.Trace(err))
  495. }
  496. }
  497. // RecordRemoteServerListStat records a completed common or OSL remote server
  498. // list resource download.
  499. //
  500. // The RSL download event could occur when the client is unable to immediately
  501. // send a status request to a server, so these records are stored in the
  502. // persistent datastore and reported via subsequent status requests sent to
  503. // any Psiphon server.
  504. //
  505. // Note that some common event field values may change between the stat
  506. // recording and reporting, including client geolocation and host_id.
  507. //
  508. // The bytes/duration fields reflect the size and download time for the _last
  509. // chunk only_ in the case of a resumed download. The purpose of these fields
  510. // is to calculate rough data transfer rates. Both bytes and duration are
  511. // included in the log, to allow for filtering out of small transfers which
  512. // may not produce accurate rate numbers.
  513. //
  514. // Multiple "status" requests may be in flight at once (due to multi-tunnel,
  515. // asynchronous final status retry, and aggressive status requests for
  516. // pre-registered tunnels), To avoid duplicate reporting, persistent stats
  517. // records are "taken-out" by a status request and then "put back" in case the
  518. // request fails.
  519. //
  520. // Duplicate reporting may also occur when a server receives and processes a
  521. // status request but the client fails to receive the response.
  522. func RecordRemoteServerListStat(
  523. config *Config,
  524. tunneled bool,
  525. url string,
  526. etag string,
  527. bytes int64,
  528. duration time.Duration,
  529. authenticated bool) error {
  530. if !config.GetClientParameters().Get().WeightedCoinFlip(
  531. parameters.RecordRemoteServerListPersistentStatsProbability) {
  532. return nil
  533. }
  534. params := make(common.APIParameters)
  535. params["session_id"] = config.SessionID
  536. params["propagation_channel_id"] = config.PropagationChannelId
  537. params["sponsor_id"] = config.GetSponsorID()
  538. params["client_version"] = config.ClientVersion
  539. params["client_platform"] = config.ClientPlatform
  540. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  541. if config.DeviceRegion != "" {
  542. params["device_region"] = config.DeviceRegion
  543. }
  544. params["client_download_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  545. tunneledStr := "0"
  546. if tunneled {
  547. tunneledStr = "1"
  548. }
  549. params["tunneled"] = tunneledStr
  550. params["url"] = url
  551. params["etag"] = etag
  552. params["bytes"] = fmt.Sprintf("%d", bytes)
  553. // duration is nanoseconds; report milliseconds
  554. params["duration"] = fmt.Sprintf("%d", duration/time.Millisecond)
  555. authenticatedStr := "0"
  556. if authenticated {
  557. authenticatedStr = "1"
  558. }
  559. params["authenticated"] = authenticatedStr
  560. remoteServerListStatJson, err := json.Marshal(params)
  561. if err != nil {
  562. return errors.Trace(err)
  563. }
  564. return StorePersistentStat(
  565. config, datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  566. }
  567. // RecordFailedTunnelStat records metrics for a failed tunnel dial, including
  568. // dial parameters and error condition (tunnelErr).
  569. //
  570. // This uses the same reporting facility, with the same caveats, as
  571. // RecordRemoteServerListStat.
  572. func RecordFailedTunnelStat(
  573. config *Config,
  574. dialParams *DialParameters,
  575. livenessTestMetrics *livenessTestMetrics,
  576. bytesUp int64,
  577. bytesDown int64,
  578. tunnelErr error) error {
  579. if !config.GetClientParameters().Get().WeightedCoinFlip(
  580. parameters.RecordFailedTunnelPersistentStatsProbability) {
  581. return nil
  582. }
  583. lastConnected, err := getLastConnected()
  584. if err != nil {
  585. return errors.Trace(err)
  586. }
  587. params := getBaseAPIParameters(baseParametersAll, config, dialParams)
  588. delete(params, "server_secret")
  589. params["server_entry_tag"] = dialParams.ServerEntry.Tag
  590. params["last_connected"] = lastConnected
  591. params["client_failed_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  592. if livenessTestMetrics != nil {
  593. params["liveness_test_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.UpstreamBytes)
  594. params["liveness_test_sent_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.SentUpstreamBytes)
  595. params["liveness_test_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.DownstreamBytes)
  596. params["liveness_test_received_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.ReceivedDownstreamBytes)
  597. }
  598. if bytesUp >= 0 {
  599. params["bytes_up"] = fmt.Sprintf("%d", bytesUp)
  600. }
  601. if bytesDown >= 0 {
  602. params["bytes_down"] = fmt.Sprintf("%d", bytesDown)
  603. }
  604. // Ensure direct server IPs are not exposed in logs. The "net" package, and
  605. // possibly other 3rd party packages, will include destination addresses in
  606. // I/O error messages.
  607. tunnelError := StripIPAddressesString(tunnelErr.Error())
  608. params["tunnel_error"] = tunnelError
  609. failedTunnelStatJson, err := json.Marshal(params)
  610. if err != nil {
  611. return errors.Trace(err)
  612. }
  613. return StorePersistentStat(
  614. config, datastorePersistentStatTypeFailedTunnel, failedTunnelStatJson)
  615. }
  616. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  617. func (serverContext *ServerContext) doGetRequest(
  618. requestUrl string) (responseBody []byte, err error) {
  619. request, err := http.NewRequest("GET", requestUrl, nil)
  620. if err != nil {
  621. return nil, errors.Trace(err)
  622. }
  623. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  624. response, err := serverContext.psiphonHttpsClient.Do(request)
  625. if err == nil && response.StatusCode != http.StatusOK {
  626. response.Body.Close()
  627. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  628. }
  629. if err != nil {
  630. // Trim this error since it may include long URLs
  631. return nil, errors.Trace(TrimError(err))
  632. }
  633. defer response.Body.Close()
  634. body, err := ioutil.ReadAll(response.Body)
  635. if err != nil {
  636. return nil, errors.Trace(err)
  637. }
  638. return body, nil
  639. }
  640. // doPostRequest makes a tunneled HTTPS POST request.
  641. func (serverContext *ServerContext) doPostRequest(
  642. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  643. request, err := http.NewRequest("POST", requestUrl, body)
  644. if err != nil {
  645. return nil, errors.Trace(err)
  646. }
  647. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  648. request.Header.Set("Content-Type", bodyType)
  649. response, err := serverContext.psiphonHttpsClient.Do(request)
  650. if err == nil && response.StatusCode != http.StatusOK {
  651. response.Body.Close()
  652. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  653. }
  654. if err != nil {
  655. // Trim this error since it may include long URLs
  656. return nil, errors.Trace(TrimError(err))
  657. }
  658. defer response.Body.Close()
  659. responseBody, err = ioutil.ReadAll(response.Body)
  660. if err != nil {
  661. return nil, errors.Trace(err)
  662. }
  663. return responseBody, nil
  664. }
  665. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  666. func (serverContext *ServerContext) makeSSHAPIRequestPayload(
  667. params common.APIParameters) ([]byte, error) {
  668. jsonPayload, err := json.Marshal(params)
  669. if err != nil {
  670. return nil, errors.Trace(err)
  671. }
  672. return jsonPayload, nil
  673. }
  674. type baseParametersFilter int
  675. const (
  676. baseParametersAll baseParametersFilter = iota
  677. baseParametersOnlyUpstreamFragmentorDialParameters
  678. baseParametersNoDialParameters
  679. )
  680. func (serverContext *ServerContext) getBaseAPIParameters(
  681. filter baseParametersFilter) common.APIParameters {
  682. params := getBaseAPIParameters(
  683. filter,
  684. serverContext.tunnel.config,
  685. serverContext.tunnel.dialParams)
  686. // Add a random amount of padding to defend against API call traffic size
  687. // fingerprints. The "pad_response" field instructs the server to pad its
  688. // response accordingly.
  689. p := serverContext.tunnel.config.GetClientParameters().Get()
  690. minUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMinBytes)
  691. maxUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMaxBytes)
  692. minDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMinBytes)
  693. maxDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMaxBytes)
  694. if maxUpstreamPadding > 0 {
  695. size := serverContext.paddingPRNG.Range(minUpstreamPadding, maxUpstreamPadding)
  696. params["padding"] = strings.Repeat(" ", size)
  697. }
  698. if maxDownstreamPadding > 0 {
  699. size := serverContext.paddingPRNG.Range(minDownstreamPadding, maxDownstreamPadding)
  700. params["pad_response"] = strconv.Itoa(size)
  701. }
  702. return params
  703. }
  704. // getBaseAPIParameters returns all the common API parameters that are
  705. // included with each Psiphon API request. These common parameters are used
  706. // for metrics.
  707. func getBaseAPIParameters(
  708. filter baseParametersFilter,
  709. config *Config,
  710. dialParams *DialParameters) common.APIParameters {
  711. params := make(common.APIParameters)
  712. params["session_id"] = config.SessionID
  713. params["client_session_id"] = config.SessionID
  714. params["server_secret"] = dialParams.ServerEntry.WebServerSecret
  715. params["propagation_channel_id"] = config.PropagationChannelId
  716. params["sponsor_id"] = config.GetSponsorID()
  717. params["client_version"] = config.ClientVersion
  718. params["client_platform"] = config.ClientPlatform
  719. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  720. params["tunnel_whole_device"] = strconv.Itoa(config.TunnelWholeDevice)
  721. // Blank parameters must be omitted.
  722. if config.DeviceRegion != "" {
  723. params["device_region"] = config.DeviceRegion
  724. }
  725. if filter == baseParametersAll {
  726. params["relay_protocol"] = dialParams.TunnelProtocol
  727. params["network_type"] = dialParams.GetNetworkType()
  728. if dialParams.BPFProgramName != "" {
  729. params["client_bpf"] = dialParams.BPFProgramName
  730. }
  731. if dialParams.SelectedSSHClientVersion {
  732. params["ssh_client_version"] = dialParams.SSHClientVersion
  733. }
  734. if dialParams.UpstreamProxyType != "" {
  735. params["upstream_proxy_type"] = dialParams.UpstreamProxyType
  736. }
  737. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  738. params["upstream_proxy_custom_header_names"] = dialParams.UpstreamProxyCustomHeaderNames
  739. }
  740. if dialParams.FrontingProviderID != "" {
  741. params["fronting_provider_id"] = dialParams.FrontingProviderID
  742. }
  743. if dialParams.MeekDialAddress != "" {
  744. params["meek_dial_address"] = dialParams.MeekDialAddress
  745. }
  746. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  747. if meekResolvedIPAddress != "" {
  748. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  749. }
  750. if dialParams.MeekSNIServerName != "" {
  751. params["meek_sni_server_name"] = dialParams.MeekSNIServerName
  752. }
  753. if dialParams.MeekHostHeader != "" {
  754. params["meek_host_header"] = dialParams.MeekHostHeader
  755. }
  756. // MeekTransformedHostName is meaningful when meek is used, which is when
  757. // MeekDialAddress != ""
  758. if dialParams.MeekDialAddress != "" {
  759. transformedHostName := "0"
  760. if dialParams.MeekTransformedHostName {
  761. transformedHostName = "1"
  762. }
  763. params["meek_transformed_host_name"] = transformedHostName
  764. }
  765. if dialParams.SelectedUserAgent {
  766. params["user_agent"] = dialParams.UserAgent
  767. }
  768. if dialParams.SelectedTLSProfile {
  769. params["tls_profile"] = dialParams.TLSProfile
  770. params["tls_version"] = dialParams.GetTLSVersionForMetrics()
  771. }
  772. if dialParams.ServerEntry.Region != "" {
  773. params["server_entry_region"] = dialParams.ServerEntry.Region
  774. }
  775. if dialParams.ServerEntry.LocalSource != "" {
  776. params["server_entry_source"] = dialParams.ServerEntry.LocalSource
  777. }
  778. // As with last_connected, this timestamp stat, which may be a precise
  779. // handshake request server timestamp, is truncated to hour granularity to
  780. // avoid introducing a reconstructable cross-session user trace into server
  781. // logs.
  782. localServerEntryTimestamp := common.TruncateTimestampToHour(
  783. dialParams.ServerEntry.LocalTimestamp)
  784. if localServerEntryTimestamp != "" {
  785. params["server_entry_timestamp"] = localServerEntryTimestamp
  786. }
  787. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] =
  788. config.GetClientParameters().Get().Tag()
  789. if dialParams.DialPortNumber != "" {
  790. params["dial_port_number"] = dialParams.DialPortNumber
  791. }
  792. if dialParams.QUICVersion != "" {
  793. params["quic_version"] = dialParams.QUICVersion
  794. }
  795. if dialParams.QUICDialSNIAddress != "" {
  796. params["quic_dial_sni_address"] = dialParams.QUICDialSNIAddress
  797. }
  798. isReplay := "0"
  799. if dialParams.IsReplay {
  800. isReplay = "1"
  801. }
  802. params["is_replay"] = isReplay
  803. if config.EgressRegion != "" {
  804. params["egress_region"] = config.EgressRegion
  805. }
  806. // dialParams.DialDuration is nanoseconds; report milliseconds
  807. params["dial_duration"] = fmt.Sprintf("%d", dialParams.DialDuration/time.Millisecond)
  808. params["candidate_number"] = strconv.Itoa(dialParams.CandidateNumber)
  809. params["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  810. if dialParams.NetworkLatencyMultiplier != 0.0 {
  811. params["network_latency_multiplier"] =
  812. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  813. }
  814. if dialParams.DialConnMetrics != nil {
  815. metrics := dialParams.DialConnMetrics.GetMetrics()
  816. for name, value := range metrics {
  817. params[name] = fmt.Sprintf("%v", value)
  818. }
  819. }
  820. if dialParams.ObfuscatedSSHConnMetrics != nil {
  821. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  822. for name, value := range metrics {
  823. params[name] = fmt.Sprintf("%v", value)
  824. }
  825. }
  826. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  827. if dialParams.DialConnMetrics != nil {
  828. names := fragmentor.GetUpstreamMetricsNames()
  829. metrics := dialParams.DialConnMetrics.GetMetrics()
  830. for name, value := range metrics {
  831. if common.Contains(names, name) {
  832. params[name] = fmt.Sprintf("%v", value)
  833. }
  834. }
  835. }
  836. }
  837. return params
  838. }
  839. // makeRequestUrl makes a URL for a web service API request.
  840. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  841. var requestUrl bytes.Buffer
  842. if port == "" {
  843. port = tunnel.dialParams.ServerEntry.WebServerPort
  844. }
  845. requestUrl.WriteString("https://")
  846. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  847. requestUrl.WriteString(":")
  848. requestUrl.WriteString(port)
  849. requestUrl.WriteString("/")
  850. requestUrl.WriteString(path)
  851. if len(params) > 0 {
  852. queryParams := url.Values{}
  853. for name, value := range params {
  854. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  855. // parameter, which has a different type. This parameter is not recognized
  856. // by legacy servers.
  857. switch v := value.(type) {
  858. case string:
  859. queryParams.Set(name, v)
  860. case []string:
  861. // String array param encoded as JSON
  862. jsonValue, err := json.Marshal(v)
  863. if err != nil {
  864. break
  865. }
  866. queryParams.Set(name, string(jsonValue))
  867. }
  868. }
  869. requestUrl.WriteString("?")
  870. requestUrl.WriteString(queryParams.Encode())
  871. }
  872. return requestUrl.String()
  873. }
  874. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  875. // requests and which validates the web server using the Psiphon server entry web server
  876. // certificate.
  877. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  878. certificate, err := DecodeCertificate(
  879. tunnel.dialParams.ServerEntry.WebServerCertificate)
  880. if err != nil {
  881. return nil, errors.Trace(err)
  882. }
  883. tunneledDialer := func(_ context.Context, _, addr string) (conn net.Conn, err error) {
  884. return tunnel.sshClient.Dial("tcp", addr)
  885. }
  886. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  887. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  888. // the request. While it's possible to add a timeout here, we leave it with no explicit
  889. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  890. // alives will cause the tunnel to close.
  891. dialer := NewCustomTLSDialer(
  892. &CustomTLSConfig{
  893. ClientParameters: tunnel.config.clientParameters,
  894. Dial: tunneledDialer,
  895. VerifyLegacyCertificate: certificate,
  896. })
  897. transport := &http.Transport{
  898. DialTLS: func(network, addr string) (net.Conn, error) {
  899. return dialer(context.Background(), network, addr)
  900. },
  901. Dial: func(network, addr string) (net.Conn, error) {
  902. return nil, errors.TraceNew("HTTP not supported")
  903. },
  904. }
  905. return &http.Client{
  906. Transport: transport,
  907. }, nil
  908. }
  909. func HandleServerRequest(
  910. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  911. switch name {
  912. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  913. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  914. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  915. return HandleAlertRequest(tunnelOwner, tunnel, payload)
  916. }
  917. return errors.Tracef("invalid request name: %s", name)
  918. }
  919. func HandleOSLRequest(
  920. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  921. var oslRequest protocol.OSLRequest
  922. err := json.Unmarshal(payload, &oslRequest)
  923. if err != nil {
  924. return errors.Trace(err)
  925. }
  926. if oslRequest.ClearLocalSLOKs {
  927. DeleteSLOKs()
  928. }
  929. seededNewSLOK := false
  930. for _, slok := range oslRequest.SeedPayload.SLOKs {
  931. duplicate, err := SetSLOK(slok.ID, slok.Key)
  932. if err != nil {
  933. // TODO: return error to trigger retry?
  934. NoticeWarning("SetSLOK failed: %s", errors.Trace(err))
  935. } else if !duplicate {
  936. seededNewSLOK = true
  937. }
  938. if tunnel.config.EmitSLOKs {
  939. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  940. }
  941. }
  942. if seededNewSLOK {
  943. tunnelOwner.SignalSeededNewSLOK()
  944. }
  945. return nil
  946. }
  947. func HandleAlertRequest(
  948. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  949. var alertRequest protocol.AlertRequest
  950. err := json.Unmarshal(payload, &alertRequest)
  951. if err != nil {
  952. return errors.Trace(err)
  953. }
  954. if tunnel.config.EmitServerAlerts {
  955. NoticeServerAlert(alertRequest)
  956. }
  957. return nil
  958. }