api.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "crypto/subtle"
  22. "encoding/base64"
  23. "encoding/json"
  24. std_errors "errors"
  25. "net"
  26. "regexp"
  27. "runtime/debug"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  37. )
  38. const (
  39. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  40. PADDING_MAX_BYTES = 16 * 1024
  41. CLIENT_PLATFORM_ANDROID = "Android"
  42. CLIENT_PLATFORM_WINDOWS = "Windows"
  43. CLIENT_PLATFORM_IOS = "iOS"
  44. )
  45. // sshAPIRequestHandler routes Psiphon API requests transported as
  46. // JSON objects via the SSH request mechanism.
  47. //
  48. // The API request handlers, handshakeAPIRequestHandler, etc., are
  49. // reused by webServer which offers the Psiphon API via web transport.
  50. //
  51. // The API request parameters and event log values follow the legacy
  52. // psi_web protocol and naming conventions. The API is compatible with
  53. // all tunnel-core clients but are not backwards compatible with all
  54. // legacy clients.
  55. //
  56. func sshAPIRequestHandler(
  57. support *SupportServices,
  58. geoIPData GeoIPData,
  59. authorizedAccessTypes []string,
  60. name string,
  61. requestPayload []byte) ([]byte, error) {
  62. // Notes:
  63. //
  64. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  65. // by max SSH request packet size.
  66. //
  67. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  68. // array of base64-encoded strings; the base64 representation should
  69. // not be decoded to []byte values. The default behavior of
  70. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  71. // type map[string]interface{} will unmarshal a base64-encoded string
  72. // to a string, not a decoded []byte, as required.
  73. var params common.APIParameters
  74. err := json.Unmarshal(requestPayload, &params)
  75. if err != nil {
  76. return nil, errors.Tracef(
  77. "invalid payload for request name: %s: %s", name, err)
  78. }
  79. return dispatchAPIRequestHandler(
  80. support,
  81. protocol.PSIPHON_SSH_API_PROTOCOL,
  82. geoIPData,
  83. authorizedAccessTypes,
  84. name,
  85. params)
  86. }
  87. // dispatchAPIRequestHandler is the common dispatch point for both
  88. // web and SSH API requests.
  89. func dispatchAPIRequestHandler(
  90. support *SupportServices,
  91. apiProtocol string,
  92. geoIPData GeoIPData,
  93. authorizedAccessTypes []string,
  94. name string,
  95. params common.APIParameters) (response []byte, reterr error) {
  96. // Recover from and log any unexpected panics caused by user input
  97. // handling bugs. User inputs should be properly validated; this
  98. // mechanism is only a last resort to prevent the process from
  99. // terminating in the case of a bug.
  100. defer func() {
  101. if e := recover(); e != nil {
  102. if intentionalPanic, ok := e.(IntentionalPanicError); ok {
  103. panic(intentionalPanic)
  104. } else {
  105. log.LogPanicRecover(e, debug.Stack())
  106. reterr = errors.TraceNew("request handler panic")
  107. }
  108. }
  109. }()
  110. // Before invoking the handlers, enforce some preconditions:
  111. //
  112. // - A handshake request must precede any other requests.
  113. // - When the handshake results in a traffic rules state where
  114. // the client is immediately exhausted, no requests
  115. // may succeed. This case ensures that blocked clients do
  116. // not log "connected", etc.
  117. //
  118. // Only one handshake request may be made. There is no check here
  119. // to enforce that handshakeAPIRequestHandler will be called at
  120. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  121. // enforces that only a single handshake is made; enforcing that there
  122. // ensures no race condition even if concurrent requests are
  123. // in flight.
  124. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  125. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  126. // applies here.
  127. sessionID, err := getStringRequestParam(params, "client_session_id")
  128. if err == nil {
  129. // Note: follows/duplicates baseParams validation
  130. if !isHexDigits(support.Config, sessionID) {
  131. err = std_errors.New("invalid param: client_session_id")
  132. }
  133. }
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. completed, exhausted, err := support.TunnelServer.GetClientHandshaked(sessionID)
  138. if err != nil {
  139. return nil, errors.Trace(err)
  140. }
  141. if !completed {
  142. return nil, errors.TraceNew("handshake not completed")
  143. }
  144. if exhausted {
  145. return nil, errors.TraceNew("exhausted after handshake")
  146. }
  147. }
  148. switch name {
  149. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  150. return handshakeAPIRequestHandler(support, apiProtocol, geoIPData, params)
  151. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  152. return connectedAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  153. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  154. return statusAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  155. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  156. return clientVerificationAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  157. }
  158. return nil, errors.Tracef("invalid request name: %s", name)
  159. }
  160. var handshakeRequestParams = append(
  161. append(
  162. append(
  163. []requestParamSpec{
  164. // Legacy clients may not send "session_id" in handshake
  165. {"session_id", isHexDigits, requestParamOptional},
  166. {"missing_server_entry_signature", isBase64String, requestParamOptional}},
  167. baseParams...),
  168. baseDialParams...),
  169. tacticsParams...)
  170. // handshakeAPIRequestHandler implements the "handshake" API request.
  171. // Clients make the handshake immediately after establishing a tunnel
  172. // connection; the response tells the client what homepage to open, what
  173. // stats to record, etc.
  174. func handshakeAPIRequestHandler(
  175. support *SupportServices,
  176. apiProtocol string,
  177. geoIPData GeoIPData,
  178. params common.APIParameters) ([]byte, error) {
  179. // Note: ignoring legacy "known_servers" params
  180. err := validateRequestParams(support.Config, params, handshakeRequestParams)
  181. if err != nil {
  182. return nil, errors.Trace(err)
  183. }
  184. sessionID, _ := getStringRequestParam(params, "client_session_id")
  185. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  186. clientVersion, _ := getStringRequestParam(params, "client_version")
  187. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  188. isMobile := isMobileClientPlatform(clientPlatform)
  189. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  190. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  191. // the client, a value of 0 will be used.
  192. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  193. // splitTunnel indicates if the client is using split tunnel mode. When
  194. // omitted by the client, the value will be false.
  195. splitTunnel, _ := getBoolStringRequestParam(params, "split_tunnel")
  196. var authorizations []string
  197. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  198. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  199. if err != nil {
  200. return nil, errors.Trace(err)
  201. }
  202. }
  203. // Note: no guarantee that PsinetDatabase won't reload between database calls
  204. db := support.PsinetDatabase
  205. httpsRequestRegexes := db.GetHttpsRequestRegexes(sponsorID)
  206. // Flag the SSH client as having completed its handshake. This
  207. // may reselect traffic rules and starts allowing port forwards.
  208. // TODO: in the case of SSH API requests, the actual sshClient could
  209. // be passed in and used here. The session ID lookup is only strictly
  210. // necessary to support web API requests.
  211. handshakeStateInfo, err := support.TunnelServer.SetClientHandshakeState(
  212. sessionID,
  213. handshakeState{
  214. completed: true,
  215. apiProtocol: apiProtocol,
  216. apiParams: copyBaseSessionAndDialParams(params),
  217. expectDomainBytes: len(httpsRequestRegexes) > 0,
  218. establishedTunnelsCount: establishedTunnelsCount,
  219. splitTunnel: splitTunnel,
  220. },
  221. authorizations)
  222. if err != nil {
  223. return nil, errors.Trace(err)
  224. }
  225. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  226. common.GeoIPData(geoIPData), params)
  227. if err != nil {
  228. return nil, errors.Trace(err)
  229. }
  230. var marshaledTacticsPayload []byte
  231. if tacticsPayload != nil {
  232. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  233. if err != nil {
  234. return nil, errors.Trace(err)
  235. }
  236. // Log a metric when new tactics are issued. Logging here indicates that
  237. // the handshake tactics mechanism is active; but logging for every
  238. // handshake creates unneccesary log data.
  239. if len(tacticsPayload.Tactics) > 0 {
  240. logFields := getRequestLogFields(
  241. tactics.TACTICS_METRIC_EVENT_NAME,
  242. geoIPData,
  243. handshakeStateInfo.authorizedAccessTypes,
  244. params,
  245. handshakeRequestParams)
  246. logFields[tactics.NEW_TACTICS_TAG_LOG_FIELD_NAME] = tacticsPayload.Tag
  247. logFields[tactics.IS_TACTICS_REQUEST_LOG_FIELD_NAME] = false
  248. log.LogRawFieldsWithTimestamp(logFields)
  249. }
  250. }
  251. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  252. // the state change (for example, if a second handshake is performed)
  253. //
  254. // The handshake event is no longer shipped to log consumers, so this is
  255. // simply a diagnostic log. Since the "server_tunnel" event includes all
  256. // common API parameters and "handshake_completed" flag, this handshake
  257. // log is mostly redundant and set to debug level.
  258. log.WithTraceFields(
  259. getRequestLogFields(
  260. "",
  261. geoIPData,
  262. handshakeStateInfo.authorizedAccessTypes,
  263. params,
  264. handshakeRequestParams)).Debug("handshake")
  265. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  266. if !geoIPData.HasDiscoveryValue {
  267. return nil, errors.TraceNew("unexpected missing discovery value")
  268. }
  269. encodedServerList := db.DiscoverServers(geoIPData.DiscoveryValue)
  270. // When the client indicates that it used an unsigned server entry for this
  271. // connection, return a signed copy of the server entry for the client to
  272. // upgrade to. See also: comment in psiphon.doHandshakeRequest.
  273. //
  274. // The missing_server_entry_signature parameter value is a server entry tag,
  275. // which is used to select the correct server entry for servers with multiple
  276. // entries. Identifying the server entries tags instead of server IPs prevents
  277. // an enumeration attack, where a malicious client can abuse this facilty to
  278. // check if an arbitrary IP address is a Psiphon server.
  279. serverEntryTag, ok := getOptionalStringRequestParam(
  280. params, "missing_server_entry_signature")
  281. if ok {
  282. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  283. if ok {
  284. encodedServerList = append(encodedServerList, ownServerEntry)
  285. }
  286. }
  287. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  288. // the JSON response, return an empty array instead of null for legacy
  289. // clients.
  290. handshakeResponse := protocol.HandshakeResponse{
  291. SSHSessionID: sessionID,
  292. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, geoIPData.ASN, isMobile),
  293. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  294. PageViewRegexes: make([]map[string]string, 0),
  295. HttpsRequestRegexes: httpsRequestRegexes,
  296. EncodedServerList: encodedServerList,
  297. ClientRegion: geoIPData.Country,
  298. ServerTimestamp: common.GetCurrentTimestamp(),
  299. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  300. TacticsPayload: marshaledTacticsPayload,
  301. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  302. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  303. Padding: strings.Repeat(" ", pad_response),
  304. }
  305. responsePayload, err := json.Marshal(handshakeResponse)
  306. if err != nil {
  307. return nil, errors.Trace(err)
  308. }
  309. return responsePayload, nil
  310. }
  311. // uniqueUserParams are the connected request parameters which are logged for
  312. // unique_user events.
  313. var uniqueUserParams = append(
  314. []requestParamSpec{
  315. {"last_connected", isLastConnected, 0}},
  316. baseSessionParams...)
  317. var connectedRequestParams = append(
  318. []requestParamSpec{
  319. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  320. uniqueUserParams...)
  321. // updateOnConnectedParamNames are connected request parameters which are
  322. // copied to update data logged with server_tunnel: these fields either only
  323. // ship with or ship newer data with connected requests.
  324. var updateOnConnectedParamNames = append(
  325. []string{
  326. "last_connected",
  327. "establishment_duration",
  328. },
  329. fragmentor.GetUpstreamMetricsNames()...)
  330. // connectedAPIRequestHandler implements the "connected" API request. Clients
  331. // make the connected request once a tunnel connection has been established
  332. // and at least once per 24h for long-running tunnels. The last_connected
  333. // input value, which should be a connected_timestamp output from a previous
  334. // connected response, is used to calculate unique user stats.
  335. // connected_timestamp is truncated as a privacy measure.
  336. func connectedAPIRequestHandler(
  337. support *SupportServices,
  338. geoIPData GeoIPData,
  339. authorizedAccessTypes []string,
  340. params common.APIParameters) ([]byte, error) {
  341. err := validateRequestParams(support.Config, params, connectedRequestParams)
  342. if err != nil {
  343. return nil, errors.Trace(err)
  344. }
  345. sessionID, _ := getStringRequestParam(params, "client_session_id")
  346. lastConnected, _ := getStringRequestParam(params, "last_connected")
  347. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  348. // client may have performed more upstream fragmentation since the previous
  349. // metrics reported by the handshake request. Also, additional fields that
  350. // are reported only in the connected request are added to server_tunnel
  351. // here.
  352. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  353. // applies here.
  354. err = support.TunnelServer.UpdateClientAPIParameters(
  355. sessionID, copyUpdateOnConnectedParams(params))
  356. if err != nil {
  357. return nil, errors.Trace(err)
  358. }
  359. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  360. // The finest required granularity for unique users is daily. To save space,
  361. // only record a "unique_user" log event when the client's last_connected is
  362. // in the previous day relative to the new connected_timestamp.
  363. logUniqueUser := false
  364. if lastConnected == "None" {
  365. logUniqueUser = true
  366. } else {
  367. t1, _ := time.Parse(time.RFC3339, lastConnected)
  368. year, month, day := t1.Date()
  369. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  370. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  371. year, month, day = t2.Date()
  372. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  373. if t1.Before(t2) && d1 != d2 {
  374. logUniqueUser = true
  375. }
  376. }
  377. if logUniqueUser {
  378. log.LogRawFieldsWithTimestamp(
  379. getRequestLogFields(
  380. "unique_user",
  381. geoIPData,
  382. authorizedAccessTypes,
  383. params,
  384. uniqueUserParams))
  385. }
  386. // TODO: retire the legacy "connected" log event
  387. log.LogRawFieldsWithTimestamp(
  388. getRequestLogFields(
  389. "connected",
  390. geoIPData,
  391. authorizedAccessTypes,
  392. params,
  393. connectedRequestParams))
  394. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  395. connectedResponse := protocol.ConnectedResponse{
  396. ConnectedTimestamp: connectedTimestamp,
  397. Padding: strings.Repeat(" ", pad_response),
  398. }
  399. responsePayload, err := json.Marshal(connectedResponse)
  400. if err != nil {
  401. return nil, errors.Trace(err)
  402. }
  403. return responsePayload, nil
  404. }
  405. var statusRequestParams = baseSessionParams
  406. var remoteServerListStatParams = append(
  407. []requestParamSpec{
  408. {"client_download_timestamp", isISO8601Date, 0},
  409. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  410. {"url", isAnyString, 0},
  411. {"etag", isAnyString, 0},
  412. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  413. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  414. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool}},
  415. baseSessionParams...)
  416. // Backwards compatibility case: legacy clients do not include these fields in
  417. // the remote_server_list_stats entries. Use the values from the outer status
  418. // request as an approximation (these values reflect the client at persistent
  419. // stat shipping time, which may differ from the client at persistent stat
  420. // recording time). Note that all but client_build_rev and device_region are
  421. // required fields.
  422. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  423. "session_id",
  424. "propagation_channel_id",
  425. "sponsor_id",
  426. "client_version",
  427. "client_platform",
  428. "client_build_rev",
  429. "device_region",
  430. }
  431. var failedTunnelStatParams = append(
  432. []requestParamSpec{
  433. {"server_entry_tag", isAnyString, requestParamOptional},
  434. {"session_id", isHexDigits, 0},
  435. {"last_connected", isLastConnected, 0},
  436. {"client_failed_timestamp", isISO8601Date, 0},
  437. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  438. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  439. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  440. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  441. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  442. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  443. {"tunnel_error", isAnyString, 0}},
  444. baseSessionAndDialParams...)
  445. // statusAPIRequestHandler implements the "status" API request.
  446. // Clients make periodic status requests which deliver client-side
  447. // recorded data transfer and tunnel duration stats.
  448. // Note from psi_web implementation: no input validation on domains;
  449. // any string is accepted (regex transform may result in arbitrary
  450. // string). Stats processor must handle this input with care.
  451. func statusAPIRequestHandler(
  452. support *SupportServices,
  453. geoIPData GeoIPData,
  454. authorizedAccessTypes []string,
  455. params common.APIParameters) ([]byte, error) {
  456. err := validateRequestParams(support.Config, params, statusRequestParams)
  457. if err != nil {
  458. return nil, errors.Trace(err)
  459. }
  460. sessionID, _ := getStringRequestParam(params, "client_session_id")
  461. statusData, err := getJSONObjectRequestParam(params, "statusData")
  462. if err != nil {
  463. return nil, errors.Trace(err)
  464. }
  465. // Logs are queued until the input is fully validated. Otherwise, stats
  466. // could be double counted if the client has a bug in its request
  467. // formatting: partial stats would be logged (counted), the request would
  468. // fail, and clients would then resend all the same stats again.
  469. logQueue := make([]LogFields, 0)
  470. // Domain bytes transferred stats
  471. // Older clients may not submit this data
  472. // Clients are expected to send host_bytes/domain_bytes stats only when
  473. // configured to do so in the handshake reponse. Legacy clients may still
  474. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  475. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  476. if err != nil {
  477. return nil, errors.Trace(err)
  478. }
  479. if domainBytesExpected && statusData["host_bytes"] != nil {
  480. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  481. if err != nil {
  482. return nil, errors.Trace(err)
  483. }
  484. for domain, bytes := range hostBytes {
  485. domainBytesFields := getRequestLogFields(
  486. "domain_bytes",
  487. geoIPData,
  488. authorizedAccessTypes,
  489. params,
  490. statusRequestParams)
  491. domainBytesFields["domain"] = domain
  492. domainBytesFields["bytes"] = bytes
  493. logQueue = append(logQueue, domainBytesFields)
  494. }
  495. }
  496. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  497. // not time-of-recording.
  498. // Remote server list download persistent stats.
  499. // Older clients may not submit this data.
  500. if statusData["remote_server_list_stats"] != nil {
  501. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  502. if err != nil {
  503. return nil, errors.Trace(err)
  504. }
  505. for _, remoteServerListStat := range remoteServerListStats {
  506. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  507. if _, ok := remoteServerListStat[name]; !ok {
  508. if field, ok := params[name]; ok {
  509. remoteServerListStat[name] = field
  510. }
  511. }
  512. }
  513. // For validation, copy expected fields from the outer
  514. // statusRequestParams.
  515. remoteServerListStat["server_secret"] = params["server_secret"]
  516. remoteServerListStat["client_session_id"] = params["client_session_id"]
  517. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  518. if err != nil {
  519. // Occasionally, clients may send corrupt persistent stat data. Do not
  520. // fail the status request, as this will lead to endless retries.
  521. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  522. continue
  523. }
  524. remoteServerListFields := getRequestLogFields(
  525. "remote_server_list",
  526. geoIPData,
  527. authorizedAccessTypes,
  528. remoteServerListStat,
  529. remoteServerListStatParams)
  530. logQueue = append(logQueue, remoteServerListFields)
  531. }
  532. }
  533. // Failed tunnel persistent stats.
  534. // Older clients may not submit this data.
  535. var invalidServerEntryTags map[string]bool
  536. if statusData["failed_tunnel_stats"] != nil {
  537. // Note: no guarantee that PsinetDatabase won't reload between database calls
  538. db := support.PsinetDatabase
  539. invalidServerEntryTags = make(map[string]bool)
  540. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  541. if err != nil {
  542. return nil, errors.Trace(err)
  543. }
  544. for _, failedTunnelStat := range failedTunnelStats {
  545. // failed_tunnel supplies a full set of base params, but the server secret
  546. // must use the correct value from the outer statusRequestParams.
  547. failedTunnelStat["server_secret"] = params["server_secret"]
  548. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  549. if err != nil {
  550. // Occasionally, clients may send corrupt persistent stat data. Do not
  551. // fail the status request, as this will lead to endless retries.
  552. //
  553. // TODO: trigger pruning if the data corruption indicates corrupt server
  554. // entry storage?
  555. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  556. continue
  557. }
  558. failedTunnelFields := getRequestLogFields(
  559. "failed_tunnel",
  560. geoIPData,
  561. authorizedAccessTypes,
  562. failedTunnelStat,
  563. failedTunnelStatParams)
  564. // Return a list of servers, identified by server entry tag, that are
  565. // invalid and presumed to be deleted. This information is used by clients
  566. // to prune deleted servers from their local datastores and stop attempting
  567. // connections to servers that no longer exist.
  568. //
  569. // This mechanism uses tags instead of server IPs: (a) to prevent an
  570. // enumeration attack, where a malicious client can query the entire IPv4
  571. // range and build a map of the Psiphon network; (b) to deal with recyling
  572. // cases where a server deleted and its IP is reused for a new server with
  573. // a distinct server entry.
  574. //
  575. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  576. // before returning a negative result, to mitigate accidental pruning.
  577. //
  578. // In addition, when the reported dial port number is 0, flag the server
  579. // entry as invalid to trigger client pruning. This covers a class of
  580. // invalid/semi-functional server entries, found in practice to be stored
  581. // by clients, where some protocol port number has been omitted -- due to
  582. // historical bugs in various server entry handling implementations. When
  583. // missing from a server entry loaded by a client, the port number
  584. // evaluates to 0, the zero value, which is not a valid port number even if
  585. // were not missing.
  586. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  587. if ok {
  588. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  589. if serverEntryValid {
  590. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  591. if err == nil && dialPortNumber == 0 {
  592. serverEntryValid = false
  593. }
  594. }
  595. if !serverEntryValid {
  596. invalidServerEntryTags[serverEntryTag] = true
  597. }
  598. // Add a field to the failed_tunnel log indicating if the server entry is
  599. // valid.
  600. failedTunnelFields["server_entry_valid"] = serverEntryValid
  601. }
  602. // Log failed_tunnel.
  603. logQueue = append(logQueue, failedTunnelFields)
  604. }
  605. }
  606. for _, logItem := range logQueue {
  607. log.LogRawFieldsWithTimestamp(logItem)
  608. }
  609. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  610. statusResponse := protocol.StatusResponse{
  611. Padding: strings.Repeat(" ", pad_response),
  612. }
  613. if len(invalidServerEntryTags) > 0 {
  614. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  615. i := 0
  616. for tag := range invalidServerEntryTags {
  617. statusResponse.InvalidServerEntryTags[i] = tag
  618. i++
  619. }
  620. }
  621. responsePayload, err := json.Marshal(statusResponse)
  622. if err != nil {
  623. return nil, errors.Trace(err)
  624. }
  625. return responsePayload, nil
  626. }
  627. // clientVerificationAPIRequestHandler is just a compliance stub
  628. // for older Android clients that still send verification requests
  629. func clientVerificationAPIRequestHandler(
  630. support *SupportServices,
  631. geoIPData GeoIPData,
  632. authorizedAccessTypes []string,
  633. params common.APIParameters) ([]byte, error) {
  634. return make([]byte, 0), nil
  635. }
  636. var tacticsParams = []requestParamSpec{
  637. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  638. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  639. }
  640. var tacticsRequestParams = append(
  641. append([]requestParamSpec(nil), tacticsParams...),
  642. baseSessionAndDialParams...)
  643. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  644. return func(params common.APIParameters) error {
  645. return validateRequestParams(config, params, tacticsRequestParams)
  646. }
  647. }
  648. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  649. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  650. logFields := getRequestLogFields(
  651. tactics.TACTICS_METRIC_EVENT_NAME,
  652. GeoIPData(geoIPData),
  653. nil, // authorizedAccessTypes are not known yet
  654. params,
  655. tacticsRequestParams)
  656. return common.LogFields(logFields)
  657. }
  658. }
  659. // requestParamSpec defines a request parameter. Each param is expected to be
  660. // a string, unless requestParamArray is specified, in which case an array of
  661. // strings is expected.
  662. type requestParamSpec struct {
  663. name string
  664. validator func(*Config, string) bool
  665. flags uint32
  666. }
  667. const (
  668. requestParamOptional = 1
  669. requestParamNotLogged = 1 << 1
  670. requestParamArray = 1 << 2
  671. requestParamJSON = 1 << 3
  672. requestParamLogStringAsInt = 1 << 4
  673. requestParamLogStringAsFloat = 1 << 5
  674. requestParamLogStringLengthAsInt = 1 << 6
  675. requestParamLogFlagAsBool = 1 << 7
  676. requestParamLogOnlyForFrontedMeek = 1 << 8
  677. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  678. )
  679. // baseParams are the basic request parameters that are expected for all API
  680. // requests and log events.
  681. var baseParams = []requestParamSpec{
  682. {"server_secret", isServerSecret, requestParamNotLogged},
  683. {"client_session_id", isHexDigits, requestParamNotLogged},
  684. {"propagation_channel_id", isHexDigits, 0},
  685. {"sponsor_id", isHexDigits, 0},
  686. {"client_version", isIntString, requestParamLogStringAsInt},
  687. {"client_platform", isClientPlatform, 0},
  688. {"client_build_rev", isHexDigits, requestParamOptional},
  689. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  690. {"device_region", isAnyString, requestParamOptional},
  691. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  692. }
  693. // baseSessionParams adds to baseParams the required session_id parameter. For
  694. // all requests except handshake, all existing clients are expected to send
  695. // session_id. Legacy clients may not send "session_id" in handshake.
  696. var baseSessionParams = append(
  697. []requestParamSpec{
  698. {"session_id", isHexDigits, 0}},
  699. baseParams...)
  700. // baseDialParams are the dial parameters, per-tunnel network protocol and
  701. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  702. // tactics.
  703. var baseDialParams = []requestParamSpec{
  704. {"relay_protocol", isRelayProtocol, 0},
  705. {"ssh_client_version", isAnyString, requestParamOptional},
  706. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  707. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  708. {"fronting_provider_id", isAnyString, requestParamOptional},
  709. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  710. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  711. {"meek_sni_server_name", isDomain, requestParamOptional},
  712. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  713. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  714. {"user_agent", isAnyString, requestParamOptional},
  715. {"tls_profile", isAnyString, requestParamOptional},
  716. {"tls_version", isAnyString, requestParamOptional},
  717. {"server_entry_region", isRegionCode, requestParamOptional},
  718. {"server_entry_source", isServerEntrySource, requestParamOptional},
  719. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  720. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  721. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  722. {"quic_version", isAnyString, requestParamOptional},
  723. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  724. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  725. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  726. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  727. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  728. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  729. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  730. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  731. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  732. {"egress_region", isRegionCode, requestParamOptional},
  733. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  734. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  735. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  736. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  737. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  738. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  739. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  740. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  741. {"client_bpf", isAnyString, requestParamOptional},
  742. {"network_type", isAnyString, requestParamOptional},
  743. {"conjure_transport", isAnyString, requestParamOptional},
  744. }
  745. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  746. var baseSessionAndDialParams = append(
  747. append(
  748. []requestParamSpec{},
  749. baseSessionParams...),
  750. baseDialParams...)
  751. func validateRequestParams(
  752. config *Config,
  753. params common.APIParameters,
  754. expectedParams []requestParamSpec) error {
  755. for _, expectedParam := range expectedParams {
  756. value := params[expectedParam.name]
  757. if value == nil {
  758. if expectedParam.flags&requestParamOptional != 0 {
  759. continue
  760. }
  761. return errors.Tracef("missing param: %s", expectedParam.name)
  762. }
  763. var err error
  764. switch {
  765. case expectedParam.flags&requestParamArray != 0:
  766. err = validateStringArrayRequestParam(config, expectedParam, value)
  767. case expectedParam.flags&requestParamJSON != 0:
  768. // No validation: the JSON already unmarshalled; the parameter
  769. // user will validate that the JSON contains the expected
  770. // objects/data.
  771. // TODO: without validation, any valid JSON will be logged
  772. // by getRequestLogFields, even if the parameter user validates
  773. // and rejects the parameter.
  774. default:
  775. err = validateStringRequestParam(config, expectedParam, value)
  776. }
  777. if err != nil {
  778. return errors.Trace(err)
  779. }
  780. }
  781. return nil
  782. }
  783. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  784. // the baseSessionAndDialParams.
  785. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  786. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  787. // scalar types (int, string, etc.)
  788. paramsCopy := make(common.APIParameters)
  789. for _, baseParam := range baseSessionAndDialParams {
  790. value := params[baseParam.name]
  791. if value == nil {
  792. continue
  793. }
  794. paramsCopy[baseParam.name] = value
  795. }
  796. return paramsCopy
  797. }
  798. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  799. // Note: not a deep copy
  800. paramsCopy := make(common.APIParameters)
  801. for _, name := range updateOnConnectedParamNames {
  802. value := params[name]
  803. if value == nil {
  804. continue
  805. }
  806. paramsCopy[name] = value
  807. }
  808. return paramsCopy
  809. }
  810. func validateStringRequestParam(
  811. config *Config,
  812. expectedParam requestParamSpec,
  813. value interface{}) error {
  814. strValue, ok := value.(string)
  815. if !ok {
  816. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  817. }
  818. if !expectedParam.validator(config, strValue) {
  819. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  820. }
  821. return nil
  822. }
  823. func validateStringArrayRequestParam(
  824. config *Config,
  825. expectedParam requestParamSpec,
  826. value interface{}) error {
  827. arrayValue, ok := value.([]interface{})
  828. if !ok {
  829. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  830. }
  831. for _, value := range arrayValue {
  832. err := validateStringRequestParam(config, expectedParam, value)
  833. if err != nil {
  834. return errors.Trace(err)
  835. }
  836. }
  837. return nil
  838. }
  839. // getRequestLogFields makes LogFields to log the API event following
  840. // the legacy psi_web and current ELK naming conventions.
  841. func getRequestLogFields(
  842. eventName string,
  843. geoIPData GeoIPData,
  844. authorizedAccessTypes []string,
  845. params common.APIParameters,
  846. expectedParams []requestParamSpec) LogFields {
  847. logFields := make(LogFields)
  848. if eventName != "" {
  849. logFields["event_name"] = eventName
  850. }
  851. geoIPData.SetLogFields(logFields)
  852. if len(authorizedAccessTypes) > 0 {
  853. logFields["authorized_access_types"] = authorizedAccessTypes
  854. }
  855. if params == nil {
  856. return logFields
  857. }
  858. for _, expectedParam := range expectedParams {
  859. if expectedParam.flags&requestParamNotLogged != 0 {
  860. continue
  861. }
  862. var tunnelProtocol string
  863. if value, ok := params["relay_protocol"]; ok {
  864. tunnelProtocol, _ = value.(string)
  865. }
  866. if expectedParam.flags&requestParamLogOnlyForFrontedMeek != 0 &&
  867. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  868. continue
  869. }
  870. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  871. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  872. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  873. // Non-HTTP unfronted meek protocols never tranform the host header.
  874. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  875. continue
  876. }
  877. var transformedHostName string
  878. if value, ok := params["meek_transformed_host_name"]; ok {
  879. transformedHostName, _ = value.(string)
  880. }
  881. if transformedHostName != "1" {
  882. continue
  883. }
  884. }
  885. value := params[expectedParam.name]
  886. if value == nil {
  887. // Special case: older clients don't send this value,
  888. // so log a default.
  889. if expectedParam.name == "tunnel_whole_device" {
  890. value = "0"
  891. } else {
  892. // Skip omitted, optional params
  893. continue
  894. }
  895. }
  896. switch v := value.(type) {
  897. case string:
  898. strValue := v
  899. // Special cases:
  900. // - Number fields are encoded as integer types.
  901. // - For ELK performance we record certain domain-or-IP
  902. // fields as one of two different values based on type;
  903. // we also omit port from these host:port fields for now.
  904. // - Boolean fields that come into the api as "1"/"0"
  905. // must be logged as actual boolean values
  906. switch expectedParam.name {
  907. case "meek_dial_address":
  908. host, _, _ := net.SplitHostPort(strValue)
  909. if isIPAddress(nil, host) {
  910. logFields["meek_dial_ip_address"] = host
  911. } else {
  912. logFields["meek_dial_domain"] = host
  913. }
  914. case "upstream_proxy_type":
  915. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  916. logFields[expectedParam.name] = strings.ToLower(strValue)
  917. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  918. // Due to a client bug, clients may deliever an incorrect ""
  919. // value for speed_test_samples via the web API protocol. Omit
  920. // the field in this case.
  921. case "tunnel_error":
  922. // net/url.Error, returned from net/url.Parse, contains the original input
  923. // URL, which may contain PII. New clients strip this out by using
  924. // common.SafeParseURL. Legacy clients will still send the full error
  925. // message, so strip it out here. The target substring should be unique to
  926. // legacy clients.
  927. target := "upstreamproxy error: proxyURI url.Parse: parse "
  928. index := strings.Index(strValue, target)
  929. if index != -1 {
  930. strValue = strValue[:index+len(target)] + "<redacted>"
  931. }
  932. logFields[expectedParam.name] = strValue
  933. default:
  934. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  935. intValue, _ := strconv.Atoi(strValue)
  936. logFields[expectedParam.name] = intValue
  937. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  938. floatValue, _ := strconv.ParseFloat(strValue, 64)
  939. logFields[expectedParam.name] = floatValue
  940. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  941. logFields[expectedParam.name] = len(strValue)
  942. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  943. // Submitted value could be "0" or "1"
  944. // "0" and non "0"/"1" values should be transformed to false
  945. // "1" should be transformed to true
  946. if strValue == "1" {
  947. logFields[expectedParam.name] = true
  948. } else {
  949. logFields[expectedParam.name] = false
  950. }
  951. } else {
  952. logFields[expectedParam.name] = strValue
  953. }
  954. }
  955. case []interface{}:
  956. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  957. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  958. } else {
  959. logFields[expectedParam.name] = v
  960. }
  961. default:
  962. logFields[expectedParam.name] = v
  963. }
  964. }
  965. return logFields
  966. }
  967. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  968. // fields to more verbose names for metrics.
  969. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  970. // TODO: use reflection and add additional tags, e.g.,
  971. // `json:"s" log:"timestamp"` to remove hard-coded
  972. // tag value dependency?
  973. logSamples := make([]interface{}, len(samples))
  974. for i, sample := range samples {
  975. logSample := make(map[string]interface{})
  976. if m, ok := sample.(map[string]interface{}); ok {
  977. for k, v := range m {
  978. logK := k
  979. switch k {
  980. case "s":
  981. logK = "timestamp"
  982. case "r":
  983. logK = "server_region"
  984. case "p":
  985. logK = "relay_protocol"
  986. case "t":
  987. logK = "round_trip_time_ms"
  988. case "u":
  989. logK = "bytes_up"
  990. case "d":
  991. logK = "bytes_down"
  992. }
  993. logSample[logK] = v
  994. }
  995. }
  996. logSamples[i] = logSample
  997. }
  998. return logSamples
  999. }
  1000. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  1001. if params[name] == nil {
  1002. return "", false
  1003. }
  1004. value, ok := params[name].(string)
  1005. if !ok {
  1006. return "", false
  1007. }
  1008. return value, true
  1009. }
  1010. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  1011. if params[name] == nil {
  1012. return "", errors.Tracef("missing param: %s", name)
  1013. }
  1014. value, ok := params[name].(string)
  1015. if !ok {
  1016. return "", errors.Tracef("invalid param: %s", name)
  1017. }
  1018. return value, nil
  1019. }
  1020. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1021. if params[name] == nil {
  1022. return 0, errors.Tracef("missing param: %s", name)
  1023. }
  1024. valueStr, ok := params[name].(string)
  1025. if !ok {
  1026. return 0, errors.Tracef("invalid param: %s", name)
  1027. }
  1028. value, err := strconv.Atoi(valueStr)
  1029. if !ok {
  1030. return 0, errors.Trace(err)
  1031. }
  1032. return value, nil
  1033. }
  1034. func getBoolStringRequestParam(params common.APIParameters, name string) (bool, error) {
  1035. if params[name] == nil {
  1036. return false, errors.Tracef("missing param: %s", name)
  1037. }
  1038. valueStr, ok := params[name].(string)
  1039. if !ok {
  1040. return false, errors.Tracef("invalid param: %s", name)
  1041. }
  1042. if valueStr == "1" {
  1043. return true, nil
  1044. }
  1045. return false, nil
  1046. }
  1047. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1048. value, err := getIntStringRequestParam(params, name)
  1049. if err != nil {
  1050. return 0, errors.Trace(err)
  1051. }
  1052. if value < 0 {
  1053. value = 0
  1054. }
  1055. if value > PADDING_MAX_BYTES {
  1056. value = PADDING_MAX_BYTES
  1057. }
  1058. return int(value), nil
  1059. }
  1060. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1061. if params[name] == nil {
  1062. return nil, errors.Tracef("missing param: %s", name)
  1063. }
  1064. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1065. value, ok := params[name].(map[string]interface{})
  1066. if !ok {
  1067. return nil, errors.Tracef("invalid param: %s", name)
  1068. }
  1069. return common.APIParameters(value), nil
  1070. }
  1071. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1072. if params[name] == nil {
  1073. return nil, errors.Tracef("missing param: %s", name)
  1074. }
  1075. value, ok := params[name].([]interface{})
  1076. if !ok {
  1077. return nil, errors.Tracef("invalid param: %s", name)
  1078. }
  1079. result := make([]common.APIParameters, len(value))
  1080. for i, item := range value {
  1081. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1082. resultItem, ok := item.(map[string]interface{})
  1083. if !ok {
  1084. return nil, errors.Tracef("invalid param: %s", name)
  1085. }
  1086. result[i] = common.APIParameters(resultItem)
  1087. }
  1088. return result, nil
  1089. }
  1090. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1091. if params[name] == nil {
  1092. return nil, errors.Tracef("missing param: %s", name)
  1093. }
  1094. // TODO: can't use common.APIParameters type?
  1095. value, ok := params[name].(map[string]interface{})
  1096. if !ok {
  1097. return nil, errors.Tracef("invalid param: %s", name)
  1098. }
  1099. result := make(map[string]int64)
  1100. for k, v := range value {
  1101. numValue, ok := v.(float64)
  1102. if !ok {
  1103. return nil, errors.Tracef("invalid param: %s", name)
  1104. }
  1105. result[k] = int64(numValue)
  1106. }
  1107. return result, nil
  1108. }
  1109. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1110. if params[name] == nil {
  1111. return nil, errors.Tracef("missing param: %s", name)
  1112. }
  1113. value, ok := params[name].([]interface{})
  1114. if !ok {
  1115. return nil, errors.Tracef("invalid param: %s", name)
  1116. }
  1117. result := make([]string, len(value))
  1118. for i, v := range value {
  1119. strValue, ok := v.(string)
  1120. if !ok {
  1121. return nil, errors.Tracef("invalid param: %s", name)
  1122. }
  1123. result[i] = strValue
  1124. }
  1125. return result, nil
  1126. }
  1127. // Normalize reported client platform. Android clients, for example, report
  1128. // OS version, rooted status, and Google Play build status in the clientPlatform
  1129. // string along with "Android".
  1130. func normalizeClientPlatform(clientPlatform string) string {
  1131. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1132. return CLIENT_PLATFORM_ANDROID
  1133. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1134. return CLIENT_PLATFORM_IOS
  1135. }
  1136. return CLIENT_PLATFORM_WINDOWS
  1137. }
  1138. func isAnyString(config *Config, value string) bool {
  1139. return true
  1140. }
  1141. func isMobileClientPlatform(clientPlatform string) bool {
  1142. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1143. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1144. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1145. }
  1146. // Input validators follow the legacy validations rules in psi_web.
  1147. func isServerSecret(config *Config, value string) bool {
  1148. return subtle.ConstantTimeCompare(
  1149. []byte(value),
  1150. []byte(config.WebServerSecret)) == 1
  1151. }
  1152. func isHexDigits(_ *Config, value string) bool {
  1153. // Allows both uppercase in addition to lowercase, for legacy support.
  1154. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1155. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1156. })
  1157. }
  1158. func isBase64String(_ *Config, value string) bool {
  1159. _, err := base64.StdEncoding.DecodeString(value)
  1160. return err == nil
  1161. }
  1162. func isDigits(_ *Config, value string) bool {
  1163. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1164. return c < '0' || c > '9'
  1165. })
  1166. }
  1167. func isIntString(_ *Config, value string) bool {
  1168. _, err := strconv.Atoi(value)
  1169. return err == nil
  1170. }
  1171. func isFloatString(_ *Config, value string) bool {
  1172. _, err := strconv.ParseFloat(value, 64)
  1173. return err == nil
  1174. }
  1175. func isClientPlatform(_ *Config, value string) bool {
  1176. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1177. // Note: stricter than psi_web's Python string.whitespace
  1178. return unicode.Is(unicode.White_Space, c)
  1179. })
  1180. }
  1181. func isRelayProtocol(_ *Config, value string) bool {
  1182. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1183. }
  1184. func isBooleanFlag(_ *Config, value string) bool {
  1185. return value == "0" || value == "1"
  1186. }
  1187. func isUpstreamProxyType(_ *Config, value string) bool {
  1188. value = strings.ToLower(value)
  1189. return value == "http" || value == "socks5" || value == "socks4a"
  1190. }
  1191. func isRegionCode(_ *Config, value string) bool {
  1192. if len(value) != 2 {
  1193. return false
  1194. }
  1195. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1196. return c < 'A' || c > 'Z'
  1197. })
  1198. }
  1199. func isDialAddress(_ *Config, value string) bool {
  1200. // "<host>:<port>", where <host> is a domain or IP address
  1201. parts := strings.Split(value, ":")
  1202. if len(parts) != 2 {
  1203. return false
  1204. }
  1205. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1206. return false
  1207. }
  1208. if !isDigits(nil, parts[1]) {
  1209. return false
  1210. }
  1211. _, err := strconv.Atoi(parts[1])
  1212. if err != nil {
  1213. return false
  1214. }
  1215. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1216. return true
  1217. }
  1218. func isIPAddress(_ *Config, value string) bool {
  1219. return net.ParseIP(value) != nil
  1220. }
  1221. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1222. func isDomain(_ *Config, value string) bool {
  1223. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1224. //
  1225. // "ensures that each segment
  1226. // * contains at least one character and a maximum of 63 characters
  1227. // * consists only of allowed characters
  1228. // * doesn't begin or end with a hyphen"
  1229. //
  1230. if len(value) > 255 {
  1231. return false
  1232. }
  1233. value = strings.TrimSuffix(value, ".")
  1234. for _, part := range strings.Split(value, ".") {
  1235. // Note: regexp doesn't support the following Perl expression which
  1236. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1237. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1238. return false
  1239. }
  1240. if !isDomainRegex.Match([]byte(part)) {
  1241. return false
  1242. }
  1243. }
  1244. return true
  1245. }
  1246. func isHostHeader(_ *Config, value string) bool {
  1247. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1248. if strings.Contains(value, ":") {
  1249. return isDialAddress(nil, value)
  1250. }
  1251. return isIPAddress(nil, value) || isDomain(nil, value)
  1252. }
  1253. func isServerEntrySource(_ *Config, value string) bool {
  1254. return common.Contains(protocol.SupportedServerEntrySources, value)
  1255. }
  1256. var isISO8601DateRegex = regexp.MustCompile(
  1257. `(?P<year>[0-9]{4})-(?P<month>[0-9]{1,2})-(?P<day>[0-9]{1,2})T(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2}):(?P<second>[0-9]{2})(\.(?P<fraction>[0-9]+))?(?P<timezone>Z|(([-+])([0-9]{2}):([0-9]{2})))`)
  1258. func isISO8601Date(_ *Config, value string) bool {
  1259. return isISO8601DateRegex.Match([]byte(value))
  1260. }
  1261. func isLastConnected(_ *Config, value string) bool {
  1262. return value == "None" || isISO8601Date(nil, value)
  1263. }