api.go 61 KB

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