serverApi.go 31 KB

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