api.go 68 KB

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