serverApi.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. "strconv"
  32. "sync/atomic"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  35. )
  36. // ServerContext is a utility struct which holds all of the data associated
  37. // with a Psiphon server connection. In addition to the established tunnel, this
  38. // includes data associated with Psiphon API requests and a persistent http
  39. // client configured to make tunneled Psiphon API requests.
  40. type ServerContext struct {
  41. sessionId string
  42. tunnelNumber int64
  43. baseRequestUrl string
  44. psiphonHttpsClient *http.Client
  45. statsRegexps *transferstats.Regexps
  46. clientRegion string
  47. clientUpgradeVersion string
  48. serverHandshakeTimestamp string
  49. }
  50. // MeekStats holds extra stats that are only gathered for meek tunnels.
  51. type MeekStats struct {
  52. DialAddress string
  53. ResolvedIPAddress string
  54. SNIServerName string
  55. HostHeader string
  56. TransformedHostName bool
  57. }
  58. // nextTunnelNumber is a monotonically increasing number assigned to each
  59. // successive tunnel connection. The sessionId and tunnelNumber together
  60. // form a globally unique identifier for tunnels, which is used for
  61. // stats. Note that the number is increasing but not necessarily
  62. // consecutive for each active tunnel in session.
  63. var nextTunnelNumber int64
  64. // MakeSessionId creates a new session ID. The same session ID is used across
  65. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  66. // instance.
  67. // In server-side stats, we now consider a "session" to be the lifetime of the
  68. // Controller (e.g., the user's commanded start and stop) and we measure this
  69. // duration as well as the duration of each tunnel within the session.
  70. func MakeSessionId() (sessionId string, err error) {
  71. randomId, err := MakeSecureRandomBytes(PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  72. if err != nil {
  73. return "", ContextError(err)
  74. }
  75. return hex.EncodeToString(randomId), nil
  76. }
  77. // NewServerContext makes the tunnelled handshake request to the Psiphon server
  78. // and returns a ServerContext struct for use with subsequent Psiphon server API
  79. // requests (e.g., periodic connected and status requests).
  80. func NewServerContext(tunnel *Tunnel, sessionId string) (*ServerContext, error) {
  81. psiphonHttpsClient, err := makePsiphonHttpsClient(tunnel)
  82. if err != nil {
  83. return nil, ContextError(err)
  84. }
  85. serverContext := &ServerContext{
  86. sessionId: sessionId,
  87. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  88. baseRequestUrl: makeBaseRequestUrl(tunnel, "", sessionId),
  89. psiphonHttpsClient: psiphonHttpsClient,
  90. }
  91. err = serverContext.doHandshakeRequest()
  92. if err != nil {
  93. return nil, ContextError(err)
  94. }
  95. return serverContext, nil
  96. }
  97. // doHandshakeRequest performs the handshake API request. The handshake
  98. // returns upgrade info, newly discovered server entries -- which are
  99. // stored -- and sponsor info (home pages, stat regexes).
  100. func (serverContext *ServerContext) doHandshakeRequest() error {
  101. extraParams := make([]*ExtraParam, 0)
  102. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  103. if err != nil {
  104. return ContextError(err)
  105. }
  106. // Submit a list of known servers -- this will be used for
  107. // discovery statistics.
  108. for _, ipAddress := range serverEntryIpAddresses {
  109. extraParams = append(extraParams, &ExtraParam{"known_server", ipAddress})
  110. }
  111. url := buildRequestUrl(serverContext.baseRequestUrl, "handshake", extraParams...)
  112. responseBody, err := serverContext.doGetRequest(url)
  113. if err != nil {
  114. return ContextError(err)
  115. }
  116. // Skip legacy format lines and just parse the JSON config line
  117. configLinePrefix := []byte("Config: ")
  118. var configLine []byte
  119. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  120. if bytes.HasPrefix(line, configLinePrefix) {
  121. configLine = line[len(configLinePrefix):]
  122. break
  123. }
  124. }
  125. if len(configLine) == 0 {
  126. return ContextError(errors.New("no config line found"))
  127. }
  128. // Note:
  129. // - 'preemptive_reconnect_lifetime_milliseconds' is currently unused
  130. // - 'ssh_session_id' is ignored; client session ID is used instead
  131. var handshakeConfig struct {
  132. Homepages []string `json:"homepages"`
  133. UpgradeClientVersion string `json:"upgrade_client_version"`
  134. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  135. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  136. EncodedServerList []string `json:"encoded_server_list"`
  137. ClientRegion string `json:"client_region"`
  138. ServerTimestamp string `json:"server_timestamp"`
  139. ClientVerificationRequired bool `json:"client_verification_required"`
  140. }
  141. err = json.Unmarshal(configLine, &handshakeConfig)
  142. if err != nil {
  143. return ContextError(err)
  144. }
  145. serverContext.clientRegion = handshakeConfig.ClientRegion
  146. NoticeClientRegion(serverContext.clientRegion)
  147. var decodedServerEntries []*ServerEntry
  148. // Store discovered server entries
  149. // We use the server's time, as it's available here, for the server entry
  150. // timestamp since this is more reliable than the client time.
  151. for _, encodedServerEntry := range handshakeConfig.EncodedServerList {
  152. serverEntry, err := DecodeServerEntry(
  153. encodedServerEntry,
  154. TruncateTimestampToHour(handshakeConfig.ServerTimestamp),
  155. SERVER_ENTRY_SOURCE_DISCOVERY)
  156. if err != nil {
  157. return ContextError(err)
  158. }
  159. err = ValidateServerEntry(serverEntry)
  160. if err != nil {
  161. // Skip this entry and continue with the next one
  162. continue
  163. }
  164. decodedServerEntries = append(decodedServerEntries, serverEntry)
  165. }
  166. // The reason we are storing the entire array of server entries at once rather
  167. // than one at a time is that some desirable side-effects get triggered by
  168. // StoreServerEntries that don't get triggered by StoreServerEntry.
  169. err = StoreServerEntries(decodedServerEntries, true)
  170. if err != nil {
  171. return ContextError(err)
  172. }
  173. // TODO: formally communicate the sponsor and upgrade info to an
  174. // outer client via some control interface.
  175. for _, homepage := range handshakeConfig.Homepages {
  176. NoticeHomepage(homepage)
  177. }
  178. serverContext.clientUpgradeVersion = handshakeConfig.UpgradeClientVersion
  179. if handshakeConfig.UpgradeClientVersion != "" {
  180. NoticeClientUpgradeAvailable(handshakeConfig.UpgradeClientVersion)
  181. } else {
  182. NoticeClientIsLatestVersion("")
  183. }
  184. var regexpsNotices []string
  185. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  186. handshakeConfig.PageViewRegexes,
  187. handshakeConfig.HttpsRequestRegexes)
  188. for _, notice := range regexpsNotices {
  189. NoticeAlert(notice)
  190. }
  191. serverContext.serverHandshakeTimestamp = handshakeConfig.ServerTimestamp
  192. if handshakeConfig.ClientVerificationRequired {
  193. NoticeClientVerificationRequired()
  194. }
  195. return nil
  196. }
  197. // DoConnectedRequest performs the connected API request. This request is
  198. // used for statistics. The server returns a last_connected token for
  199. // the client to store and send next time it connects. This token is
  200. // a timestamp (using the server clock, and should be rounded to the
  201. // nearest hour) which is used to determine when a connection represents
  202. // a unique user for a time period.
  203. func (serverContext *ServerContext) DoConnectedRequest() error {
  204. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  205. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  206. if err != nil {
  207. return ContextError(err)
  208. }
  209. if lastConnected == "" {
  210. lastConnected = "None"
  211. }
  212. url := buildRequestUrl(
  213. serverContext.baseRequestUrl,
  214. "connected",
  215. &ExtraParam{"session_id", serverContext.sessionId},
  216. &ExtraParam{"last_connected", lastConnected})
  217. responseBody, err := serverContext.doGetRequest(url)
  218. if err != nil {
  219. return ContextError(err)
  220. }
  221. var response struct {
  222. ConnectedTimestamp string `json:"connected_timestamp"`
  223. }
  224. err = json.Unmarshal(responseBody, &response)
  225. if err != nil {
  226. return ContextError(err)
  227. }
  228. err = SetKeyValue(DATA_STORE_LAST_CONNECTED_KEY, response.ConnectedTimestamp)
  229. if err != nil {
  230. return ContextError(err)
  231. }
  232. return nil
  233. }
  234. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  235. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  236. return serverContext.statsRegexps
  237. }
  238. // DoStatusRequest makes a /status request to the server, sending session stats.
  239. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  240. url := makeStatusRequestUrl(serverContext.sessionId, serverContext.baseRequestUrl, true)
  241. payload, payloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  242. if err != nil {
  243. return ContextError(err)
  244. }
  245. err = serverContext.doPostRequest(url, "application/json", bytes.NewReader(payload))
  246. if err != nil {
  247. // Resend the transfer stats and tunnel stats later
  248. // Note: potential duplicate reports if the server received and processed
  249. // the request but the client failed to receive the response.
  250. putBackStatusRequestPayload(payloadInfo)
  251. return ContextError(err)
  252. }
  253. confirmStatusRequestPayload(payloadInfo)
  254. return nil
  255. }
  256. func makeStatusRequestUrl(sessionId, baseRequestUrl string, isTunneled bool) string {
  257. // Add a random amount of padding to help prevent stats updates from being
  258. // a predictable size (which often happens when the connection is quiet).
  259. padding := MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  260. // Legacy clients set "connected" to "0" when disconnecting, and this value
  261. // is used to calculate session duration estimates. This is now superseded
  262. // by explicit tunnel stats duration reporting.
  263. // The legacy method of reconstructing session durations is not compatible
  264. // with this client's connected request retries and asynchronous final
  265. // status request attempts. So we simply set this "connected" flag to reflect
  266. // whether the request is sent tunneled or not.
  267. connected := "1"
  268. if !isTunneled {
  269. connected = "0"
  270. }
  271. return buildRequestUrl(
  272. baseRequestUrl,
  273. "status",
  274. &ExtraParam{"session_id", sessionId},
  275. &ExtraParam{"connected", connected},
  276. // TODO: base64 encoding of padding means the padding
  277. // size is not exactly [0, PADDING_MAX_BYTES]
  278. &ExtraParam{"padding", base64.StdEncoding.EncodeToString(padding)})
  279. }
  280. // statusRequestPayloadInfo is a temporary structure for data used to
  281. // either "clear" or "put back" status request payload data depending
  282. // on whether or not the request succeeded.
  283. type statusRequestPayloadInfo struct {
  284. serverId string
  285. transferStats *transferstats.AccumulatedStats
  286. tunnelStats [][]byte
  287. }
  288. func makeStatusRequestPayload(
  289. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  290. transferStats := transferstats.TakeOutStatsForServer(serverId)
  291. tunnelStats, err := TakeOutUnreportedTunnelStats(
  292. PSIPHON_API_TUNNEL_STATS_MAX_COUNT)
  293. if err != nil {
  294. NoticeAlert(
  295. "TakeOutUnreportedTunnelStats failed: %s", ContextError(err))
  296. tunnelStats = nil
  297. // Proceed with transferStats only
  298. }
  299. payloadInfo := &statusRequestPayloadInfo{
  300. serverId, transferStats, tunnelStats}
  301. payload := make(map[string]interface{})
  302. hostBytes, bytesTransferred := transferStats.GetStatsForStatusRequest()
  303. payload["host_bytes"] = hostBytes
  304. payload["bytes_transferred"] = bytesTransferred
  305. // We're not recording these fields, but the server requires them.
  306. payload["page_views"] = make([]string, 0)
  307. payload["https_requests"] = make([]string, 0)
  308. // Tunnel stats records are already in JSON format
  309. jsonTunnelStats := make([]json.RawMessage, len(tunnelStats))
  310. for i, tunnelStatsRecord := range tunnelStats {
  311. jsonTunnelStats[i] = json.RawMessage(tunnelStatsRecord)
  312. }
  313. payload["tunnel_stats"] = jsonTunnelStats
  314. jsonPayload, err := json.Marshal(payload)
  315. if err != nil {
  316. // Send the transfer stats and tunnel stats later
  317. putBackStatusRequestPayload(payloadInfo)
  318. return nil, nil, ContextError(err)
  319. }
  320. return jsonPayload, payloadInfo, nil
  321. }
  322. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  323. transferstats.PutBackStatsForServer(
  324. payloadInfo.serverId, payloadInfo.transferStats)
  325. err := PutBackUnreportedTunnelStats(payloadInfo.tunnelStats)
  326. if err != nil {
  327. // These tunnel stats records won't be resent under after a
  328. // datastore re-initialization.
  329. NoticeAlert(
  330. "PutBackUnreportedTunnelStats failed: %s", ContextError(err))
  331. }
  332. }
  333. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  334. err := ClearReportedTunnelStats(payloadInfo.tunnelStats)
  335. if err != nil {
  336. // These tunnel stats records may be resent.
  337. NoticeAlert(
  338. "ClearReportedTunnelStats failed: %s", ContextError(err))
  339. }
  340. }
  341. // TryUntunneledStatusRequest makes direct connections to the specified
  342. // server (if supported) in an attempt to send useful bytes transferred
  343. // and tunnel duration stats after a tunnel has alreay failed.
  344. // The tunnel is assumed to be closed, but its config, protocol, and
  345. // context values must still be valid.
  346. // TryUntunneledStatusRequest emits notices detailing failed attempts.
  347. func TryUntunneledStatusRequest(tunnel *Tunnel, isShutdown bool) error {
  348. for _, port := range tunnel.serverEntry.GetDirectWebRequestPorts() {
  349. err := doUntunneledStatusRequest(tunnel, port, isShutdown)
  350. if err == nil {
  351. return nil
  352. }
  353. NoticeAlert("doUntunneledStatusRequest failed for %s:%s: %s",
  354. tunnel.serverEntry.IpAddress, port, err)
  355. }
  356. return errors.New("all attempts failed")
  357. }
  358. // doUntunneledStatusRequest attempts an untunneled stratus request.
  359. func doUntunneledStatusRequest(
  360. tunnel *Tunnel, port string, isShutdown bool) error {
  361. url := makeStatusRequestUrl(
  362. tunnel.serverContext.sessionId,
  363. makeBaseRequestUrl(tunnel, port, tunnel.serverContext.sessionId),
  364. false)
  365. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  366. if err != nil {
  367. return ContextError(err)
  368. }
  369. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  370. dialConfig := tunnel.untunneledDialConfig
  371. if isShutdown {
  372. timeout = PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT
  373. // Use a copy of DialConfig without pendingConns. This ensures
  374. // this request isn't interrupted/canceled. This measure should
  375. // be used only with the very short PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT.
  376. dialConfig = new(DialConfig)
  377. *dialConfig = *tunnel.untunneledDialConfig
  378. }
  379. httpClient, requestUrl, err := MakeUntunneledHttpsClient(
  380. dialConfig,
  381. certificate,
  382. url,
  383. timeout)
  384. if err != nil {
  385. return ContextError(err)
  386. }
  387. payload, payloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  388. if err != nil {
  389. return ContextError(err)
  390. }
  391. bodyType := "application/json"
  392. body := bytes.NewReader(payload)
  393. response, err := httpClient.Post(requestUrl, bodyType, body)
  394. if err == nil && response.StatusCode != http.StatusOK {
  395. response.Body.Close()
  396. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  397. }
  398. if err != nil {
  399. // Resend the transfer stats and tunnel stats later
  400. // Note: potential duplicate reports if the server received and processed
  401. // the request but the client failed to receive the response.
  402. putBackStatusRequestPayload(payloadInfo)
  403. // Trim this error since it may include long URLs
  404. return ContextError(TrimError(err))
  405. }
  406. confirmStatusRequestPayload(payloadInfo)
  407. response.Body.Close()
  408. return nil
  409. }
  410. // RecordTunnelStats records a tunnel duration and bytes
  411. // sent and received for subsequent reporting and quality
  412. // analysis.
  413. //
  414. // Tunnel durations are precisely measured client-side
  415. // and reported in status requests. As the duration is
  416. // not determined until the tunnel is closed, tunnel
  417. // stats records are stored in the persistent datastore
  418. // and reported via subsequent status requests sent to any
  419. // Psiphon server.
  420. //
  421. // Since the status request that reports a tunnel stats
  422. // record is not necessarily handled by the same server, the
  423. // tunnel stats records include the original server ID.
  424. //
  425. // Other fields that may change between tunnel stats recording
  426. // and reporting include client geo data, propagation channel,
  427. // sponsor ID, client version. These are not stored in the
  428. // datastore (client region, in particular, since that would
  429. // create an on-disk record of user location).
  430. // TODO: the server could encrypt, with a nonce and key unknown to
  431. // the client, a blob containing this data; return it in the
  432. // handshake response; and the client could store and later report
  433. // this blob with its tunnel stats records.
  434. //
  435. // Multiple "status" requests may be in flight at once (due
  436. // to multi-tunnel, asynchronous final status retry, and
  437. // aggressive status requests for pre-registered tunnels),
  438. // To avoid duplicate reporting, tunnel stats records are
  439. // "taken-out" by a status request and then "put back" in
  440. // case the request fails.
  441. //
  442. // Note: since tunnel stats records have a globally unique
  443. // identifier (sessionId + tunnelNumber), we could tolerate
  444. // duplicate reporting and filter our duplicates on the
  445. // server-side. Permitting duplicate reporting could increase
  446. // the velocity of reporting (for example, both the asynchronous
  447. // untunneled final status requests and the post-connected
  448. // immediate startus requests could try to report the same tunnel
  449. // stats).
  450. // Duplicate reporting may also occur when a server receives and
  451. // processes a status request but the client fails to receive
  452. // the response.
  453. func RecordTunnelStats(
  454. sessionId string,
  455. tunnelNumber int64,
  456. tunnelServerIpAddress string,
  457. serverHandshakeTimestamp, duration string,
  458. totalBytesSent, totalBytesReceived int64) error {
  459. tunnelStats := struct {
  460. SessionId string `json:"session_id"`
  461. TunnelNumber int64 `json:"tunnel_number"`
  462. TunnelServerIpAddress string `json:"tunnel_server_ip_address"`
  463. ServerHandshakeTimestamp string `json:"server_handshake_timestamp"`
  464. Duration string `json:"duration"`
  465. TotalBytesSent int64 `json:"total_bytes_sent"`
  466. TotalBytesReceived int64 `json:"total_bytes_received"`
  467. }{
  468. sessionId,
  469. tunnelNumber,
  470. tunnelServerIpAddress,
  471. serverHandshakeTimestamp,
  472. duration,
  473. totalBytesSent,
  474. totalBytesReceived,
  475. }
  476. tunnelStatsJson, err := json.Marshal(tunnelStats)
  477. if err != nil {
  478. return ContextError(err)
  479. }
  480. return StoreTunnelStats(tunnelStatsJson)
  481. }
  482. // DoClientVerificationRequest performs the client_verification API
  483. // request. This request is used to verify that the client is a
  484. // valid Psiphon client, which will determine how the server treats
  485. // the client traffic. The proof-of-validity is platform-specific
  486. // and the payload is opaque to this function but assumed to be JSON.
  487. func (serverContext *ServerContext) DoClientVerificationRequest(
  488. verificationPayload string) error {
  489. return serverContext.doPostRequest(
  490. buildRequestUrl(serverContext.baseRequestUrl, "client_verification"),
  491. "application/json",
  492. bytes.NewReader([]byte(verificationPayload)))
  493. }
  494. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  495. func (serverContext *ServerContext) doGetRequest(
  496. requestUrl string) (responseBody []byte, err error) {
  497. response, err := serverContext.psiphonHttpsClient.Get(requestUrl)
  498. if err == nil && response.StatusCode != http.StatusOK {
  499. response.Body.Close()
  500. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  501. }
  502. if err != nil {
  503. // Trim this error since it may include long URLs
  504. return nil, ContextError(TrimError(err))
  505. }
  506. defer response.Body.Close()
  507. body, err := ioutil.ReadAll(response.Body)
  508. if err != nil {
  509. return nil, ContextError(err)
  510. }
  511. return body, nil
  512. }
  513. // doPostRequest makes a tunneled HTTPS POST request.
  514. func (serverContext *ServerContext) doPostRequest(
  515. requestUrl string, bodyType string, body io.Reader) (err error) {
  516. response, err := serverContext.psiphonHttpsClient.Post(requestUrl, bodyType, body)
  517. if err == nil && response.StatusCode != http.StatusOK {
  518. response.Body.Close()
  519. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  520. }
  521. if err != nil {
  522. // Trim this error since it may include long URLs
  523. return ContextError(TrimError(err))
  524. }
  525. response.Body.Close()
  526. return nil
  527. }
  528. // makeBaseRequestUrl makes a URL containing all the common parameters
  529. // that are included with Psiphon API requests. These common parameters
  530. // are used for statistics.
  531. func makeBaseRequestUrl(tunnel *Tunnel, port, sessionId string) string {
  532. var requestUrl bytes.Buffer
  533. if port == "" {
  534. port = tunnel.serverEntry.WebServerPort
  535. }
  536. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  537. // e.g., don't do this: requestUrl.WriteString("https://")
  538. requestUrl.WriteString("http://")
  539. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  540. requestUrl.WriteString(":")
  541. requestUrl.WriteString(port)
  542. requestUrl.WriteString("/")
  543. // Placeholder for the path component of a request
  544. requestUrl.WriteString("%s")
  545. requestUrl.WriteString("?client_session_id=")
  546. requestUrl.WriteString(sessionId)
  547. requestUrl.WriteString("&server_secret=")
  548. requestUrl.WriteString(tunnel.serverEntry.WebServerSecret)
  549. requestUrl.WriteString("&propagation_channel_id=")
  550. requestUrl.WriteString(tunnel.config.PropagationChannelId)
  551. requestUrl.WriteString("&sponsor_id=")
  552. requestUrl.WriteString(tunnel.config.SponsorId)
  553. requestUrl.WriteString("&client_version=")
  554. requestUrl.WriteString(tunnel.config.ClientVersion)
  555. // TODO: client_tunnel_core_version
  556. requestUrl.WriteString("&relay_protocol=")
  557. requestUrl.WriteString(tunnel.protocol)
  558. requestUrl.WriteString("&client_platform=")
  559. requestUrl.WriteString(tunnel.config.ClientPlatform)
  560. requestUrl.WriteString("&tunnel_whole_device=")
  561. requestUrl.WriteString(strconv.Itoa(tunnel.config.TunnelWholeDevice))
  562. // The following parameters may be blank and must
  563. // not be sent to the server if blank.
  564. if tunnel.config.DeviceRegion != "" {
  565. requestUrl.WriteString("&device_region=")
  566. requestUrl.WriteString(tunnel.config.DeviceRegion)
  567. }
  568. if tunnel.meekStats != nil {
  569. if tunnel.meekStats.DialAddress != "" {
  570. requestUrl.WriteString("&meek_dial_address=")
  571. requestUrl.WriteString(tunnel.meekStats.DialAddress)
  572. }
  573. if tunnel.meekStats.ResolvedIPAddress != "" {
  574. requestUrl.WriteString("&meek_resolved_ip_address=")
  575. requestUrl.WriteString(tunnel.meekStats.ResolvedIPAddress)
  576. }
  577. if tunnel.meekStats.SNIServerName != "" {
  578. requestUrl.WriteString("&meek_sni_server_name=")
  579. requestUrl.WriteString(tunnel.meekStats.SNIServerName)
  580. }
  581. if tunnel.meekStats.HostHeader != "" {
  582. requestUrl.WriteString("&meek_host_header=")
  583. requestUrl.WriteString(tunnel.meekStats.HostHeader)
  584. }
  585. requestUrl.WriteString("&meek_transformed_host_name=")
  586. if tunnel.meekStats.TransformedHostName {
  587. requestUrl.WriteString("1")
  588. } else {
  589. requestUrl.WriteString("0")
  590. }
  591. }
  592. if tunnel.serverEntry.Region != "" {
  593. requestUrl.WriteString("&server_entry_region=")
  594. requestUrl.WriteString(tunnel.serverEntry.Region)
  595. }
  596. if tunnel.serverEntry.LocalSource != "" {
  597. requestUrl.WriteString("&server_entry_source=")
  598. requestUrl.WriteString(tunnel.serverEntry.LocalSource)
  599. }
  600. // As with last_connected, this timestamp stat, which may be
  601. // a precise handshake request server timestamp, is truncated
  602. // to hour granularity to avoid introducing a reconstructable
  603. // cross-session user trace into server logs.
  604. localServerEntryTimestamp := TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  605. if localServerEntryTimestamp != "" {
  606. requestUrl.WriteString("&server_entry_timestamp=")
  607. requestUrl.WriteString(localServerEntryTimestamp)
  608. }
  609. return requestUrl.String()
  610. }
  611. type ExtraParam struct{ name, value string }
  612. // buildRequestUrl makes a URL for an API request. The URL includes the
  613. // base request URL and any extra parameters for the specific request.
  614. func buildRequestUrl(baseRequestUrl, path string, extraParams ...*ExtraParam) string {
  615. var requestUrl bytes.Buffer
  616. requestUrl.WriteString(fmt.Sprintf(baseRequestUrl, path))
  617. for _, extraParam := range extraParams {
  618. requestUrl.WriteString("&")
  619. requestUrl.WriteString(extraParam.name)
  620. requestUrl.WriteString("=")
  621. requestUrl.WriteString(extraParam.value)
  622. }
  623. return requestUrl.String()
  624. }
  625. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels requests and which validates
  626. // the web server using the Psiphon server entry web server certificate.
  627. // This is not a general purpose HTTPS client.
  628. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  629. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  630. // handshake inside the explicit TLS session.
  631. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  632. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  633. if err != nil {
  634. return nil, ContextError(err)
  635. }
  636. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  637. // TODO: check tunnel.isClosed, and apply TUNNEL_PORT_FORWARD_DIAL_TIMEOUT as in Tunnel.Dial?
  638. return tunnel.sshClient.Dial("tcp", addr)
  639. }
  640. timeout := time.Duration(*tunnel.config.PsiphonApiServerTimeoutSeconds) * time.Second
  641. dialer := NewCustomTLSDialer(
  642. &CustomTLSConfig{
  643. Dial: tunneledDialer,
  644. Timeout: timeout,
  645. VerifyLegacyCertificate: certificate,
  646. })
  647. transport := &http.Transport{
  648. Dial: dialer,
  649. ResponseHeaderTimeout: timeout,
  650. }
  651. return &http.Client{
  652. Transport: transport,
  653. Timeout: timeout,
  654. }, nil
  655. }