api.go 48 KB

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