serverApi.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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.SelectedSSHClientVersion {
  686. params["ssh_client_version"] = tunnel.dialStats.SSHClientVersion
  687. }
  688. if tunnel.dialStats.UpstreamProxyType != "" {
  689. params["upstream_proxy_type"] = tunnel.dialStats.UpstreamProxyType
  690. }
  691. if tunnel.dialStats.UpstreamProxyCustomHeaderNames != nil {
  692. params["upstream_proxy_custom_header_names"] = tunnel.dialStats.UpstreamProxyCustomHeaderNames
  693. }
  694. if tunnel.dialStats.MeekDialAddress != "" {
  695. params["meek_dial_address"] = tunnel.dialStats.MeekDialAddress
  696. }
  697. if tunnel.dialStats.MeekResolvedIPAddress != "" {
  698. params["meek_resolved_ip_address"] = tunnel.dialStats.MeekResolvedIPAddress
  699. }
  700. if tunnel.dialStats.MeekSNIServerName != "" {
  701. params["meek_sni_server_name"] = tunnel.dialStats.MeekSNIServerName
  702. }
  703. if tunnel.dialStats.MeekHostHeader != "" {
  704. params["meek_host_header"] = tunnel.dialStats.MeekHostHeader
  705. }
  706. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  707. if tunnel.dialStats.MeekDialAddress != "" {
  708. transformedHostName := "0"
  709. if tunnel.dialStats.MeekTransformedHostName {
  710. transformedHostName = "1"
  711. }
  712. params["meek_transformed_host_name"] = transformedHostName
  713. }
  714. if tunnel.dialStats.SelectedUserAgent {
  715. params["user_agent"] = tunnel.dialStats.UserAgent
  716. }
  717. if tunnel.dialStats.SelectedTLSProfile {
  718. params["tls_profile"] = tunnel.dialStats.TLSProfile
  719. }
  720. if tunnel.serverEntry.Region != "" {
  721. params["server_entry_region"] = tunnel.serverEntry.Region
  722. }
  723. if tunnel.serverEntry.LocalSource != "" {
  724. params["server_entry_source"] = tunnel.serverEntry.LocalSource
  725. }
  726. // As with last_connected, this timestamp stat, which may be
  727. // a precise handshake request server timestamp, is truncated
  728. // to hour granularity to avoid introducing a reconstructable
  729. // cross-session user trace into server logs.
  730. localServerEntryTimestamp := common.TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  731. if localServerEntryTimestamp != "" {
  732. params["server_entry_timestamp"] = localServerEntryTimestamp
  733. }
  734. return params
  735. }
  736. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  737. func makeSSHAPIRequestPayload(params requestJSONObject) ([]byte, error) {
  738. jsonPayload, err := json.Marshal(params)
  739. if err != nil {
  740. return nil, common.ContextError(err)
  741. }
  742. return jsonPayload, nil
  743. }
  744. // makeRequestUrl makes a URL for a web service API request.
  745. func makeRequestUrl(tunnel *Tunnel, port, path string, params requestJSONObject) string {
  746. var requestUrl bytes.Buffer
  747. if port == "" {
  748. port = tunnel.serverEntry.WebServerPort
  749. }
  750. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  751. // e.g., don't do this: requestUrl.WriteString("https://")
  752. requestUrl.WriteString("http://")
  753. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  754. requestUrl.WriteString(":")
  755. requestUrl.WriteString(port)
  756. requestUrl.WriteString("/")
  757. requestUrl.WriteString(path)
  758. if len(params) > 0 {
  759. queryParams := url.Values{}
  760. for name, value := range params {
  761. strValue := ""
  762. switch v := value.(type) {
  763. case string:
  764. strValue = v
  765. case []string:
  766. // String array param encoded as JSON
  767. jsonValue, err := json.Marshal(v)
  768. if err != nil {
  769. break
  770. }
  771. strValue = string(jsonValue)
  772. }
  773. queryParams.Set(name, strValue)
  774. }
  775. requestUrl.WriteString("?")
  776. requestUrl.WriteString(queryParams.Encode())
  777. }
  778. return requestUrl.String()
  779. }
  780. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  781. // requests and which validates the web server using the Psiphon server entry web server
  782. // certificate. This is not a general purpose HTTPS client.
  783. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  784. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  785. // handshake inside the explicit TLS session.
  786. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  787. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  788. if err != nil {
  789. return nil, common.ContextError(err)
  790. }
  791. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  792. // TODO: check tunnel.isClosed, and apply TUNNEL_PORT_FORWARD_DIAL_TIMEOUT as in Tunnel.Dial?
  793. return tunnel.sshClient.Dial("tcp", addr)
  794. }
  795. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  796. dialer := NewCustomTLSDialer(
  797. &CustomTLSConfig{
  798. Dial: tunneledDialer,
  799. Timeout: timeout,
  800. VerifyLegacyCertificate: certificate,
  801. })
  802. transport := &http.Transport{
  803. Dial: dialer,
  804. }
  805. return &http.Client{
  806. Transport: transport,
  807. Timeout: timeout,
  808. }, nil
  809. }
  810. func HandleServerRequest(
  811. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  812. switch name {
  813. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  814. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  815. }
  816. return common.ContextError(fmt.Errorf("invalid request name: %s", name))
  817. }
  818. func HandleOSLRequest(
  819. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  820. var oslRequest protocol.OSLRequest
  821. err := json.Unmarshal(payload, &oslRequest)
  822. if err != nil {
  823. return common.ContextError(err)
  824. }
  825. if oslRequest.ClearLocalSLOKs {
  826. DeleteSLOKs()
  827. }
  828. seededNewSLOK := false
  829. for _, slok := range oslRequest.SeedPayload.SLOKs {
  830. duplicate, err := SetSLOK(slok.ID, slok.Key)
  831. if err != nil {
  832. // TODO: return error to trigger retry?
  833. NoticeAlert("SetSLOK failed: %s", common.ContextError(err))
  834. } else if !duplicate {
  835. seededNewSLOK = true
  836. }
  837. if tunnel.config.EmitSLOKs {
  838. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  839. }
  840. }
  841. if seededNewSLOK {
  842. tunnelOwner.SignalSeededNewSLOK()
  843. }
  844. return nil
  845. }