serverApi.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. // *TODO*: this is obsolete?
  110. /*
  111. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  112. if err != nil {
  113. return common.ContextError(err)
  114. }
  115. // Submit a list of known servers -- this will be used for
  116. // discovery statistics.
  117. for _, ipAddress := range serverEntryIpAddresses {
  118. params = append(params, requestParam{"known_server", ipAddress})
  119. }
  120. */
  121. var response []byte
  122. if serverContext.psiphonHttpsClient == nil {
  123. request, err := makeSSHAPIRequestPayload(params)
  124. if err != nil {
  125. return common.ContextError(err)
  126. }
  127. response, err = serverContext.tunnel.SendAPIRequest(
  128. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  129. if err != nil {
  130. return common.ContextError(err)
  131. }
  132. } else {
  133. // Legacy web service API request
  134. responseBody, err := serverContext.doGetRequest(
  135. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  136. if err != nil {
  137. return common.ContextError(err)
  138. }
  139. // Skip legacy format lines and just parse the JSON config line
  140. configLinePrefix := []byte("Config: ")
  141. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  142. if bytes.HasPrefix(line, configLinePrefix) {
  143. response = line[len(configLinePrefix):]
  144. break
  145. }
  146. }
  147. if len(response) == 0 {
  148. return common.ContextError(errors.New("no config line found"))
  149. }
  150. }
  151. // Legacy fields:
  152. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  153. // - 'ssh_session_id' is ignored; client session ID is used instead
  154. var handshakeResponse protocol.HandshakeResponse
  155. err := json.Unmarshal(response, &handshakeResponse)
  156. if err != nil {
  157. return common.ContextError(err)
  158. }
  159. serverContext.clientRegion = handshakeResponse.ClientRegion
  160. NoticeClientRegion(serverContext.clientRegion)
  161. var decodedServerEntries []*protocol.ServerEntry
  162. // Store discovered server entries
  163. // We use the server's time, as it's available here, for the server entry
  164. // timestamp since this is more reliable than the client time.
  165. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  166. serverEntry, err := protocol.DecodeServerEntry(
  167. encodedServerEntry,
  168. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  169. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  170. if err != nil {
  171. return common.ContextError(err)
  172. }
  173. err = protocol.ValidateServerEntry(serverEntry)
  174. if err != nil {
  175. // Skip this entry and continue with the next one
  176. NoticeAlert("invalid server entry: %s", err)
  177. continue
  178. }
  179. decodedServerEntries = append(decodedServerEntries, serverEntry)
  180. }
  181. // The reason we are storing the entire array of server entries at once rather
  182. // than one at a time is that some desirable side-effects get triggered by
  183. // StoreServerEntries that don't get triggered by StoreServerEntry.
  184. err = StoreServerEntries(decodedServerEntries, true)
  185. if err != nil {
  186. return common.ContextError(err)
  187. }
  188. NoticeHomepages(handshakeResponse.Homepages)
  189. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  190. if handshakeResponse.UpgradeClientVersion != "" {
  191. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  192. } else {
  193. NoticeClientIsLatestVersion("")
  194. }
  195. if !ignoreStatsRegexps {
  196. var regexpsNotices []string
  197. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  198. handshakeResponse.PageViewRegexes,
  199. handshakeResponse.HttpsRequestRegexes)
  200. for _, notice := range regexpsNotices {
  201. NoticeAlert(notice)
  202. }
  203. }
  204. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  205. NoticeServerTimestamp(serverContext.serverHandshakeTimestamp)
  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. // RecordTunnelStat records a tunnel duration and bytes
  389. // sent and received for subsequent reporting and quality
  390. // analysis.
  391. //
  392. // Tunnel durations are precisely measured client-side
  393. // and reported in status requests. As the duration is
  394. // not determined until the tunnel is closed, tunnel
  395. // stats records are stored in the persistent datastore
  396. // and reported via subsequent status requests sent to any
  397. // Psiphon server.
  398. //
  399. // Since the status request that reports a tunnel stats
  400. // record is not necessarily handled by the same server, the
  401. // tunnel stats records include the original server ID.
  402. //
  403. // Other fields that may change between tunnel stats recording
  404. // and reporting include client geo data, propagation channel,
  405. // sponsor ID, client version. These are not stored in the
  406. // datastore (client region, in particular, since that would
  407. // create an on-disk record of user location).
  408. // TODO: the server could encrypt, with a nonce and key unknown to
  409. // the client, a blob containing this data; return it in the
  410. // handshake response; and the client could store and later report
  411. // this blob with its tunnel stats records.
  412. //
  413. // Multiple "status" requests may be in flight at once (due
  414. // to multi-tunnel, asynchronous final status retry, and
  415. // aggressive status requests for pre-registered tunnels),
  416. // To avoid duplicate reporting, tunnel stats records are
  417. // "taken-out" by a status request and then "put back" in
  418. // case the request fails.
  419. //
  420. // Note: since tunnel stats records have a globally unique
  421. // identifier (sessionId + tunnelNumber), we could tolerate
  422. // duplicate reporting and filter our duplicates on the
  423. // server-side. Permitting duplicate reporting could increase
  424. // the velocity of reporting (for example, both the asynchronous
  425. // untunneled final status requests and the post-connected
  426. // immediate status requests could try to report the same tunnel
  427. // stats).
  428. // Duplicate reporting may also occur when a server receives and
  429. // processes a status request but the client fails to receive
  430. // the response.
  431. func RecordTunnelStat(
  432. sessionId string,
  433. tunnelNumber int64,
  434. tunnelServerIpAddress string,
  435. establishmentDuration string,
  436. serverHandshakeTimestamp string,
  437. tunnelDuration string,
  438. totalBytesSent int64,
  439. totalBytesReceived int64) error {
  440. tunnelStat := struct {
  441. SessionId string `json:"session_id"`
  442. TunnelNumber int64 `json:"tunnel_number"`
  443. TunnelServerIpAddress string `json:"tunnel_server_ip_address"`
  444. EstablishmentDuration string `json:"establishment_duration"`
  445. ServerHandshakeTimestamp string `json:"server_handshake_timestamp"`
  446. Duration string `json:"duration"`
  447. TotalBytesSent int64 `json:"total_bytes_sent"`
  448. TotalBytesReceived int64 `json:"total_bytes_received"`
  449. }{
  450. sessionId,
  451. tunnelNumber,
  452. tunnelServerIpAddress,
  453. establishmentDuration,
  454. serverHandshakeTimestamp,
  455. tunnelDuration,
  456. totalBytesSent,
  457. totalBytesReceived,
  458. }
  459. tunnelStatJson, err := json.Marshal(tunnelStat)
  460. if err != nil {
  461. return common.ContextError(err)
  462. }
  463. return StorePersistentStat(
  464. PERSISTENT_STAT_TYPE_TUNNEL, tunnelStatJson)
  465. }
  466. // RecordRemoteServerListStat records a completed common or OSL
  467. // remote server list resource download. These stats use the same
  468. // persist-until-reported mechanism described in RecordTunnelStats.
  469. func RecordRemoteServerListStat(
  470. url, etag string) error {
  471. remoteServerListStat := struct {
  472. ClientDownloadTimestamp string `json:"client_download_timestamp"`
  473. URL string `json:"url"`
  474. ETag string `json:"etag"`
  475. }{
  476. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  477. url,
  478. etag,
  479. }
  480. remoteServerListStatJson, err := json.Marshal(remoteServerListStat)
  481. if err != nil {
  482. return common.ContextError(err)
  483. }
  484. return StorePersistentStat(
  485. PERSISTENT_STAT_TYPE_REMOTE_SERVER_LIST, remoteServerListStatJson)
  486. }
  487. // DoClientVerificationRequest performs the "client_verification" API
  488. // request. This request is used to verify that the client is a valid
  489. // Psiphon client, which will determine how the server treats the client
  490. // traffic. The proof-of-validity is platform-specific and the payload
  491. // is opaque to this function but assumed to be JSON.
  492. func (serverContext *ServerContext) DoClientVerificationRequest(
  493. verificationPayload string, serverIP string) error {
  494. params := serverContext.getBaseParams()
  495. var response []byte
  496. var err error
  497. if serverContext.psiphonHttpsClient == nil {
  498. // Empty verification payload signals desire to
  499. // query the server for current TTL. This is
  500. // indicated to the server by the absence of the
  501. // verificationData field.
  502. if verificationPayload != "" {
  503. rawMessage := json.RawMessage(verificationPayload)
  504. params["verificationData"] = &rawMessage
  505. }
  506. request, err := makeSSHAPIRequestPayload(params)
  507. if err != nil {
  508. return common.ContextError(err)
  509. }
  510. response, err = serverContext.tunnel.SendAPIRequest(
  511. protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME, request)
  512. if err != nil {
  513. return common.ContextError(err)
  514. }
  515. } else {
  516. // Legacy web service API request
  517. response, err = serverContext.doPostRequest(
  518. makeRequestUrl(serverContext.tunnel, "", "client_verification", params),
  519. "application/json",
  520. bytes.NewReader([]byte(verificationPayload)))
  521. if err != nil {
  522. return common.ContextError(err)
  523. }
  524. }
  525. // Server may request a new verification to be performed,
  526. // for example, if the payload timestamp is too old, etc.
  527. var clientVerificationResponse struct {
  528. ClientVerificationServerNonce string `json:"client_verification_server_nonce"`
  529. ClientVerificationTTLSeconds int `json:"client_verification_ttl_seconds"`
  530. ClientVerificationResetCache bool `json:"client_verification_reset_cache"`
  531. }
  532. // In case of empty response body the json.Unmarshal will fail
  533. // and clientVerificationResponse will be initialized with default values
  534. _ = json.Unmarshal(response, &clientVerificationResponse)
  535. if clientVerificationResponse.ClientVerificationTTLSeconds > 0 {
  536. NoticeClientVerificationRequired(
  537. clientVerificationResponse.ClientVerificationServerNonce,
  538. clientVerificationResponse.ClientVerificationTTLSeconds,
  539. clientVerificationResponse.ClientVerificationResetCache)
  540. } else {
  541. NoticeClientVerificationRequestCompleted(serverIP)
  542. }
  543. return nil
  544. }
  545. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  546. func (serverContext *ServerContext) doGetRequest(
  547. requestUrl string) (responseBody []byte, err error) {
  548. request, err := http.NewRequest("GET", requestUrl, nil)
  549. if err != nil {
  550. return nil, common.ContextError(err)
  551. }
  552. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  553. response, err := serverContext.psiphonHttpsClient.Do(request)
  554. if err == nil && response.StatusCode != http.StatusOK {
  555. response.Body.Close()
  556. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  557. }
  558. if err != nil {
  559. // Trim this error since it may include long URLs
  560. return nil, common.ContextError(TrimError(err))
  561. }
  562. defer response.Body.Close()
  563. body, err := ioutil.ReadAll(response.Body)
  564. if err != nil {
  565. return nil, common.ContextError(err)
  566. }
  567. return body, nil
  568. }
  569. // doPostRequest makes a tunneled HTTPS POST request.
  570. func (serverContext *ServerContext) doPostRequest(
  571. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  572. request, err := http.NewRequest("POST", requestUrl, body)
  573. if err != nil {
  574. return nil, common.ContextError(err)
  575. }
  576. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  577. request.Header.Set("Content-Type", bodyType)
  578. response, err := serverContext.psiphonHttpsClient.Do(request)
  579. if err == nil && response.StatusCode != http.StatusOK {
  580. response.Body.Close()
  581. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  582. }
  583. if err != nil {
  584. // Trim this error since it may include long URLs
  585. return nil, common.ContextError(TrimError(err))
  586. }
  587. defer response.Body.Close()
  588. responseBody, err = ioutil.ReadAll(response.Body)
  589. if err != nil {
  590. return nil, common.ContextError(err)
  591. }
  592. return responseBody, nil
  593. }
  594. type requestJSONObject map[string]interface{}
  595. // getBaseParams returns all the common API parameters that are included
  596. // with each Psiphon API request. These common parameters are used for
  597. // statistics.
  598. func (serverContext *ServerContext) getBaseParams() requestJSONObject {
  599. params := make(requestJSONObject)
  600. tunnel := serverContext.tunnel
  601. params["session_id"] = serverContext.sessionId
  602. params["client_session_id"] = serverContext.sessionId
  603. params["server_secret"] = tunnel.serverEntry.WebServerSecret
  604. params["propagation_channel_id"] = tunnel.config.PropagationChannelId
  605. params["sponsor_id"] = tunnel.config.SponsorId
  606. params["client_version"] = tunnel.config.ClientVersion
  607. // TODO: client_tunnel_core_version?
  608. params["relay_protocol"] = tunnel.protocol
  609. params["client_platform"] = tunnel.config.ClientPlatform
  610. params["client_build_rev"] = common.GetBuildInfo().BuildRev
  611. params["tunnel_whole_device"] = strconv.Itoa(tunnel.config.TunnelWholeDevice)
  612. // The following parameters may be blank and must
  613. // not be sent to the server if blank.
  614. if tunnel.config.DeviceRegion != "" {
  615. params["device_region"] = tunnel.config.DeviceRegion
  616. }
  617. if tunnel.dialStats.SelectedSSHClientVersion {
  618. params["ssh_client_version"] = tunnel.dialStats.SSHClientVersion
  619. }
  620. if tunnel.dialStats.UpstreamProxyType != "" {
  621. params["upstream_proxy_type"] = tunnel.dialStats.UpstreamProxyType
  622. }
  623. if tunnel.dialStats.UpstreamProxyCustomHeaderNames != nil {
  624. params["upstream_proxy_custom_header_names"] = tunnel.dialStats.UpstreamProxyCustomHeaderNames
  625. }
  626. if tunnel.dialStats.MeekDialAddress != "" {
  627. params["meek_dial_address"] = tunnel.dialStats.MeekDialAddress
  628. }
  629. if tunnel.dialStats.MeekResolvedIPAddress != "" {
  630. params["meek_resolved_ip_address"] = tunnel.dialStats.MeekResolvedIPAddress
  631. }
  632. if tunnel.dialStats.MeekSNIServerName != "" {
  633. params["meek_sni_server_name"] = tunnel.dialStats.MeekSNIServerName
  634. }
  635. if tunnel.dialStats.MeekHostHeader != "" {
  636. params["meek_host_header"] = tunnel.dialStats.MeekHostHeader
  637. }
  638. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  639. if tunnel.dialStats.MeekDialAddress != "" {
  640. transformedHostName := "0"
  641. if tunnel.dialStats.MeekTransformedHostName {
  642. transformedHostName = "1"
  643. }
  644. params["meek_transformed_host_name"] = transformedHostName
  645. }
  646. if tunnel.dialStats.SelectedUserAgent {
  647. params["user_agent"] = tunnel.dialStats.UserAgent
  648. }
  649. if tunnel.dialStats.SelectedTLSProfile {
  650. params["tls_profile"] = tunnel.dialStats.TLSProfile
  651. }
  652. if tunnel.serverEntry.Region != "" {
  653. params["server_entry_region"] = tunnel.serverEntry.Region
  654. }
  655. if tunnel.serverEntry.LocalSource != "" {
  656. params["server_entry_source"] = tunnel.serverEntry.LocalSource
  657. }
  658. // As with last_connected, this timestamp stat, which may be
  659. // a precise handshake request server timestamp, is truncated
  660. // to hour granularity to avoid introducing a reconstructable
  661. // cross-session user trace into server logs.
  662. localServerEntryTimestamp := common.TruncateTimestampToHour(tunnel.serverEntry.LocalTimestamp)
  663. if localServerEntryTimestamp != "" {
  664. params["server_entry_timestamp"] = localServerEntryTimestamp
  665. }
  666. return params
  667. }
  668. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  669. func makeSSHAPIRequestPayload(params requestJSONObject) ([]byte, error) {
  670. jsonPayload, err := json.Marshal(params)
  671. if err != nil {
  672. return nil, common.ContextError(err)
  673. }
  674. return jsonPayload, nil
  675. }
  676. // makeRequestUrl makes a URL for a web service API request.
  677. func makeRequestUrl(tunnel *Tunnel, port, path string, params requestJSONObject) string {
  678. var requestUrl bytes.Buffer
  679. if port == "" {
  680. port = tunnel.serverEntry.WebServerPort
  681. }
  682. requestUrl.WriteString("https://")
  683. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  684. requestUrl.WriteString(":")
  685. requestUrl.WriteString(port)
  686. requestUrl.WriteString("/")
  687. requestUrl.WriteString(path)
  688. if len(params) > 0 {
  689. queryParams := url.Values{}
  690. for name, value := range params {
  691. strValue := ""
  692. switch v := value.(type) {
  693. case string:
  694. strValue = v
  695. case []string:
  696. // String array param encoded as JSON
  697. jsonValue, err := json.Marshal(v)
  698. if err != nil {
  699. break
  700. }
  701. strValue = string(jsonValue)
  702. }
  703. queryParams.Set(name, strValue)
  704. }
  705. requestUrl.WriteString("?")
  706. requestUrl.WriteString(queryParams.Encode())
  707. }
  708. return requestUrl.String()
  709. }
  710. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  711. // requests and which validates the web server using the Psiphon server entry web server
  712. // certificate.
  713. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  714. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  715. if err != nil {
  716. return nil, common.ContextError(err)
  717. }
  718. tunneledDialer := func(_ context.Context, _, addr string) (conn net.Conn, err error) {
  719. return tunnel.sshClient.Dial("tcp", addr)
  720. }
  721. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  722. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  723. // the request. While it's possible to add a timeout here, we leave it with no explicit
  724. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  725. // alives will cause the tunnel to close.
  726. dialer := NewCustomTLSDialer(
  727. &CustomTLSConfig{
  728. Dial: tunneledDialer,
  729. VerifyLegacyCertificate: certificate,
  730. })
  731. transport := &http.Transport{
  732. DialTLS: func(network, addr string) (net.Conn, error) {
  733. return dialer(context.Background(), network, addr)
  734. },
  735. Dial: func(network, addr string) (net.Conn, error) {
  736. return nil, errors.New("HTTP not supported")
  737. },
  738. }
  739. return &http.Client{
  740. Transport: transport,
  741. }, nil
  742. }
  743. func HandleServerRequest(
  744. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  745. switch name {
  746. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  747. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  748. }
  749. return common.ContextError(fmt.Errorf("invalid request name: %s", name))
  750. }
  751. func HandleOSLRequest(
  752. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  753. var oslRequest protocol.OSLRequest
  754. err := json.Unmarshal(payload, &oslRequest)
  755. if err != nil {
  756. return common.ContextError(err)
  757. }
  758. if oslRequest.ClearLocalSLOKs {
  759. DeleteSLOKs()
  760. }
  761. seededNewSLOK := false
  762. for _, slok := range oslRequest.SeedPayload.SLOKs {
  763. duplicate, err := SetSLOK(slok.ID, slok.Key)
  764. if err != nil {
  765. // TODO: return error to trigger retry?
  766. NoticeAlert("SetSLOK failed: %s", common.ContextError(err))
  767. } else if !duplicate {
  768. seededNewSLOK = true
  769. }
  770. if tunnel.config.EmitSLOKs {
  771. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  772. }
  773. }
  774. if seededNewSLOK {
  775. tunnelOwner.SignalSeededNewSLOK()
  776. }
  777. return nil
  778. }