serverApi.go 30 KB

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