serverApi.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. "context"
  23. "encoding/base64"
  24. "encoding/hex"
  25. "encoding/json"
  26. "errors"
  27. "fmt"
  28. "io"
  29. "io/ioutil"
  30. "net"
  31. "net/http"
  32. "net/url"
  33. "strconv"
  34. "sync/atomic"
  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 tunneled 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) (*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: tunnel.sessionId,
  93. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  94. tunnel: tunnel,
  95. psiphonHttpsClient: psiphonHttpsClient,
  96. }
  97. err := serverContext.doHandshakeRequest(tunnel.config.IgnoreHandshakeStatsRegexps)
  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(
  107. ignoreStatsRegexps bool) error {
  108. params := serverContext.getBaseParams()
  109. var response []byte
  110. if serverContext.psiphonHttpsClient == nil {
  111. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] = serverContext.tunnel.config.Authorizations
  112. request, err := makeSSHAPIRequestPayload(params)
  113. if err != nil {
  114. return common.ContextError(err)
  115. }
  116. response, err = serverContext.tunnel.SendAPIRequest(
  117. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  118. if err != nil {
  119. return common.ContextError(err)
  120. }
  121. } else {
  122. // Legacy web service API request
  123. responseBody, err := serverContext.doGetRequest(
  124. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  125. if err != nil {
  126. return common.ContextError(err)
  127. }
  128. // Skip legacy format lines and just parse the JSON config line
  129. configLinePrefix := []byte("Config: ")
  130. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  131. if bytes.HasPrefix(line, configLinePrefix) {
  132. response = line[len(configLinePrefix):]
  133. break
  134. }
  135. }
  136. if len(response) == 0 {
  137. return common.ContextError(errors.New("no config line found"))
  138. }
  139. }
  140. // Legacy fields:
  141. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  142. // - 'ssh_session_id' is ignored; client session ID is used instead
  143. var handshakeResponse protocol.HandshakeResponse
  144. err := json.Unmarshal(response, &handshakeResponse)
  145. if err != nil {
  146. return common.ContextError(err)
  147. }
  148. serverContext.clientRegion = handshakeResponse.ClientRegion
  149. NoticeClientRegion(serverContext.clientRegion)
  150. var decodedServerEntries []*protocol.ServerEntry
  151. // Store discovered server entries
  152. // We use the server's time, as it's available here, for the server entry
  153. // timestamp since this is more reliable than the client time.
  154. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  155. serverEntry, err := protocol.DecodeServerEntry(
  156. encodedServerEntry,
  157. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  158. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  159. if err != nil {
  160. return common.ContextError(err)
  161. }
  162. err = protocol.ValidateServerEntry(serverEntry)
  163. if err != nil {
  164. // Skip this entry and continue with the next one
  165. NoticeAlert("invalid server entry: %s", err)
  166. continue
  167. }
  168. decodedServerEntries = append(decodedServerEntries, serverEntry)
  169. }
  170. // The reason we are storing the entire array of server entries at once rather
  171. // than one at a time is that some desirable side-effects get triggered by
  172. // StoreServerEntries that don't get triggered by StoreServerEntry.
  173. err = StoreServerEntries(decodedServerEntries, true)
  174. if err != nil {
  175. return common.ContextError(err)
  176. }
  177. NoticeHomepages(handshakeResponse.Homepages)
  178. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  179. if handshakeResponse.UpgradeClientVersion != "" {
  180. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  181. } else {
  182. NoticeClientIsLatestVersion("")
  183. }
  184. if !ignoreStatsRegexps {
  185. var regexpsNotices []string
  186. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  187. handshakeResponse.PageViewRegexes,
  188. handshakeResponse.HttpsRequestRegexes)
  189. for _, notice := range regexpsNotices {
  190. NoticeAlert(notice)
  191. }
  192. }
  193. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  194. NoticeServerTimestamp(serverContext.serverHandshakeTimestamp)
  195. NoticeActiveAuthorizationIDs(handshakeResponse.ActiveAuthorizationIDs)
  196. return nil
  197. }
  198. // DoConnectedRequest performs the "connected" API request. This request is
  199. // used for statistics. The server returns a last_connected token for
  200. // the client to store and send next time it connects. This token is
  201. // a timestamp (using the server clock, and should be rounded to the
  202. // nearest hour) which is used to determine when a connection represents
  203. // a unique user for a time period.
  204. func (serverContext *ServerContext) DoConnectedRequest() error {
  205. params := serverContext.getBaseParams()
  206. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  207. if err != nil {
  208. return common.ContextError(err)
  209. }
  210. if lastConnected == "" {
  211. lastConnected = "None"
  212. }
  213. params["last_connected"] = lastConnected
  214. // serverContext.tunnel.establishDuration is nanoseconds; divide to get to milliseconds
  215. params["establishment_duration"] =
  216. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/1000000)
  217. var response []byte
  218. if serverContext.psiphonHttpsClient == nil {
  219. request, err := makeSSHAPIRequestPayload(params)
  220. if err != nil {
  221. return common.ContextError(err)
  222. }
  223. response, err = serverContext.tunnel.SendAPIRequest(
  224. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  225. if err != nil {
  226. return common.ContextError(err)
  227. }
  228. } else {
  229. // Legacy web service API request
  230. response, err = serverContext.doGetRequest(
  231. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  232. if err != nil {
  233. return common.ContextError(err)
  234. }
  235. }
  236. var connectedResponse protocol.ConnectedResponse
  237. err = json.Unmarshal(response, &connectedResponse)
  238. if err != nil {
  239. return common.ContextError(err)
  240. }
  241. err = SetKeyValue(
  242. DATA_STORE_LAST_CONNECTED_KEY, connectedResponse.ConnectedTimestamp)
  243. if err != nil {
  244. return common.ContextError(err)
  245. }
  246. return nil
  247. }
  248. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  249. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  250. return serverContext.statsRegexps
  251. }
  252. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  253. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  254. params := serverContext.getStatusParams(true)
  255. // Note: ensure putBackStatusRequestPayload is called, to replace
  256. // payload for future attempt, in all failure cases.
  257. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  258. tunnel.serverEntry.IpAddress)
  259. if err != nil {
  260. return common.ContextError(err)
  261. }
  262. // Skip the request when there's no payload to send.
  263. if len(statusPayload) == 0 {
  264. return nil
  265. }
  266. if serverContext.psiphonHttpsClient == nil {
  267. rawMessage := json.RawMessage(statusPayload)
  268. params["statusData"] = &rawMessage
  269. var request []byte
  270. request, err = makeSSHAPIRequestPayload(params)
  271. if err == nil {
  272. _, err = serverContext.tunnel.SendAPIRequest(
  273. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  274. }
  275. } else {
  276. // Legacy web service API request
  277. _, err = serverContext.doPostRequest(
  278. makeRequestUrl(serverContext.tunnel, "", "status", params),
  279. "application/json",
  280. bytes.NewReader(statusPayload))
  281. }
  282. if err != nil {
  283. // Resend the transfer stats and tunnel stats later
  284. // Note: potential duplicate reports if the server received and processed
  285. // the request but the client failed to receive the response.
  286. putBackStatusRequestPayload(statusPayloadInfo)
  287. return common.ContextError(err)
  288. }
  289. confirmStatusRequestPayload(statusPayloadInfo)
  290. return nil
  291. }
  292. func (serverContext *ServerContext) getStatusParams(isTunneled bool) requestJSONObject {
  293. params := serverContext.getBaseParams()
  294. // Add a random amount of padding to help prevent stats updates from being
  295. // a predictable size (which often happens when the connection is quiet).
  296. // TODO: base64 encoding of padding means the padding size is not exactly
  297. // [0, PADDING_MAX_BYTES].
  298. randomPadding, err := common.MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  299. if err != nil {
  300. NoticeAlert("MakeSecureRandomPadding failed: %s", common.ContextError(err))
  301. // Proceed without random padding
  302. randomPadding = make([]byte, 0)
  303. }
  304. params["padding"] = base64.StdEncoding.EncodeToString(randomPadding)
  305. // Legacy clients set "connected" to "0" when disconnecting, and this value
  306. // is used to calculate session duration estimates. This is now superseded
  307. // by explicit tunnel stats duration reporting.
  308. // The legacy method of reconstructing session durations is not compatible
  309. // with this client's connected request retries and asynchronous final
  310. // status request attempts. So we simply set this "connected" flag to reflect
  311. // whether the request is sent tunneled or not.
  312. connected := "1"
  313. if !isTunneled {
  314. connected = "0"
  315. }
  316. params["connected"] = connected
  317. return params
  318. }
  319. // statusRequestPayloadInfo is a temporary structure for data used to
  320. // either "clear" or "put back" status request payload data depending
  321. // on whether or not the request succeeded.
  322. type statusRequestPayloadInfo struct {
  323. serverId string
  324. transferStats *transferstats.AccumulatedStats
  325. persistentStats map[string][][]byte
  326. }
  327. func makeStatusRequestPayload(
  328. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  329. transferStats := transferstats.TakeOutStatsForServer(serverId)
  330. hostBytes := transferStats.GetStatsForStatusRequest()
  331. persistentStats, err := TakeOutUnreportedPersistentStats(
  332. PSIPHON_API_PERSISTENT_STATS_MAX_COUNT)
  333. if err != nil {
  334. NoticeAlert(
  335. "TakeOutUnreportedPersistentStats failed: %s", common.ContextError(err))
  336. persistentStats = nil
  337. // Proceed with transferStats only
  338. }
  339. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  340. // There is no payload to send.
  341. return nil, nil, nil
  342. }
  343. payloadInfo := &statusRequestPayloadInfo{
  344. serverId, transferStats, persistentStats}
  345. payload := make(map[string]interface{})
  346. payload["host_bytes"] = hostBytes
  347. // We're not recording these fields, but legacy servers require them.
  348. payload["bytes_transferred"] = 0
  349. payload["page_views"] = make([]string, 0)
  350. payload["https_requests"] = make([]string, 0)
  351. persistentStatPayloadNames := make(map[string]string)
  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. // RecordRemoteServerListStat records a completed common or OSL
  389. // remote server list resource download.
  390. //
  391. // The RSL download event could occur when the client is unable
  392. // to immediately send a status request to a server, so these
  393. // records are stored in the persistent datastore and reported
  394. // via subsequent status requests sent to any Psiphon server.
  395. //
  396. // Note that common event field values may change between the
  397. // stat recording and reporting include client geo data,
  398. // propagation channel, sponsor ID, client version. These are not
  399. // stored in the datastore (client region, in particular, since
  400. // that would create an on-disk record of user location).
  401. // TODO: the server could encrypt, with a nonce and key unknown to
  402. // the client, a blob containing this data; return it in the
  403. // handshake response; and the client could store and later report
  404. // this blob with its tunnel stats records.
  405. //
  406. // Multiple "status" requests may be in flight at once (due
  407. // to multi-tunnel, asynchronous final status retry, and
  408. // aggressive status requests for pre-registered tunnels),
  409. // To avoid duplicate reporting, persistent stats records are
  410. // "taken-out" by a status request and then "put back" in
  411. // case the request fails.
  412. //
  413. // Duplicate reporting may also occur when a server receives and
  414. // processes a status request but the client fails to receive
  415. // the response.
  416. func RecordRemoteServerListStat(
  417. url, etag string) error {
  418. remoteServerListStat := struct {
  419. ClientDownloadTimestamp string `json:"client_download_timestamp"`
  420. URL string `json:"url"`
  421. ETag string `json:"etag"`
  422. }{
  423. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  424. url,
  425. etag,
  426. }
  427. remoteServerListStatJson, err := json.Marshal(remoteServerListStat)
  428. if err != nil {
  429. return common.ContextError(err)
  430. }
  431. return StorePersistentStat(
  432. PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST, remoteServerListStatJson)
  433. }
  434. // DoClientVerificationRequest performs the "client_verification" API
  435. // request. This request is used to verify that the client is a valid
  436. // Psiphon client, which will determine how the server treats the client
  437. // traffic. The proof-of-validity is platform-specific and the payload
  438. // is opaque to this function but assumed to be JSON.
  439. func (serverContext *ServerContext) DoClientVerificationRequest(
  440. verificationPayload string, serverIP string) error {
  441. params := serverContext.getBaseParams()
  442. var response []byte
  443. var err error
  444. if serverContext.psiphonHttpsClient == nil {
  445. // Empty verification payload signals desire to
  446. // query the server for current TTL. This is
  447. // indicated to the server by the absence of the
  448. // verificationData field.
  449. if verificationPayload != "" {
  450. rawMessage := json.RawMessage(verificationPayload)
  451. params["verificationData"] = &rawMessage
  452. }
  453. request, err := makeSSHAPIRequestPayload(params)
  454. if err != nil {
  455. return common.ContextError(err)
  456. }
  457. response, err = serverContext.tunnel.SendAPIRequest(
  458. protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME, request)
  459. if err != nil {
  460. return common.ContextError(err)
  461. }
  462. } else {
  463. // Legacy web service API request
  464. response, err = serverContext.doPostRequest(
  465. makeRequestUrl(serverContext.tunnel, "", "client_verification", params),
  466. "application/json",
  467. bytes.NewReader([]byte(verificationPayload)))
  468. if err != nil {
  469. return common.ContextError(err)
  470. }
  471. }
  472. // Server may request a new verification to be performed,
  473. // for example, if the payload timestamp is too old, etc.
  474. var clientVerificationResponse struct {
  475. ClientVerificationServerNonce string `json:"client_verification_server_nonce"`
  476. ClientVerificationTTLSeconds int `json:"client_verification_ttl_seconds"`
  477. ClientVerificationResetCache bool `json:"client_verification_reset_cache"`
  478. }
  479. // In case of empty response body the json.Unmarshal will fail
  480. // and clientVerificationResponse will be initialized with default values
  481. _ = json.Unmarshal(response, &clientVerificationResponse)
  482. if clientVerificationResponse.ClientVerificationTTLSeconds > 0 {
  483. NoticeClientVerificationRequired(
  484. clientVerificationResponse.ClientVerificationServerNonce,
  485. clientVerificationResponse.ClientVerificationTTLSeconds,
  486. clientVerificationResponse.ClientVerificationResetCache)
  487. } else {
  488. NoticeClientVerificationRequestCompleted(serverIP)
  489. }
  490. return nil
  491. }
  492. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  493. func (serverContext *ServerContext) doGetRequest(
  494. requestUrl string) (responseBody []byte, err error) {
  495. request, err := http.NewRequest("GET", requestUrl, nil)
  496. if err != nil {
  497. return nil, common.ContextError(err)
  498. }
  499. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  500. response, err := serverContext.psiphonHttpsClient.Do(request)
  501. if err == nil && response.StatusCode != http.StatusOK {
  502. response.Body.Close()
  503. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  504. }
  505. if err != nil {
  506. // Trim this error since it may include long URLs
  507. return nil, common.ContextError(TrimError(err))
  508. }
  509. defer response.Body.Close()
  510. body, err := ioutil.ReadAll(response.Body)
  511. if err != nil {
  512. return nil, common.ContextError(err)
  513. }
  514. return body, nil
  515. }
  516. // doPostRequest makes a tunneled HTTPS POST request.
  517. func (serverContext *ServerContext) doPostRequest(
  518. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  519. request, err := http.NewRequest("POST", requestUrl, body)
  520. if err != nil {
  521. return nil, common.ContextError(err)
  522. }
  523. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  524. request.Header.Set("Content-Type", bodyType)
  525. response, err := serverContext.psiphonHttpsClient.Do(request)
  526. if err == nil && response.StatusCode != http.StatusOK {
  527. response.Body.Close()
  528. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  529. }
  530. if err != nil {
  531. // Trim this error since it may include long URLs
  532. return nil, common.ContextError(TrimError(err))
  533. }
  534. defer response.Body.Close()
  535. responseBody, err = ioutil.ReadAll(response.Body)
  536. if err != nil {
  537. return nil, common.ContextError(err)
  538. }
  539. return responseBody, nil
  540. }
  541. type requestJSONObject map[string]interface{}
  542. // getBaseParams returns all the common API parameters that are included
  543. // with each Psiphon API request. These common parameters are used for
  544. // statistics.
  545. func (serverContext *ServerContext) getBaseParams() requestJSONObject {
  546. params := make(requestJSONObject)
  547. tunnel := serverContext.tunnel
  548. params["session_id"] = serverContext.sessionId
  549. params["client_session_id"] = serverContext.sessionId
  550. params["server_secret"] = tunnel.serverEntry.WebServerSecret
  551. params["propagation_channel_id"] = tunnel.config.PropagationChannelId
  552. params["sponsor_id"] = tunnel.config.SponsorId
  553. params["client_version"] = tunnel.config.ClientVersion
  554. // TODO: client_tunnel_core_version?
  555. params["relay_protocol"] = tunnel.protocol
  556. params["client_platform"] = tunnel.config.ClientPlatform
  557. params["client_build_rev"] = common.GetBuildInfo().BuildRev
  558. params["tunnel_whole_device"] = strconv.Itoa(tunnel.config.TunnelWholeDevice)
  559. // The following parameters may be blank and must
  560. // not be sent to the server if blank.
  561. if tunnel.config.DeviceRegion != "" {
  562. params["device_region"] = tunnel.config.DeviceRegion
  563. }
  564. if tunnel.dialStats.SelectedSSHClientVersion {
  565. params["ssh_client_version"] = tunnel.dialStats.SSHClientVersion
  566. }
  567. if tunnel.dialStats.UpstreamProxyType != "" {
  568. params["upstream_proxy_type"] = tunnel.dialStats.UpstreamProxyType
  569. }
  570. if tunnel.dialStats.UpstreamProxyCustomHeaderNames != nil {
  571. params["upstream_proxy_custom_header_names"] = tunnel.dialStats.UpstreamProxyCustomHeaderNames
  572. }
  573. if tunnel.dialStats.MeekDialAddress != "" {
  574. params["meek_dial_address"] = tunnel.dialStats.MeekDialAddress
  575. }
  576. if tunnel.dialStats.MeekResolvedIPAddress != "" {
  577. params["meek_resolved_ip_address"] = tunnel.dialStats.MeekResolvedIPAddress
  578. }
  579. if tunnel.dialStats.MeekSNIServerName != "" {
  580. params["meek_sni_server_name"] = tunnel.dialStats.MeekSNIServerName
  581. }
  582. if tunnel.dialStats.MeekHostHeader != "" {
  583. params["meek_host_header"] = tunnel.dialStats.MeekHostHeader
  584. }
  585. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  586. if tunnel.dialStats.MeekDialAddress != "" {
  587. transformedHostName := "0"
  588. if tunnel.dialStats.MeekTransformedHostName {
  589. transformedHostName = "1"
  590. }
  591. params["meek_transformed_host_name"] = transformedHostName
  592. }
  593. if tunnel.dialStats.SelectedUserAgent {
  594. params["user_agent"] = tunnel.dialStats.UserAgent
  595. }
  596. if tunnel.dialStats.SelectedTLSProfile {
  597. params["tls_profile"] = tunnel.dialStats.TLSProfile
  598. }
  599. if tunnel.serverEntry.Region != "" {
  600. params["server_entry_region"] = tunnel.serverEntry.Region
  601. }
  602. if tunnel.serverEntry.LocalSource != "" {
  603. params["server_entry_source"] = tunnel.serverEntry.LocalSource
  604. }
  605. // As with last_connected, this timestamp stat, which may be
  606. // a precise handshake request server timestamp, is truncated
  607. // to hour granularity to avoid introducing a reconstructable
  608. // cross-session user trace into server logs.
  609. localServerEntryTimestamp := common.TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  610. if localServerEntryTimestamp != "" {
  611. params["server_entry_timestamp"] = localServerEntryTimestamp
  612. }
  613. return params
  614. }
  615. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  616. func makeSSHAPIRequestPayload(params requestJSONObject) ([]byte, error) {
  617. jsonPayload, err := json.Marshal(params)
  618. if err != nil {
  619. return nil, common.ContextError(err)
  620. }
  621. return jsonPayload, nil
  622. }
  623. // makeRequestUrl makes a URL for a web service API request.
  624. func makeRequestUrl(tunnel *Tunnel, port, path string, params requestJSONObject) string {
  625. var requestUrl bytes.Buffer
  626. if port == "" {
  627. port = tunnel.serverEntry.WebServerPort
  628. }
  629. requestUrl.WriteString("https://")
  630. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  631. requestUrl.WriteString(":")
  632. requestUrl.WriteString(port)
  633. requestUrl.WriteString("/")
  634. requestUrl.WriteString(path)
  635. if len(params) > 0 {
  636. queryParams := url.Values{}
  637. for name, value := range params {
  638. strValue := ""
  639. switch v := value.(type) {
  640. case string:
  641. strValue = v
  642. case []string:
  643. // String array param encoded as JSON
  644. jsonValue, err := json.Marshal(v)
  645. if err != nil {
  646. break
  647. }
  648. strValue = string(jsonValue)
  649. }
  650. queryParams.Set(name, strValue)
  651. }
  652. requestUrl.WriteString("?")
  653. requestUrl.WriteString(queryParams.Encode())
  654. }
  655. return requestUrl.String()
  656. }
  657. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  658. // requests and which validates the web server using the Psiphon server entry web server
  659. // certificate.
  660. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  661. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  662. if err != nil {
  663. return nil, common.ContextError(err)
  664. }
  665. tunneledDialer := func(_ context.Context, _, addr string) (conn net.Conn, err error) {
  666. return tunnel.sshClient.Dial("tcp", addr)
  667. }
  668. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  669. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  670. // the request. While it's possible to add a timeout here, we leave it with no explicit
  671. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  672. // alives will cause the tunnel to close.
  673. dialer := NewCustomTLSDialer(
  674. &CustomTLSConfig{
  675. Dial: tunneledDialer,
  676. VerifyLegacyCertificate: certificate,
  677. })
  678. transport := &http.Transport{
  679. DialTLS: func(network, addr string) (net.Conn, error) {
  680. return dialer(context.Background(), network, addr)
  681. },
  682. Dial: func(network, addr string) (net.Conn, error) {
  683. return nil, errors.New("HTTP not supported")
  684. },
  685. }
  686. return &http.Client{
  687. Transport: transport,
  688. }, nil
  689. }
  690. func HandleServerRequest(
  691. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  692. switch name {
  693. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  694. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  695. }
  696. return common.ContextError(fmt.Errorf("invalid request name: %s", name))
  697. }
  698. func HandleOSLRequest(
  699. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  700. var oslRequest protocol.OSLRequest
  701. err := json.Unmarshal(payload, &oslRequest)
  702. if err != nil {
  703. return common.ContextError(err)
  704. }
  705. if oslRequest.ClearLocalSLOKs {
  706. DeleteSLOKs()
  707. }
  708. seededNewSLOK := false
  709. for _, slok := range oslRequest.SeedPayload.SLOKs {
  710. duplicate, err := SetSLOK(slok.ID, slok.Key)
  711. if err != nil {
  712. // TODO: return error to trigger retry?
  713. NoticeAlert("SetSLOK failed: %s", common.ContextError(err))
  714. } else if !duplicate {
  715. seededNewSLOK = true
  716. }
  717. if tunnel.config.EmitSLOKs {
  718. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  719. }
  720. }
  721. if seededNewSLOK {
  722. tunnelOwner.SignalSeededNewSLOK()
  723. }
  724. return nil
  725. }