serverApi.go 31 KB

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