api.go 65 KB

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