serverApi.go 31 KB

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