serverApi.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. "errors"
  27. "fmt"
  28. "io"
  29. "io/ioutil"
  30. "net"
  31. "net/http"
  32. "net/url"
  33. "strconv"
  34. "sync/atomic"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  40. )
  41. // ServerContext is a utility struct which holds all of the data associated
  42. // with a Psiphon server connection. In addition to the established tunnel, this
  43. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  44. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  45. // API through SSH requests made directly through the tunnel's SSH client.
  46. type ServerContext struct {
  47. // Note: 64-bit ints used with atomic operations are placed
  48. // at the start of struct to ensure 64-bit alignment.
  49. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  50. tunnelNumber int64
  51. sessionId string
  52. tunnel *Tunnel
  53. psiphonHttpsClient *http.Client
  54. statsRegexps *transferstats.Regexps
  55. clientRegion string
  56. clientUpgradeVersion string
  57. serverHandshakeTimestamp string
  58. }
  59. // nextTunnelNumber is a monotonically increasing number assigned to each
  60. // successive tunnel connection. The sessionId and tunnelNumber together
  61. // form a globally unique identifier for tunnels, which is used for
  62. // stats. Note that the number is increasing but not necessarily
  63. // consecutive for each active tunnel in session.
  64. var nextTunnelNumber int64
  65. // MakeSessionId creates a new session ID. The same session ID is used across
  66. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  67. // instance.
  68. // In server-side stats, we now consider a "session" to be the lifetime of the
  69. // Controller (e.g., the user's commanded start and stop) and we measure this
  70. // duration as well as the duration of each tunnel within the session.
  71. func MakeSessionId() (sessionId string, err error) {
  72. randomId, err := common.MakeSecureRandomBytes(protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  73. if err != nil {
  74. return "", common.ContextError(err)
  75. }
  76. return hex.EncodeToString(randomId), nil
  77. }
  78. // NewServerContext makes the tunneled handshake request to the Psiphon server
  79. // and returns a ServerContext struct for use with subsequent Psiphon server API
  80. // requests (e.g., periodic connected and status requests).
  81. func NewServerContext(tunnel *Tunnel) (*ServerContext, error) {
  82. // For legacy servers, set up psiphonHttpsClient for
  83. // accessing the Psiphon API via the web service.
  84. var psiphonHttpsClient *http.Client
  85. if !tunnel.serverEntry.SupportsSSHAPIRequests() ||
  86. tunnel.config.TargetApiProtocol == protocol.PSIPHON_WEB_API_PROTOCOL {
  87. var err error
  88. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  89. if err != nil {
  90. return nil, common.ContextError(err)
  91. }
  92. }
  93. serverContext := &ServerContext{
  94. sessionId: tunnel.sessionId,
  95. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  96. tunnel: tunnel,
  97. psiphonHttpsClient: psiphonHttpsClient,
  98. }
  99. ignoreRegexps := tunnel.config.clientParameters.Get().Bool(parameters.IgnoreHandshakeStatsRegexps)
  100. err := serverContext.doHandshakeRequest(ignoreRegexps)
  101. if err != nil {
  102. return nil, common.ContextError(err)
  103. }
  104. return serverContext, nil
  105. }
  106. // doHandshakeRequest performs the "handshake" API request. The handshake
  107. // returns upgrade info, newly discovered server entries -- which are
  108. // stored -- and sponsor info (home pages, stat regexes).
  109. func (serverContext *ServerContext) doHandshakeRequest(
  110. ignoreStatsRegexps bool) error {
  111. params := serverContext.getBaseAPIParameters()
  112. doTactics := !serverContext.tunnel.config.DisableTactics &&
  113. serverContext.tunnel.config.networkIDGetter != nil
  114. networkID := ""
  115. if doTactics {
  116. // Limitation: it is assumed that the network ID obtained here is the
  117. // one that is active when the handshake request is received by the
  118. // server. However, it is remotely possible to switch networks
  119. // immediately after invoking the GetNetworkID callback and initiating
  120. // the handshake, if the tunnel protocol is meek.
  121. //
  122. // The response handling code below calls GetNetworkID again and ignores
  123. // any tactics payload if the network ID is not the same. While this
  124. // doesn't detect all cases of changing networks, it reduces the already
  125. // narrow window.
  126. networkID = serverContext.tunnel.config.networkIDGetter.GetNetworkID()
  127. err := tactics.SetTacticsAPIParameters(
  128. serverContext.tunnel.config.clientParameters, GetTacticsStorer(), networkID, params)
  129. if err != nil {
  130. return common.ContextError(err)
  131. }
  132. }
  133. var response []byte
  134. if serverContext.psiphonHttpsClient == nil {
  135. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] =
  136. serverContext.tunnel.config.GetAuthorizations()
  137. request, err := makeSSHAPIRequestPayload(params)
  138. if err != nil {
  139. return common.ContextError(err)
  140. }
  141. response, err = serverContext.tunnel.SendAPIRequest(
  142. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  143. if err != nil {
  144. return common.ContextError(err)
  145. }
  146. } else {
  147. // Legacy web service API request
  148. responseBody, err := serverContext.doGetRequest(
  149. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  150. if err != nil {
  151. return common.ContextError(err)
  152. }
  153. // Skip legacy format lines and just parse the JSON config line
  154. configLinePrefix := []byte("Config: ")
  155. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  156. if bytes.HasPrefix(line, configLinePrefix) {
  157. response = line[len(configLinePrefix):]
  158. break
  159. }
  160. }
  161. if len(response) == 0 {
  162. return common.ContextError(errors.New("no config line found"))
  163. }
  164. }
  165. // Legacy fields:
  166. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  167. // - 'ssh_session_id' is ignored; client session ID is used instead
  168. var handshakeResponse protocol.HandshakeResponse
  169. err := json.Unmarshal(response, &handshakeResponse)
  170. if err != nil {
  171. return common.ContextError(err)
  172. }
  173. serverContext.clientRegion = handshakeResponse.ClientRegion
  174. NoticeClientRegion(serverContext.clientRegion)
  175. var serverEntries []protocol.ServerEntryFields
  176. // Store discovered server entries
  177. // We use the server's time, as it's available here, for the server entry
  178. // timestamp since this is more reliable than the client time.
  179. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  180. serverEntryFields, err := protocol.DecodeServerEntryFields(
  181. encodedServerEntry,
  182. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  183. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  184. if err != nil {
  185. return common.ContextError(err)
  186. }
  187. err = protocol.ValidateServerEntryFields(serverEntryFields)
  188. if err != nil {
  189. // Skip this entry and continue with the next one
  190. NoticeAlert("invalid handshake server entry: %s", err)
  191. continue
  192. }
  193. serverEntries = append(serverEntries, serverEntryFields)
  194. }
  195. // The reason we are storing the entire array of server entries at once rather
  196. // than one at a time is that some desirable side-effects get triggered by
  197. // StoreServerEntries that don't get triggered by StoreServerEntry.
  198. err = StoreServerEntries(
  199. serverContext.tunnel.config,
  200. serverEntries,
  201. true)
  202. if err != nil {
  203. return common.ContextError(err)
  204. }
  205. NoticeHomepages(handshakeResponse.Homepages)
  206. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  207. if handshakeResponse.UpgradeClientVersion != "" {
  208. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  209. } else {
  210. NoticeClientIsLatestVersion("")
  211. }
  212. if !ignoreStatsRegexps {
  213. var regexpsNotices []string
  214. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  215. handshakeResponse.PageViewRegexes,
  216. handshakeResponse.HttpsRequestRegexes)
  217. for _, notice := range regexpsNotices {
  218. NoticeAlert(notice)
  219. }
  220. }
  221. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  222. NoticeServerTimestamp(serverContext.serverHandshakeTimestamp)
  223. NoticeActiveAuthorizationIDs(handshakeResponse.ActiveAuthorizationIDs)
  224. if doTactics && handshakeResponse.TacticsPayload != nil &&
  225. networkID == serverContext.tunnel.config.networkIDGetter.GetNetworkID() {
  226. var payload *tactics.Payload
  227. err := json.Unmarshal(handshakeResponse.TacticsPayload, &payload)
  228. if err != nil {
  229. return common.ContextError(err)
  230. }
  231. // handshakeResponse.TacticsPayload may be "null", and payload
  232. // will successfully unmarshal as nil. As a result, the previous
  233. // handshakeResponse.TacticsPayload != nil test is insufficient.
  234. if payload != nil {
  235. tacticsRecord, err := tactics.HandleTacticsPayload(
  236. GetTacticsStorer(),
  237. networkID,
  238. payload)
  239. if err != nil {
  240. return common.ContextError(err)
  241. }
  242. if tacticsRecord != nil &&
  243. common.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  244. err := serverContext.tunnel.config.SetClientParameters(
  245. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  246. if err != nil {
  247. NoticeInfo("apply handshake tactics failed: %s", err)
  248. }
  249. // The error will be due to invalid tactics values from
  250. // the server. When ApplyClientParameters fails, all
  251. // previous tactics values are left in place.
  252. }
  253. }
  254. }
  255. return nil
  256. }
  257. // DoConnectedRequest performs the "connected" API request. This request is
  258. // used for statistics. The server returns a last_connected token for
  259. // the client to store and send next time it connects. This token is
  260. // a timestamp (using the server clock, and should be rounded to the
  261. // nearest hour) which is used to determine when a connection represents
  262. // a unique user for a time period.
  263. func (serverContext *ServerContext) DoConnectedRequest() error {
  264. params := serverContext.getBaseAPIParameters()
  265. lastConnected, err := GetKeyValue(datastoreLastConnectedKey)
  266. if err != nil {
  267. return common.ContextError(err)
  268. }
  269. if lastConnected == "" {
  270. lastConnected = "None"
  271. }
  272. params["last_connected"] = lastConnected
  273. // serverContext.tunnel.establishDuration is nanoseconds; divide to get to milliseconds
  274. params["establishment_duration"] =
  275. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/1000000)
  276. var response []byte
  277. if serverContext.psiphonHttpsClient == nil {
  278. request, err := makeSSHAPIRequestPayload(params)
  279. if err != nil {
  280. return common.ContextError(err)
  281. }
  282. response, err = serverContext.tunnel.SendAPIRequest(
  283. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  284. if err != nil {
  285. return common.ContextError(err)
  286. }
  287. } else {
  288. // Legacy web service API request
  289. response, err = serverContext.doGetRequest(
  290. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  291. if err != nil {
  292. return common.ContextError(err)
  293. }
  294. }
  295. var connectedResponse protocol.ConnectedResponse
  296. err = json.Unmarshal(response, &connectedResponse)
  297. if err != nil {
  298. return common.ContextError(err)
  299. }
  300. err = SetKeyValue(
  301. datastoreLastConnectedKey, connectedResponse.ConnectedTimestamp)
  302. if err != nil {
  303. return common.ContextError(err)
  304. }
  305. return nil
  306. }
  307. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  308. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  309. return serverContext.statsRegexps
  310. }
  311. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  312. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  313. params := serverContext.getStatusParams(true)
  314. // Note: ensure putBackStatusRequestPayload is called, to replace
  315. // payload for future attempt, in all failure cases.
  316. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  317. serverContext.tunnel.config.clientParameters,
  318. tunnel.serverEntry.IpAddress)
  319. if err != nil {
  320. return common.ContextError(err)
  321. }
  322. // Skip the request when there's no payload to send.
  323. if len(statusPayload) == 0 {
  324. return nil
  325. }
  326. if serverContext.psiphonHttpsClient == nil {
  327. rawMessage := json.RawMessage(statusPayload)
  328. params["statusData"] = &rawMessage
  329. var request []byte
  330. request, err = makeSSHAPIRequestPayload(params)
  331. if err == nil {
  332. _, err = serverContext.tunnel.SendAPIRequest(
  333. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  334. }
  335. } else {
  336. // Legacy web service API request
  337. _, err = serverContext.doPostRequest(
  338. makeRequestUrl(serverContext.tunnel, "", "status", params),
  339. "application/json",
  340. bytes.NewReader(statusPayload))
  341. }
  342. if err != nil {
  343. // Resend the transfer stats and tunnel stats later
  344. // Note: potential duplicate reports if the server received and processed
  345. // the request but the client failed to receive the response.
  346. putBackStatusRequestPayload(statusPayloadInfo)
  347. return common.ContextError(err)
  348. }
  349. confirmStatusRequestPayload(statusPayloadInfo)
  350. return nil
  351. }
  352. func (serverContext *ServerContext) getStatusParams(
  353. isTunneled bool) common.APIParameters {
  354. params := serverContext.getBaseAPIParameters()
  355. // Add a random amount of padding to help prevent stats updates from being
  356. // a predictable size (which often happens when the connection is quiet).
  357. // TODO: base64 encoding of padding means the padding size is not exactly
  358. // [PADDING_MIN_BYTES, PADDING_MAX_BYTES].
  359. p := serverContext.tunnel.config.clientParameters.Get()
  360. randomPadding, err := common.MakeSecureRandomPadding(
  361. p.Int(parameters.PsiphonAPIStatusRequestPaddingMinBytes),
  362. p.Int(parameters.PsiphonAPIStatusRequestPaddingMaxBytes))
  363. p = nil
  364. if err != nil {
  365. NoticeAlert("MakeSecureRandomPadding failed: %s", common.ContextError(err))
  366. // Proceed without random padding
  367. randomPadding = make([]byte, 0)
  368. }
  369. params["padding"] = base64.StdEncoding.EncodeToString(randomPadding)
  370. // Legacy clients set "connected" to "0" when disconnecting, and this value
  371. // is used to calculate session duration estimates. This is now superseded
  372. // by explicit tunnel stats duration reporting.
  373. // The legacy method of reconstructing session durations is not compatible
  374. // with this client's connected request retries and asynchronous final
  375. // status request attempts. So we simply set this "connected" flag to reflect
  376. // whether the request is sent tunneled or not.
  377. connected := "1"
  378. if !isTunneled {
  379. connected = "0"
  380. }
  381. params["connected"] = connected
  382. return params
  383. }
  384. // statusRequestPayloadInfo is a temporary structure for data used to
  385. // either "clear" or "put back" status request payload data depending
  386. // on whether or not the request succeeded.
  387. type statusRequestPayloadInfo struct {
  388. serverId string
  389. transferStats *transferstats.AccumulatedStats
  390. persistentStats map[string][][]byte
  391. }
  392. func makeStatusRequestPayload(
  393. clientParameters *parameters.ClientParameters,
  394. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  395. transferStats := transferstats.TakeOutStatsForServer(serverId)
  396. hostBytes := transferStats.GetStatsForStatusRequest()
  397. maxCount := clientParameters.Get().Int(parameters.PsiphonAPIPersistentStatsMaxCount)
  398. persistentStats, err := TakeOutUnreportedPersistentStats(maxCount)
  399. if err != nil {
  400. NoticeAlert(
  401. "TakeOutUnreportedPersistentStats failed: %s", common.ContextError(err))
  402. persistentStats = nil
  403. // Proceed with transferStats only
  404. }
  405. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  406. // There is no payload to send.
  407. return nil, nil, nil
  408. }
  409. payloadInfo := &statusRequestPayloadInfo{
  410. serverId, transferStats, persistentStats}
  411. payload := make(map[string]interface{})
  412. payload["host_bytes"] = hostBytes
  413. // We're not recording these fields, but legacy servers require them.
  414. payload["bytes_transferred"] = 0
  415. payload["page_views"] = make([]string, 0)
  416. payload["https_requests"] = make([]string, 0)
  417. persistentStatPayloadNames := make(map[string]string)
  418. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  419. for statType, stats := range persistentStats {
  420. // Persistent stats records are already in JSON format
  421. jsonStats := make([]json.RawMessage, len(stats))
  422. for i, stat := range stats {
  423. jsonStats[i] = json.RawMessage(stat)
  424. }
  425. payload[persistentStatPayloadNames[statType]] = jsonStats
  426. }
  427. jsonPayload, err := json.Marshal(payload)
  428. if err != nil {
  429. // Send the transfer stats and tunnel stats later
  430. putBackStatusRequestPayload(payloadInfo)
  431. return nil, nil, common.ContextError(err)
  432. }
  433. return jsonPayload, payloadInfo, nil
  434. }
  435. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  436. transferstats.PutBackStatsForServer(
  437. payloadInfo.serverId, payloadInfo.transferStats)
  438. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  439. if err != nil {
  440. // These persistent stats records won't be resent until after a
  441. // datastore re-initialization.
  442. NoticeAlert(
  443. "PutBackUnreportedPersistentStats failed: %s", common.ContextError(err))
  444. }
  445. }
  446. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  447. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  448. if err != nil {
  449. // These persistent stats records may be resent.
  450. NoticeAlert(
  451. "ClearReportedPersistentStats failed: %s", common.ContextError(err))
  452. }
  453. }
  454. // RecordRemoteServerListStat records a completed common or OSL
  455. // remote server list resource download.
  456. //
  457. // The RSL download event could occur when the client is unable
  458. // to immediately send a status request to a server, so these
  459. // records are stored in the persistent datastore and reported
  460. // via subsequent status requests sent to any Psiphon server.
  461. //
  462. // Note that common event field values may change between the
  463. // stat recording and reporting include client geo data,
  464. // propagation channel, sponsor ID, client version. These are not
  465. // stored in the datastore (client region, in particular, since
  466. // that would create an on-disk record of user location).
  467. // TODO: the server could encrypt, with a nonce and key unknown to
  468. // the client, a blob containing this data; return it in the
  469. // handshake response; and the client could store and later report
  470. // this blob with its tunnel stats records.
  471. //
  472. // Multiple "status" requests may be in flight at once (due
  473. // to multi-tunnel, asynchronous final status retry, and
  474. // aggressive status requests for pre-registered tunnels),
  475. // To avoid duplicate reporting, persistent stats records are
  476. // "taken-out" by a status request and then "put back" in
  477. // case the request fails.
  478. //
  479. // Duplicate reporting may also occur when a server receives and
  480. // processes a status request but the client fails to receive
  481. // the response.
  482. func RecordRemoteServerListStat(
  483. url, etag string) error {
  484. remoteServerListStat := struct {
  485. ClientDownloadTimestamp string `json:"client_download_timestamp"`
  486. URL string `json:"url"`
  487. ETag string `json:"etag"`
  488. }{
  489. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  490. url,
  491. etag,
  492. }
  493. remoteServerListStatJson, err := json.Marshal(remoteServerListStat)
  494. if err != nil {
  495. return common.ContextError(err)
  496. }
  497. return StorePersistentStat(
  498. datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  499. }
  500. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  501. func (serverContext *ServerContext) doGetRequest(
  502. requestUrl string) (responseBody []byte, err error) {
  503. request, err := http.NewRequest("GET", requestUrl, nil)
  504. if err != nil {
  505. return nil, common.ContextError(err)
  506. }
  507. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  508. response, err := serverContext.psiphonHttpsClient.Do(request)
  509. if err == nil && response.StatusCode != http.StatusOK {
  510. response.Body.Close()
  511. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  512. }
  513. if err != nil {
  514. // Trim this error since it may include long URLs
  515. return nil, common.ContextError(TrimError(err))
  516. }
  517. defer response.Body.Close()
  518. body, err := ioutil.ReadAll(response.Body)
  519. if err != nil {
  520. return nil, common.ContextError(err)
  521. }
  522. return body, nil
  523. }
  524. // doPostRequest makes a tunneled HTTPS POST request.
  525. func (serverContext *ServerContext) doPostRequest(
  526. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  527. request, err := http.NewRequest("POST", requestUrl, body)
  528. if err != nil {
  529. return nil, common.ContextError(err)
  530. }
  531. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  532. request.Header.Set("Content-Type", bodyType)
  533. response, err := serverContext.psiphonHttpsClient.Do(request)
  534. if err == nil && response.StatusCode != http.StatusOK {
  535. response.Body.Close()
  536. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  537. }
  538. if err != nil {
  539. // Trim this error since it may include long URLs
  540. return nil, common.ContextError(TrimError(err))
  541. }
  542. defer response.Body.Close()
  543. responseBody, err = ioutil.ReadAll(response.Body)
  544. if err != nil {
  545. return nil, common.ContextError(err)
  546. }
  547. return responseBody, nil
  548. }
  549. func (serverContext *ServerContext) getBaseAPIParameters() common.APIParameters {
  550. return getBaseAPIParameters(
  551. serverContext.tunnel.config,
  552. serverContext.sessionId,
  553. serverContext.tunnel.serverEntry,
  554. serverContext.tunnel.protocol,
  555. serverContext.tunnel.dialStats)
  556. }
  557. // getBaseAPIParameters returns all the common API parameters that are
  558. // included with each Psiphon API request. These common parameters are used
  559. // for metrics.
  560. func getBaseAPIParameters(
  561. config *Config,
  562. sessionID string,
  563. serverEntry *protocol.ServerEntry,
  564. protocol string,
  565. dialStats *DialStats) common.APIParameters {
  566. params := make(common.APIParameters)
  567. params["session_id"] = sessionID
  568. params["client_session_id"] = sessionID
  569. params["server_secret"] = serverEntry.WebServerSecret
  570. params["propagation_channel_id"] = config.PropagationChannelId
  571. params["sponsor_id"] = config.GetSponsorID()
  572. params["client_version"] = config.ClientVersion
  573. params["relay_protocol"] = protocol
  574. params["client_platform"] = config.ClientPlatform
  575. params["client_build_rev"] = common.GetBuildInfo().BuildRev
  576. params["tunnel_whole_device"] = strconv.Itoa(config.TunnelWholeDevice)
  577. // The following parameters may be blank and must
  578. // not be sent to the server if blank.
  579. if config.DeviceRegion != "" {
  580. params["device_region"] = config.DeviceRegion
  581. }
  582. if dialStats.SelectedSSHClientVersion {
  583. params["ssh_client_version"] = dialStats.SSHClientVersion
  584. }
  585. if dialStats.UpstreamProxyType != "" {
  586. params["upstream_proxy_type"] = dialStats.UpstreamProxyType
  587. }
  588. if dialStats.UpstreamProxyCustomHeaderNames != nil {
  589. params["upstream_proxy_custom_header_names"] = dialStats.UpstreamProxyCustomHeaderNames
  590. }
  591. if dialStats.MeekDialAddress != "" {
  592. params["meek_dial_address"] = dialStats.MeekDialAddress
  593. }
  594. meekResolvedIPAddress := dialStats.MeekResolvedIPAddress.Load().(string)
  595. if meekResolvedIPAddress != "" {
  596. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  597. }
  598. if dialStats.MeekSNIServerName != "" {
  599. params["meek_sni_server_name"] = dialStats.MeekSNIServerName
  600. }
  601. if dialStats.MeekHostHeader != "" {
  602. params["meek_host_header"] = dialStats.MeekHostHeader
  603. }
  604. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  605. if dialStats.MeekDialAddress != "" {
  606. transformedHostName := "0"
  607. if dialStats.MeekTransformedHostName {
  608. transformedHostName = "1"
  609. }
  610. params["meek_transformed_host_name"] = transformedHostName
  611. }
  612. if dialStats.SelectedUserAgent {
  613. params["user_agent"] = dialStats.UserAgent
  614. }
  615. if dialStats.SelectedTLSProfile {
  616. params["tls_profile"] = dialStats.TLSProfile
  617. }
  618. if serverEntry.Region != "" {
  619. params["server_entry_region"] = serverEntry.Region
  620. }
  621. if serverEntry.LocalSource != "" {
  622. params["server_entry_source"] = serverEntry.LocalSource
  623. }
  624. // As with last_connected, this timestamp stat, which may be
  625. // a precise handshake request server timestamp, is truncated
  626. // to hour granularity to avoid introducing a reconstructable
  627. // cross-session user trace into server logs.
  628. localServerEntryTimestamp := common.TruncateTimestampToHour(serverEntry.LocalTimestamp)
  629. if localServerEntryTimestamp != "" {
  630. params["server_entry_timestamp"] = localServerEntryTimestamp
  631. }
  632. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] = config.clientParameters.Get().Tag()
  633. if dialStats.DialPortNumber != "" {
  634. params["dial_port_number"] = dialStats.DialPortNumber
  635. }
  636. if dialStats.QUICVersion != "" {
  637. params["quic_version"] = dialStats.QUICVersion
  638. }
  639. if dialStats.QUICDialSNIAddress != "" {
  640. params["quic_dial_sni_address"] = dialStats.QUICDialSNIAddress
  641. }
  642. if dialStats.DialConnMetrics != nil {
  643. metrics := dialStats.DialConnMetrics.GetMetrics()
  644. for name, value := range metrics {
  645. params[name] = fmt.Sprintf("%v", value)
  646. }
  647. }
  648. if dialStats.ObfuscatedSSHConnMetrics != nil {
  649. metrics := dialStats.ObfuscatedSSHConnMetrics.GetMetrics()
  650. for name, value := range metrics {
  651. params[name] = fmt.Sprintf("%v", value)
  652. }
  653. }
  654. return params
  655. }
  656. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  657. func makeSSHAPIRequestPayload(params common.APIParameters) ([]byte, error) {
  658. jsonPayload, err := json.Marshal(params)
  659. if err != nil {
  660. return nil, common.ContextError(err)
  661. }
  662. return jsonPayload, nil
  663. }
  664. // makeRequestUrl makes a URL for a web service API request.
  665. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  666. var requestUrl bytes.Buffer
  667. if port == "" {
  668. port = tunnel.serverEntry.WebServerPort
  669. }
  670. requestUrl.WriteString("https://")
  671. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  672. requestUrl.WriteString(":")
  673. requestUrl.WriteString(port)
  674. requestUrl.WriteString("/")
  675. requestUrl.WriteString(path)
  676. if len(params) > 0 {
  677. queryParams := url.Values{}
  678. for name, value := range params {
  679. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  680. // parameter, which has a different type. This parameter is not recognized
  681. // by legacy servers.
  682. switch v := value.(type) {
  683. case string:
  684. queryParams.Set(name, v)
  685. case []string:
  686. // String array param encoded as JSON
  687. jsonValue, err := json.Marshal(v)
  688. if err != nil {
  689. break
  690. }
  691. queryParams.Set(name, string(jsonValue))
  692. }
  693. }
  694. requestUrl.WriteString("?")
  695. requestUrl.WriteString(queryParams.Encode())
  696. }
  697. return requestUrl.String()
  698. }
  699. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  700. // requests and which validates the web server using the Psiphon server entry web server
  701. // certificate.
  702. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  703. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  704. if err != nil {
  705. return nil, common.ContextError(err)
  706. }
  707. tunneledDialer := func(_ context.Context, _, addr string) (conn net.Conn, err error) {
  708. return tunnel.sshClient.Dial("tcp", addr)
  709. }
  710. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  711. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  712. // the request. While it's possible to add a timeout here, we leave it with no explicit
  713. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  714. // alives will cause the tunnel to close.
  715. dialer := NewCustomTLSDialer(
  716. &CustomTLSConfig{
  717. ClientParameters: tunnel.config.clientParameters,
  718. Dial: tunneledDialer,
  719. VerifyLegacyCertificate: certificate,
  720. })
  721. transport := &http.Transport{
  722. DialTLS: func(network, addr string) (net.Conn, error) {
  723. return dialer(context.Background(), network, addr)
  724. },
  725. Dial: func(network, addr string) (net.Conn, error) {
  726. return nil, errors.New("HTTP not supported")
  727. },
  728. }
  729. return &http.Client{
  730. Transport: transport,
  731. }, nil
  732. }
  733. func HandleServerRequest(
  734. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  735. switch name {
  736. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  737. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  738. }
  739. return common.ContextError(fmt.Errorf("invalid request name: %s", name))
  740. }
  741. func HandleOSLRequest(
  742. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  743. var oslRequest protocol.OSLRequest
  744. err := json.Unmarshal(payload, &oslRequest)
  745. if err != nil {
  746. return common.ContextError(err)
  747. }
  748. if oslRequest.ClearLocalSLOKs {
  749. DeleteSLOKs()
  750. }
  751. seededNewSLOK := false
  752. for _, slok := range oslRequest.SeedPayload.SLOKs {
  753. duplicate, err := SetSLOK(slok.ID, slok.Key)
  754. if err != nil {
  755. // TODO: return error to trigger retry?
  756. NoticeAlert("SetSLOK failed: %s", common.ContextError(err))
  757. } else if !duplicate {
  758. seededNewSLOK = true
  759. }
  760. if tunnel.config.EmitSLOKs {
  761. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  762. }
  763. }
  764. if seededNewSLOK {
  765. tunnelOwner.SignalSeededNewSLOK()
  766. }
  767. return nil
  768. }