serverApi.go 33 KB

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