api.go 52 KB

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