serverApi.go 33 KB

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