api.go 53 KB

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