api.go 54 KB

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