api.go 63 KB

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