serverApi.go 32 KB

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