serverApi.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. "encoding/base64"
  23. "encoding/hex"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "net/url"
  32. "strconv"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  38. )
  39. // ServerContext is a utility struct which holds all of the data associated
  40. // with a Psiphon server connection. In addition to the established tunnel, this
  41. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  42. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  43. // API through SSH requests made directly through the tunnel's SSH client.
  44. type ServerContext struct {
  45. // Note: 64-bit ints used with atomic operations are placed
  46. // at the start of struct to ensure 64-bit alignment.
  47. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  48. tunnelNumber int64
  49. sessionId string
  50. tunnel *Tunnel
  51. psiphonHttpsClient *http.Client
  52. statsRegexps *transferstats.Regexps
  53. clientRegion string
  54. clientUpgradeVersion string
  55. serverHandshakeTimestamp string
  56. }
  57. // nextTunnelNumber is a monotonically increasing number assigned to each
  58. // successive tunnel connection. The sessionId and tunnelNumber together
  59. // form a globally unique identifier for tunnels, which is used for
  60. // stats. Note that the number is increasing but not necessarily
  61. // consecutive for each active tunnel in session.
  62. var nextTunnelNumber int64
  63. // MakeSessionId creates a new session ID. The same session ID is used across
  64. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  65. // instance.
  66. // In server-side stats, we now consider a "session" to be the lifetime of the
  67. // Controller (e.g., the user's commanded start and stop) and we measure this
  68. // duration as well as the duration of each tunnel within the session.
  69. func MakeSessionId() (sessionId string, err error) {
  70. randomId, err := common.MakeSecureRandomBytes(protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  71. if err != nil {
  72. return "", common.ContextError(err)
  73. }
  74. return hex.EncodeToString(randomId), nil
  75. }
  76. // NewServerContext makes the tunnelled handshake request to the Psiphon server
  77. // and returns a ServerContext struct for use with subsequent Psiphon server API
  78. // requests (e.g., periodic connected and status requests).
  79. func NewServerContext(
  80. tunnel *Tunnel, sessionId string, ignoreStatsRegexps bool) (*ServerContext, error) {
  81. // For legacy servers, set up psiphonHttpsClient for
  82. // accessing the Psiphon API via the web service.
  83. var psiphonHttpsClient *http.Client
  84. if !tunnel.serverEntry.SupportsSSHAPIRequests() ||
  85. tunnel.config.TargetApiProtocol == protocol.PSIPHON_WEB_API_PROTOCOL {
  86. var err error
  87. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  88. if err != nil {
  89. return nil, common.ContextError(err)
  90. }
  91. }
  92. serverContext := &ServerContext{
  93. sessionId: sessionId,
  94. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  95. tunnel: tunnel,
  96. psiphonHttpsClient: psiphonHttpsClient,
  97. }
  98. err := serverContext.doHandshakeRequest(ignoreStatsRegexps)
  99. if err != nil {
  100. return nil, common.ContextError(err)
  101. }
  102. return serverContext, nil
  103. }
  104. // doHandshakeRequest performs the "handshake" API request. The handshake
  105. // returns upgrade info, newly discovered server entries -- which are
  106. // stored -- and sponsor info (home pages, stat regexes).
  107. func (serverContext *ServerContext) doHandshakeRequest(
  108. ignoreStatsRegexps bool) error {
  109. params := serverContext.getBaseParams()
  110. // *TODO*: this is obsolete?
  111. /*
  112. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  113. if err != nil {
  114. return common.ContextError(err)
  115. }
  116. // Submit a list of known servers -- this will be used for
  117. // discovery statistics.
  118. for _, ipAddress := range serverEntryIpAddresses {
  119. params = append(params, requestParam{"known_server", ipAddress})
  120. }
  121. */
  122. var response []byte
  123. if serverContext.psiphonHttpsClient == nil {
  124. request, err := makeSSHAPIRequestPayload(params)
  125. if err != nil {
  126. return common.ContextError(err)
  127. }
  128. response, err = serverContext.tunnel.SendAPIRequest(
  129. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  130. if err != nil {
  131. return common.ContextError(err)
  132. }
  133. } else {
  134. // Legacy web service API request
  135. responseBody, err := serverContext.doGetRequest(
  136. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  137. if err != nil {
  138. return common.ContextError(err)
  139. }
  140. // Skip legacy format lines and just parse the JSON config line
  141. configLinePrefix := []byte("Config: ")
  142. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  143. if bytes.HasPrefix(line, configLinePrefix) {
  144. response = line[len(configLinePrefix):]
  145. break
  146. }
  147. }
  148. if len(response) == 0 {
  149. return common.ContextError(errors.New("no config line found"))
  150. }
  151. }
  152. // Legacy fields:
  153. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  154. // - 'ssh_session_id' is ignored; client session ID is used instead
  155. var handshakeResponse protocol.HandshakeResponse
  156. err := json.Unmarshal(response, &handshakeResponse)
  157. if err != nil {
  158. return common.ContextError(err)
  159. }
  160. serverContext.clientRegion = handshakeResponse.ClientRegion
  161. NoticeClientRegion(serverContext.clientRegion)
  162. var decodedServerEntries []*protocol.ServerEntry
  163. // Store discovered server entries
  164. // We use the server's time, as it's available here, for the server entry
  165. // timestamp since this is more reliable than the client time.
  166. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  167. serverEntry, err := protocol.DecodeServerEntry(
  168. encodedServerEntry,
  169. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  170. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  171. if err != nil {
  172. return common.ContextError(err)
  173. }
  174. err = protocol.ValidateServerEntry(serverEntry)
  175. if err != nil {
  176. // Skip this entry and continue with the next one
  177. NoticeAlert("invalid server entry: %s", err)
  178. continue
  179. }
  180. decodedServerEntries = append(decodedServerEntries, serverEntry)
  181. }
  182. // The reason we are storing the entire array of server entries at once rather
  183. // than one at a time is that some desirable side-effects get triggered by
  184. // StoreServerEntries that don't get triggered by StoreServerEntry.
  185. err = StoreServerEntries(decodedServerEntries, true)
  186. if err != nil {
  187. return common.ContextError(err)
  188. }
  189. NoticeHomepages(handshakeResponse.Homepages)
  190. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  191. if handshakeResponse.UpgradeClientVersion != "" {
  192. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  193. } else {
  194. NoticeClientIsLatestVersion("")
  195. }
  196. if !ignoreStatsRegexps {
  197. var regexpsNotices []string
  198. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  199. handshakeResponse.PageViewRegexes,
  200. handshakeResponse.HttpsRequestRegexes)
  201. for _, notice := range regexpsNotices {
  202. NoticeAlert(notice)
  203. }
  204. }
  205. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  206. NoticeServerTimestamp(serverContext.serverHandshakeTimestamp)
  207. return nil
  208. }
  209. // DoConnectedRequest performs the "connected" API request. This request is
  210. // used for statistics. The server returns a last_connected token for
  211. // the client to store and send next time it connects. This token is
  212. // a timestamp (using the server clock, and should be rounded to the
  213. // nearest hour) which is used to determine when a connection represents
  214. // a unique user for a time period.
  215. func (serverContext *ServerContext) DoConnectedRequest() error {
  216. params := serverContext.getBaseParams()
  217. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  218. if err != nil {
  219. return common.ContextError(err)
  220. }
  221. if lastConnected == "" {
  222. lastConnected = "None"
  223. }
  224. params["last_connected"] = lastConnected
  225. var response []byte
  226. if serverContext.psiphonHttpsClient == nil {
  227. request, err := makeSSHAPIRequestPayload(params)
  228. if err != nil {
  229. return common.ContextError(err)
  230. }
  231. response, err = serverContext.tunnel.SendAPIRequest(
  232. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  233. if err != nil {
  234. return common.ContextError(err)
  235. }
  236. } else {
  237. // Legacy web service API request
  238. response, err = serverContext.doGetRequest(
  239. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  240. if err != nil {
  241. return common.ContextError(err)
  242. }
  243. }
  244. var connectedResponse protocol.ConnectedResponse
  245. err = json.Unmarshal(response, &connectedResponse)
  246. if err != nil {
  247. return common.ContextError(err)
  248. }
  249. err = SetKeyValue(
  250. DATA_STORE_LAST_CONNECTED_KEY, connectedResponse.ConnectedTimestamp)
  251. if err != nil {
  252. return common.ContextError(err)
  253. }
  254. return nil
  255. }
  256. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  257. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  258. return serverContext.statsRegexps
  259. }
  260. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  261. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  262. params := serverContext.getStatusParams(true)
  263. // Note: ensure putBackStatusRequestPayload is called, to replace
  264. // payload for future attempt, in all failure cases.
  265. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  266. tunnel.serverEntry.IpAddress)
  267. if err != nil {
  268. return common.ContextError(err)
  269. }
  270. if serverContext.psiphonHttpsClient == nil {
  271. rawMessage := json.RawMessage(statusPayload)
  272. params["statusData"] = &rawMessage
  273. var request []byte
  274. request, err = makeSSHAPIRequestPayload(params)
  275. if err == nil {
  276. _, err = serverContext.tunnel.SendAPIRequest(
  277. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  278. }
  279. } else {
  280. // Legacy web service API request
  281. _, err = serverContext.doPostRequest(
  282. makeRequestUrl(serverContext.tunnel, "", "status", params),
  283. "application/json",
  284. bytes.NewReader(statusPayload))
  285. }
  286. if err != nil {
  287. // Resend the transfer stats and tunnel stats later
  288. // Note: potential duplicate reports if the server received and processed
  289. // the request but the client failed to receive the response.
  290. putBackStatusRequestPayload(statusPayloadInfo)
  291. return common.ContextError(err)
  292. }
  293. confirmStatusRequestPayload(statusPayloadInfo)
  294. return nil
  295. }
  296. func (serverContext *ServerContext) getStatusParams(isTunneled bool) requestJSONObject {
  297. params := serverContext.getBaseParams()
  298. // Add a random amount of padding to help prevent stats updates from being
  299. // a predictable size (which often happens when the connection is quiet).
  300. // TODO: base64 encoding of padding means the padding size is not exactly
  301. // [0, PADDING_MAX_BYTES].
  302. randomPadding, err := common.MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  303. if err != nil {
  304. NoticeAlert("MakeSecureRandomPadding failed: %s", common.ContextError(err))
  305. // Proceed without random padding
  306. randomPadding = make([]byte, 0)
  307. }
  308. params["padding"] = base64.StdEncoding.EncodeToString(randomPadding)
  309. // Legacy clients set "connected" to "0" when disconnecting, and this value
  310. // is used to calculate session duration estimates. This is now superseded
  311. // by explicit tunnel stats duration reporting.
  312. // The legacy method of reconstructing session durations is not compatible
  313. // with this client's connected request retries and asynchronous final
  314. // status request attempts. So we simply set this "connected" flag to reflect
  315. // whether the request is sent tunneled or not.
  316. connected := "1"
  317. if !isTunneled {
  318. connected = "0"
  319. }
  320. params["connected"] = connected
  321. return params
  322. }
  323. // statusRequestPayloadInfo is a temporary structure for data used to
  324. // either "clear" or "put back" status request payload data depending
  325. // on whether or not the request succeeded.
  326. type statusRequestPayloadInfo struct {
  327. serverId string
  328. transferStats *transferstats.AccumulatedStats
  329. persistentStats map[string][][]byte
  330. }
  331. func makeStatusRequestPayload(
  332. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  333. transferStats := transferstats.TakeOutStatsForServer(serverId)
  334. persistentStats, err := TakeOutUnreportedPersistentStats(
  335. PSIPHON_API_PERSISTENT_STATS_MAX_COUNT)
  336. if err != nil {
  337. NoticeAlert(
  338. "TakeOutUnreportedPersistentStats failed: %s", common.ContextError(err))
  339. persistentStats = nil
  340. // Proceed with transferStats only
  341. }
  342. payloadInfo := &statusRequestPayloadInfo{
  343. serverId, transferStats, persistentStats}
  344. payload := make(map[string]interface{})
  345. hostBytes, bytesTransferred := transferStats.GetStatsForStatusRequest()
  346. payload["host_bytes"] = hostBytes
  347. payload["bytes_transferred"] = bytesTransferred
  348. // We're not recording these fields, but the server requires them.
  349. payload["page_views"] = make([]string, 0)
  350. payload["https_requests"] = make([]string, 0)
  351. persistentStatPayloadNames := make(map[string]string)
  352. persistentStatPayloadNames[PERSISTENT_STAT_TYPE_TUNNEL] = "tunnel_stats"
  353. persistentStatPayloadNames[PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST] = "remote_server_list_stats"
  354. for statType, stats := range persistentStats {
  355. // Persistent stats records are already in JSON format
  356. jsonStats := make([]json.RawMessage, len(stats))
  357. for i, stat := range stats {
  358. jsonStats[i] = json.RawMessage(stat)
  359. }
  360. payload[persistentStatPayloadNames[statType]] = jsonStats
  361. }
  362. jsonPayload, err := json.Marshal(payload)
  363. if err != nil {
  364. // Send the transfer stats and tunnel stats later
  365. putBackStatusRequestPayload(payloadInfo)
  366. return nil, nil, common.ContextError(err)
  367. }
  368. return jsonPayload, payloadInfo, nil
  369. }
  370. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  371. transferstats.PutBackStatsForServer(
  372. payloadInfo.serverId, payloadInfo.transferStats)
  373. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  374. if err != nil {
  375. // These persistent stats records won't be resent until after a
  376. // datastore re-initialization.
  377. NoticeAlert(
  378. "PutBackUnreportedPersistentStats failed: %s", common.ContextError(err))
  379. }
  380. }
  381. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  382. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  383. if err != nil {
  384. // These persistent stats records may be resent.
  385. NoticeAlert(
  386. "ClearReportedPersistentStats failed: %s", common.ContextError(err))
  387. }
  388. }
  389. // TryUntunneledStatusRequest makes direct connections to the specified
  390. // server (if supported) in an attempt to send useful bytes transferred
  391. // and tunnel duration stats after a tunnel has alreay failed.
  392. // The tunnel is assumed to be closed, but its config, protocol, and
  393. // context values must still be valid.
  394. // TryUntunneledStatusRequest emits notices detailing failed attempts.
  395. func (serverContext *ServerContext) TryUntunneledStatusRequest(isShutdown bool) error {
  396. for _, port := range serverContext.tunnel.serverEntry.GetUntunneledWebRequestPorts() {
  397. err := serverContext.doUntunneledStatusRequest(port, isShutdown)
  398. if err == nil {
  399. return nil
  400. }
  401. NoticeAlert("doUntunneledStatusRequest failed for %s:%s: %s",
  402. serverContext.tunnel.serverEntry.IpAddress, port, err)
  403. }
  404. return errors.New("all attempts failed")
  405. }
  406. // doUntunneledStatusRequest attempts an untunneled status request.
  407. func (serverContext *ServerContext) doUntunneledStatusRequest(
  408. port string, isShutdown bool) error {
  409. tunnel := serverContext.tunnel
  410. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  411. if err != nil {
  412. return common.ContextError(err)
  413. }
  414. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  415. dialConfig := tunnel.untunneledDialConfig
  416. if isShutdown {
  417. timeout = PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT
  418. // Use a copy of DialConfig without pendingConns. This ensures
  419. // this request isn't interrupted/canceled. This measure should
  420. // be used only with the very short PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT.
  421. dialConfig = new(DialConfig)
  422. *dialConfig = *tunnel.untunneledDialConfig
  423. }
  424. url := makeRequestUrl(tunnel, port, "status", serverContext.getStatusParams(false))
  425. httpClient, url, err := MakeUntunneledHttpsClient(
  426. dialConfig,
  427. certificate,
  428. url,
  429. false,
  430. timeout)
  431. if err != nil {
  432. return common.ContextError(err)
  433. }
  434. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  435. if err != nil {
  436. return common.ContextError(err)
  437. }
  438. bodyType := "application/json"
  439. body := bytes.NewReader(statusPayload)
  440. response, err := httpClient.Post(url, bodyType, body)
  441. if err == nil && response.StatusCode != http.StatusOK {
  442. response.Body.Close()
  443. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  444. }
  445. if err != nil {
  446. // Resend the transfer stats and tunnel stats later
  447. // Note: potential duplicate reports if the server received and processed
  448. // the request but the client failed to receive the response.
  449. putBackStatusRequestPayload(statusPayloadInfo)
  450. // Trim this error since it may include long URLs
  451. return common.ContextError(TrimError(err))
  452. }
  453. confirmStatusRequestPayload(statusPayloadInfo)
  454. response.Body.Close()
  455. return nil
  456. }
  457. // RecordTunnelStat records a tunnel duration and bytes
  458. // sent and received for subsequent reporting and quality
  459. // analysis.
  460. //
  461. // Tunnel durations are precisely measured client-side
  462. // and reported in status requests. As the duration is
  463. // not determined until the tunnel is closed, tunnel
  464. // stats records are stored in the persistent datastore
  465. // and reported via subsequent status requests sent to any
  466. // Psiphon server.
  467. //
  468. // Since the status request that reports a tunnel stats
  469. // record is not necessarily handled by the same server, the
  470. // tunnel stats records include the original server ID.
  471. //
  472. // Other fields that may change between tunnel stats recording
  473. // and reporting include client geo data, propagation channel,
  474. // sponsor ID, client version. These are not stored in the
  475. // datastore (client region, in particular, since that would
  476. // create an on-disk record of user location).
  477. // TODO: the server could encrypt, with a nonce and key unknown to
  478. // the client, a blob containing this data; return it in the
  479. // handshake response; and the client could store and later report
  480. // this blob with its tunnel stats records.
  481. //
  482. // Multiple "status" requests may be in flight at once (due
  483. // to multi-tunnel, asynchronous final status retry, and
  484. // aggressive status requests for pre-registered tunnels),
  485. // To avoid duplicate reporting, tunnel stats records are
  486. // "taken-out" by a status request and then "put back" in
  487. // case the request fails.
  488. //
  489. // Note: since tunnel stats records have a globally unique
  490. // identifier (sessionId + tunnelNumber), we could tolerate
  491. // duplicate reporting and filter our duplicates on the
  492. // server-side. Permitting duplicate reporting could increase
  493. // the velocity of reporting (for example, both the asynchronous
  494. // untunneled final status requests and the post-connected
  495. // immediate status requests could try to report the same tunnel
  496. // stats).
  497. // Duplicate reporting may also occur when a server receives and
  498. // processes a status request but the client fails to receive
  499. // the response.
  500. func RecordTunnelStat(
  501. sessionId string,
  502. tunnelNumber int64,
  503. tunnelServerIpAddress string,
  504. establishmentDuration string,
  505. serverHandshakeTimestamp string,
  506. tunnelDuration string,
  507. totalBytesSent int64,
  508. totalBytesReceived int64) error {
  509. tunnelStat := struct {
  510. SessionId string `json:"session_id"`
  511. TunnelNumber int64 `json:"tunnel_number"`
  512. TunnelServerIpAddress string `json:"tunnel_server_ip_address"`
  513. EstablishmentDuration string `json:"establishment_duration"`
  514. ServerHandshakeTimestamp string `json:"server_handshake_timestamp"`
  515. Duration string `json:"duration"`
  516. TotalBytesSent int64 `json:"total_bytes_sent"`
  517. TotalBytesReceived int64 `json:"total_bytes_received"`
  518. }{
  519. sessionId,
  520. tunnelNumber,
  521. tunnelServerIpAddress,
  522. establishmentDuration,
  523. serverHandshakeTimestamp,
  524. tunnelDuration,
  525. totalBytesSent,
  526. totalBytesReceived,
  527. }
  528. tunnelStatJson, err := json.Marshal(tunnelStat)
  529. if err != nil {
  530. return common.ContextError(err)
  531. }
  532. return StorePersistentStat(
  533. PERSISTENT_STAT_TYPE_TUNNEL, tunnelStatJson)
  534. }
  535. // RecordRemoteServerListStat records a completed common or OSL
  536. // remote server list resource download. These stats use the same
  537. // persist-until-reported mechanism described in RecordTunnelStats.
  538. func RecordRemoteServerListStat(
  539. url, etag string) error {
  540. remoteServerListStat := struct {
  541. ClientDownloadTimestamp string `json:"client_download_timestamp"`
  542. URL string `json:"url"`
  543. ETag string `json:"etag"`
  544. }{
  545. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  546. url,
  547. etag,
  548. }
  549. remoteServerListStatJson, err := json.Marshal(remoteServerListStat)
  550. if err != nil {
  551. return common.ContextError(err)
  552. }
  553. return StorePersistentStat(
  554. PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST, remoteServerListStatJson)
  555. }
  556. // DoClientVerificationRequest performs the "client_verification" API
  557. // request. This request is used to verify that the client is a valid
  558. // Psiphon client, which will determine how the server treats the client
  559. // traffic. The proof-of-validity is platform-specific and the payload
  560. // is opaque to this function but assumed to be JSON.
  561. func (serverContext *ServerContext) DoClientVerificationRequest(
  562. verificationPayload string, serverIP string) error {
  563. params := serverContext.getBaseParams()
  564. var response []byte
  565. var err error
  566. if serverContext.psiphonHttpsClient == nil {
  567. // Empty verification payload signals desire to
  568. // query the server for current TTL. This is
  569. // indicated to the server by the absence of the
  570. // verificationData field.
  571. if verificationPayload != "" {
  572. rawMessage := json.RawMessage(verificationPayload)
  573. params["verificationData"] = &rawMessage
  574. }
  575. request, err := makeSSHAPIRequestPayload(params)
  576. if err != nil {
  577. return common.ContextError(err)
  578. }
  579. response, err = serverContext.tunnel.SendAPIRequest(
  580. protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME, request)
  581. if err != nil {
  582. return common.ContextError(err)
  583. }
  584. } else {
  585. // Legacy web service API request
  586. response, err = serverContext.doPostRequest(
  587. makeRequestUrl(serverContext.tunnel, "", "client_verification", params),
  588. "application/json",
  589. bytes.NewReader([]byte(verificationPayload)))
  590. if err != nil {
  591. return common.ContextError(err)
  592. }
  593. }
  594. // Server may request a new verification to be performed,
  595. // for example, if the payload timestamp is too old, etc.
  596. var clientVerificationResponse struct {
  597. ClientVerificationServerNonce string `json:"client_verification_server_nonce"`
  598. ClientVerificationTTLSeconds int `json:"client_verification_ttl_seconds"`
  599. ClientVerificationResetCache bool `json:"client_verification_reset_cache"`
  600. }
  601. // In case of empty response body the json.Unmarshal will fail
  602. // and clientVerificationResponse will be initialized with default values
  603. _ = json.Unmarshal(response, &clientVerificationResponse)
  604. if clientVerificationResponse.ClientVerificationTTLSeconds > 0 {
  605. NoticeClientVerificationRequired(
  606. clientVerificationResponse.ClientVerificationServerNonce,
  607. clientVerificationResponse.ClientVerificationTTLSeconds,
  608. clientVerificationResponse.ClientVerificationResetCache)
  609. } else {
  610. NoticeClientVerificationRequestCompleted(serverIP)
  611. }
  612. return nil
  613. }
  614. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  615. func (serverContext *ServerContext) doGetRequest(
  616. requestUrl string) (responseBody []byte, err error) {
  617. request, err := http.NewRequest("GET", requestUrl, nil)
  618. if err != nil {
  619. return nil, common.ContextError(err)
  620. }
  621. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  622. response, err := serverContext.psiphonHttpsClient.Do(request)
  623. if err == nil && response.StatusCode != http.StatusOK {
  624. response.Body.Close()
  625. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  626. }
  627. if err != nil {
  628. // Trim this error since it may include long URLs
  629. return nil, common.ContextError(TrimError(err))
  630. }
  631. defer response.Body.Close()
  632. body, err := ioutil.ReadAll(response.Body)
  633. if err != nil {
  634. return nil, common.ContextError(err)
  635. }
  636. return body, nil
  637. }
  638. // doPostRequest makes a tunneled HTTPS POST request.
  639. func (serverContext *ServerContext) doPostRequest(
  640. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  641. request, err := http.NewRequest("POST", requestUrl, body)
  642. if err != nil {
  643. return nil, common.ContextError(err)
  644. }
  645. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  646. request.Header.Set("Content-Type", bodyType)
  647. response, err := serverContext.psiphonHttpsClient.Do(request)
  648. if err == nil && response.StatusCode != http.StatusOK {
  649. response.Body.Close()
  650. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  651. }
  652. if err != nil {
  653. // Trim this error since it may include long URLs
  654. return nil, common.ContextError(TrimError(err))
  655. }
  656. defer response.Body.Close()
  657. responseBody, err = ioutil.ReadAll(response.Body)
  658. if err != nil {
  659. return nil, common.ContextError(err)
  660. }
  661. return responseBody, nil
  662. }
  663. type requestJSONObject map[string]interface{}
  664. // getBaseParams returns all the common API parameters that are included
  665. // with each Psiphon API request. These common parameters are used for
  666. // statistics.
  667. func (serverContext *ServerContext) getBaseParams() requestJSONObject {
  668. params := make(requestJSONObject)
  669. tunnel := serverContext.tunnel
  670. params["session_id"] = serverContext.sessionId
  671. params["client_session_id"] = serverContext.sessionId
  672. params["server_secret"] = tunnel.serverEntry.WebServerSecret
  673. params["propagation_channel_id"] = tunnel.config.PropagationChannelId
  674. params["sponsor_id"] = tunnel.config.SponsorId
  675. params["client_version"] = tunnel.config.ClientVersion
  676. // TODO: client_tunnel_core_version?
  677. params["relay_protocol"] = tunnel.protocol
  678. params["client_platform"] = tunnel.config.ClientPlatform
  679. params["client_build_rev"] = common.GetBuildInfo().BuildRev
  680. params["tunnel_whole_device"] = strconv.Itoa(tunnel.config.TunnelWholeDevice)
  681. // The following parameters may be blank and must
  682. // not be sent to the server if blank.
  683. if tunnel.config.DeviceRegion != "" {
  684. params["device_region"] = tunnel.config.DeviceRegion
  685. }
  686. if tunnel.dialStats.SelectedSSHClientVersion {
  687. params["ssh_client_version"] = tunnel.dialStats.SSHClientVersion
  688. }
  689. if tunnel.dialStats.UpstreamProxyType != "" {
  690. params["upstream_proxy_type"] = tunnel.dialStats.UpstreamProxyType
  691. }
  692. if tunnel.dialStats.UpstreamProxyCustomHeaderNames != nil {
  693. params["upstream_proxy_custom_header_names"] = tunnel.dialStats.UpstreamProxyCustomHeaderNames
  694. }
  695. if tunnel.dialStats.MeekDialAddress != "" {
  696. params["meek_dial_address"] = tunnel.dialStats.MeekDialAddress
  697. }
  698. if tunnel.dialStats.MeekResolvedIPAddress != "" {
  699. params["meek_resolved_ip_address"] = tunnel.dialStats.MeekResolvedIPAddress
  700. }
  701. if tunnel.dialStats.MeekSNIServerName != "" {
  702. params["meek_sni_server_name"] = tunnel.dialStats.MeekSNIServerName
  703. }
  704. if tunnel.dialStats.MeekHostHeader != "" {
  705. params["meek_host_header"] = tunnel.dialStats.MeekHostHeader
  706. }
  707. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  708. if tunnel.dialStats.MeekDialAddress != "" {
  709. transformedHostName := "0"
  710. if tunnel.dialStats.MeekTransformedHostName {
  711. transformedHostName = "1"
  712. }
  713. params["meek_transformed_host_name"] = transformedHostName
  714. }
  715. if tunnel.dialStats.SelectedUserAgent {
  716. params["user_agent"] = tunnel.dialStats.UserAgent
  717. }
  718. if tunnel.dialStats.SelectedTLSProfile {
  719. params["tls_profile"] = tunnel.dialStats.TLSProfile
  720. }
  721. if tunnel.serverEntry.Region != "" {
  722. params["server_entry_region"] = tunnel.serverEntry.Region
  723. }
  724. if tunnel.serverEntry.LocalSource != "" {
  725. params["server_entry_source"] = tunnel.serverEntry.LocalSource
  726. }
  727. // As with last_connected, this timestamp stat, which may be
  728. // a precise handshake request server timestamp, is truncated
  729. // to hour granularity to avoid introducing a reconstructable
  730. // cross-session user trace into server logs.
  731. localServerEntryTimestamp := common.TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  732. if localServerEntryTimestamp != "" {
  733. params["server_entry_timestamp"] = localServerEntryTimestamp
  734. }
  735. return params
  736. }
  737. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  738. func makeSSHAPIRequestPayload(params requestJSONObject) ([]byte, error) {
  739. jsonPayload, err := json.Marshal(params)
  740. if err != nil {
  741. return nil, common.ContextError(err)
  742. }
  743. return jsonPayload, nil
  744. }
  745. // makeRequestUrl makes a URL for a web service API request.
  746. func makeRequestUrl(tunnel *Tunnel, port, path string, params requestJSONObject) string {
  747. var requestUrl bytes.Buffer
  748. if port == "" {
  749. port = tunnel.serverEntry.WebServerPort
  750. }
  751. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  752. // e.g., don't do this: requestUrl.WriteString("https://")
  753. requestUrl.WriteString("http://")
  754. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  755. requestUrl.WriteString(":")
  756. requestUrl.WriteString(port)
  757. requestUrl.WriteString("/")
  758. requestUrl.WriteString(path)
  759. if len(params) > 0 {
  760. queryParams := url.Values{}
  761. for name, value := range params {
  762. strValue := ""
  763. switch v := value.(type) {
  764. case string:
  765. strValue = v
  766. case []string:
  767. // String array param encoded as JSON
  768. jsonValue, err := json.Marshal(v)
  769. if err != nil {
  770. break
  771. }
  772. strValue = string(jsonValue)
  773. }
  774. queryParams.Set(name, strValue)
  775. }
  776. requestUrl.WriteString("?")
  777. requestUrl.WriteString(queryParams.Encode())
  778. }
  779. return requestUrl.String()
  780. }
  781. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  782. // requests and which validates the web server using the Psiphon server entry web server
  783. // certificate. This is not a general purpose HTTPS client.
  784. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  785. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  786. // handshake inside the explicit TLS session.
  787. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  788. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  789. if err != nil {
  790. return nil, common.ContextError(err)
  791. }
  792. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  793. // TODO: check tunnel.isClosed, and apply TUNNEL_PORT_FORWARD_DIAL_TIMEOUT as in Tunnel.Dial?
  794. return tunnel.sshClient.Dial("tcp", addr)
  795. }
  796. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  797. dialer := NewCustomTLSDialer(
  798. &CustomTLSConfig{
  799. Dial: tunneledDialer,
  800. Timeout: timeout,
  801. VerifyLegacyCertificate: certificate,
  802. })
  803. transport := &http.Transport{
  804. Dial: dialer,
  805. }
  806. return &http.Client{
  807. Transport: transport,
  808. Timeout: timeout,
  809. }, nil
  810. }
  811. func HandleServerRequest(
  812. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  813. switch name {
  814. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  815. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  816. }
  817. return common.ContextError(fmt.Errorf("invalid request name: %s", name))
  818. }
  819. func HandleOSLRequest(
  820. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  821. var oslRequest protocol.OSLRequest
  822. err := json.Unmarshal(payload, &oslRequest)
  823. if err != nil {
  824. return common.ContextError(err)
  825. }
  826. if oslRequest.ClearLocalSLOKs {
  827. DeleteSLOKs()
  828. }
  829. seededNewSLOK := false
  830. for _, slok := range oslRequest.SeedPayload.SLOKs {
  831. duplicate, err := SetSLOK(slok.ID, slok.Key)
  832. if err != nil {
  833. // TODO: return error to trigger retry?
  834. NoticeAlert("SetSLOK failed: %s", common.ContextError(err))
  835. } else if !duplicate {
  836. seededNewSLOK = true
  837. }
  838. if tunnel.config.EmitSLOKs {
  839. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  840. }
  841. }
  842. if seededNewSLOK {
  843. tunnelOwner.SignalSeededNewSLOK()
  844. }
  845. return nil
  846. }