api.go 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796
  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. []requestParamSpec{
  123. {"missing_server_entry_signature", isBase64String, requestParamOptional},
  124. {"missing_server_entry_provider_id", isBase64String, requestParamOptional},
  125. },
  126. baseAndDialParams...),
  127. tacticsParams...)
  128. // handshakeAPIRequestHandler implements the "handshake" API request.
  129. // Clients make the handshake immediately after establishing a tunnel
  130. // connection; the response tells the client what homepage to open, what
  131. // stats to record, etc.
  132. func handshakeAPIRequestHandler(
  133. support *SupportServices,
  134. apiProtocol string,
  135. sshClient *sshClient,
  136. params common.APIParameters) ([]byte, error) {
  137. var clientGeoIPData GeoIPData
  138. var inproxyClientIP string
  139. var inproxyClientGeoIPData GeoIPData
  140. var inproxyRelayLogFields common.LogFields
  141. if sshClient.isInproxyTunnelProtocol {
  142. inproxyConnectionID, err := getStringRequestParam(params, "inproxy_connection_id")
  143. if err != nil {
  144. return nil, errors.Trace(err)
  145. }
  146. // Complete the in-proxy broker/server relay before the rest of
  147. // handshake in order to obtain the original client IP and other
  148. // inputs sent from the broker.
  149. //
  150. // In the best and typical case, the broker has already established a
  151. // secure session with this server and the inproxy_relay_packet is
  152. // the broker report application-level payload. Otherwise, if there
  153. // is no session or the session has expired, session handshake
  154. // messages will be relayed to the broker via the client, using SSH
  155. // requests to the client. These requests/responses happen while the
  156. // handshake response remains outstanding, as this handler needs the
  157. // original client IP and its geolocation data in order to determine
  158. // the correct landing pages, traffic rules, tactics, etc.
  159. //
  160. // The client should extends its handshake timeout to accommodate
  161. // potential relay round trips.
  162. inproxyRelayPacketStr, err := getStringRequestParam(params, "inproxy_relay_packet")
  163. if err != nil {
  164. return nil, errors.Trace(err)
  165. }
  166. inproxyRelayPacket, err := base64.RawStdEncoding.DecodeString(inproxyRelayPacketStr)
  167. if err != nil {
  168. return nil, errors.Trace(err)
  169. }
  170. inproxyClientIP, inproxyRelayLogFields, err = doHandshakeInproxyBrokerRelay(
  171. sshClient,
  172. inproxyConnectionID,
  173. inproxyRelayPacket)
  174. if err != nil {
  175. return nil, errors.Trace(err)
  176. }
  177. inproxyClientGeoIPData = support.GeoIPService.Lookup(inproxyClientIP)
  178. clientGeoIPData = inproxyClientGeoIPData
  179. } else {
  180. clientGeoIPData = sshClient.getClientGeoIPData()
  181. }
  182. // Check input parameters
  183. // Note: ignoring legacy "known_servers" params
  184. err := validateRequestParams(support.Config, params, handshakeRequestParams)
  185. if err != nil {
  186. return nil, errors.Trace(err)
  187. }
  188. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  189. clientVersion, _ := getStringRequestParam(params, "client_version")
  190. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  191. isMobile := isMobileClientPlatform(clientPlatform)
  192. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  193. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  194. // the client, a value of 0 will be used.
  195. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  196. var authorizations []string
  197. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  198. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  199. if err != nil {
  200. return nil, errors.Trace(err)
  201. }
  202. }
  203. deviceRegion, ok := getOptionalStringRequestParam(params, "device_region")
  204. if !ok {
  205. deviceRegion = GEOIP_UNKNOWN_VALUE
  206. }
  207. // splitTunnelOwnRegion indicates if the client is requesting split tunnel
  208. // mode to be applied to the client's own country. When omitted by the
  209. // client, the value will be false.
  210. //
  211. // When split_tunnel_regions is non-empty, split tunnel mode will be
  212. // applied for the specified country codes. When omitted by the client,
  213. // the value will be an empty slice.
  214. splitTunnelOwnRegion, _ := getBoolStringRequestParam(params, "split_tunnel")
  215. splitTunnelOtherRegions, _ := getStringArrayRequestParam(params, "split_tunnel_regions")
  216. ownRegion := ""
  217. if splitTunnelOwnRegion {
  218. ownRegion = clientGeoIPData.Country
  219. }
  220. var splitTunnelLookup *splitTunnelLookup
  221. if ownRegion != "" || len(splitTunnelOtherRegions) > 0 {
  222. splitTunnelLookup, err = newSplitTunnelLookup(ownRegion, splitTunnelOtherRegions)
  223. if err != nil {
  224. return nil, errors.Trace(err)
  225. }
  226. }
  227. // Note: no guarantee that PsinetDatabase won't reload between database calls
  228. db := support.PsinetDatabase
  229. httpsRequestRegexes, domainBytesChecksum := db.GetHttpsRequestRegexes(sponsorID)
  230. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  231. common.GeoIPData(clientGeoIPData), params)
  232. if err != nil {
  233. return nil, errors.Trace(err)
  234. }
  235. var newTacticsTag string
  236. if tacticsPayload != nil && len(tacticsPayload.Tactics) > 0 {
  237. newTacticsTag = tacticsPayload.Tag
  238. }
  239. // Flag the SSH client as having completed its handshake. This
  240. // may reselect traffic rules and starts allowing port forwards.
  241. apiParams := copyBaseAndDialParams(params)
  242. handshakeStateInfo, err := sshClient.setHandshakeState(
  243. handshakeState{
  244. completed: true,
  245. apiProtocol: apiProtocol,
  246. apiParams: apiParams,
  247. domainBytesChecksum: domainBytesChecksum,
  248. establishedTunnelsCount: establishedTunnelsCount,
  249. splitTunnelLookup: splitTunnelLookup,
  250. deviceRegion: deviceRegion,
  251. newTacticsTag: newTacticsTag,
  252. inproxyClientIP: inproxyClientIP,
  253. inproxyClientGeoIPData: inproxyClientGeoIPData,
  254. inproxyRelayLogFields: inproxyRelayLogFields,
  255. },
  256. authorizations)
  257. if err != nil {
  258. return nil, errors.Trace(err)
  259. }
  260. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  261. // the state change (for example, if a second handshake is performed)
  262. //
  263. // The handshake event is no longer shipped to log consumers, so this is
  264. // simply a diagnostic log. Since the "server_tunnel" event includes all
  265. // common API parameters and "handshake_completed" flag, this handshake
  266. // log is mostly redundant and set to debug level.
  267. if IsLogLevelDebug() {
  268. logFields := getRequestLogFields(
  269. "",
  270. sshClient.sessionID,
  271. clientGeoIPData,
  272. handshakeStateInfo.authorizedAccessTypes,
  273. params,
  274. handshakeRequestParams)
  275. log.WithTraceFields(logFields).Debug("handshake")
  276. }
  277. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  278. // Discover new servers
  279. var encodedServerList []string
  280. if !sshClient.getDisableDiscovery() {
  281. clientIP := ""
  282. if sshClient.isInproxyTunnelProtocol {
  283. clientIP = inproxyClientIP
  284. } else if sshClient.peerAddr != nil {
  285. clientIP, _, _ = net.SplitHostPort(sshClient.peerAddr.String())
  286. }
  287. IP := net.ParseIP(clientIP)
  288. if IP == nil {
  289. return nil, errors.TraceNew("invalid client IP")
  290. }
  291. encodedServerList = support.discovery.DiscoverServers(IP)
  292. }
  293. // When the client indicates that it used an out-of-date server entry for
  294. // this connection, return a signed copy of the server entry for the client
  295. // to upgrade to. Out-of-date server entries are either unsigned or missing
  296. // a provider ID. See also: comment in psiphon.doHandshakeRequest.
  297. //
  298. // The missing_server_entry_signature parameter value is a server entry tag,
  299. // which is used to select the correct server entry for servers with multiple
  300. // entries. Identifying the server entries tags instead of server IPs prevents
  301. // an enumeration attack, where a malicious client can abuse this facilty to
  302. // check if an arbitrary IP address is a Psiphon server.
  303. //
  304. // The missing_server_entry_provider_id parameter value is a server entry
  305. // tag.
  306. serverEntryTag, ok := getOptionalStringRequestParam(
  307. params, "missing_server_entry_signature")
  308. if !ok {
  309. // Do not need to check this case if we'll already return the server
  310. // entry due to a missing signature.
  311. serverEntryTag, ok = getOptionalStringRequestParam(
  312. params, "missing_server_entry_provider_id")
  313. }
  314. if ok {
  315. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  316. if ok {
  317. encodedServerList = append(encodedServerList, ownServerEntry)
  318. }
  319. }
  320. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  321. // the JSON response, return an empty array instead of null for legacy
  322. // clients.
  323. homepages := db.GetRandomizedHomepages(
  324. sponsorID,
  325. clientGeoIPData.Country,
  326. clientGeoIPData.ASN,
  327. deviceRegion,
  328. isMobile)
  329. clientAddress := ""
  330. if sshClient.isInproxyTunnelProtocol {
  331. // ClientAddress not supported for in-proxy tunnel protocols:
  332. //
  333. // - We don't want to return the address of the direct peer, the
  334. // in-proxy proxy;
  335. // - The known port number will correspond to the in-proxy proxy
  336. // source address, not the client;
  337. // - While we assume that the the original client IP from the broker
  338. // is representative for geolocation, an actual direct connection
  339. // to the Psiphon server from the client may route differently and
  340. // use a different IP address.
  341. clientAddress = ""
  342. } else if sshClient.peerAddr != nil {
  343. clientAddress = sshClient.peerAddr.String()
  344. }
  345. var marshaledTacticsPayload []byte
  346. if tacticsPayload != nil {
  347. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  348. if err != nil {
  349. return nil, errors.Trace(err)
  350. }
  351. }
  352. handshakeResponse := protocol.HandshakeResponse{
  353. Homepages: homepages,
  354. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  355. PageViewRegexes: make([]map[string]string, 0),
  356. HttpsRequestRegexes: httpsRequestRegexes,
  357. EncodedServerList: encodedServerList,
  358. ClientRegion: clientGeoIPData.Country,
  359. ClientAddress: clientAddress,
  360. ServerTimestamp: common.GetCurrentTimestamp(),
  361. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  362. TacticsPayload: marshaledTacticsPayload,
  363. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  364. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  365. SteeringIP: handshakeStateInfo.steeringIP,
  366. Padding: strings.Repeat(" ", pad_response),
  367. }
  368. // TODO: as a future enhancement, pack and CBOR encode this and other API
  369. // responses
  370. responsePayload, err := json.Marshal(handshakeResponse)
  371. if err != nil {
  372. return nil, errors.Trace(err)
  373. }
  374. return responsePayload, nil
  375. }
  376. func doHandshakeInproxyBrokerRelay(
  377. sshClient *sshClient,
  378. clientConnectionID string,
  379. initialRelayPacket []byte) (string, common.LogFields, error) {
  380. connectionID, err := inproxy.IDFromString(clientConnectionID)
  381. if err != nil {
  382. return "", nil, errors.Trace(err)
  383. }
  384. clientIP := ""
  385. var logFields common.LogFields
  386. // This first packet from broker arrives via the client handshake. If
  387. // there is an established, non-expired session, this packet will contain
  388. // the application-level broker report and the relay will complete
  389. // immediately.
  390. relayPacket := initialRelayPacket
  391. for i := 0; i < inproxy.MaxRelayRoundTrips; i++ {
  392. // broker -> server
  393. relayPacket, err = sshClient.sshServer.inproxyBrokerSessions.HandlePacket(
  394. CommonLogger(log),
  395. relayPacket,
  396. connectionID,
  397. func(
  398. brokerVerifiedOriginalClientIP string,
  399. fields common.LogFields) {
  400. // Once the broker report is received, this callback is invoked.
  401. clientIP = brokerVerifiedOriginalClientIP
  402. logFields = fields
  403. })
  404. if err != nil {
  405. if relayPacket == nil {
  406. // If there is an error and no relay packet, the packet is
  407. // invalid. Drop the packet and return an error. Do _not_
  408. // reset the session, otherwise a malicious client could
  409. // interrupt a valid broker/server session with a malformed packet.
  410. return "", nil, errors.Trace(err)
  411. }
  412. // In the case of expired sessions, a reset session token is sent
  413. // to the broker, so this is not a failure condition; the error
  414. // is for logging only. Continue to ship relayPacket.
  415. log.WithTraceFields(LogFields{"error": err}).Warning(
  416. "HandlePacket returned packet and error")
  417. }
  418. if relayPacket == nil {
  419. // The relay is complete; the handler recording the clientIP and
  420. // logFields was invoked.
  421. return clientIP, logFields, nil
  422. }
  423. // server -> broker
  424. // Send an SSH request back to client with next packet for broker;
  425. // then the client relays that to the broker and returns the broker's
  426. // next response in the SSH response.
  427. request := protocol.InproxyRelayRequest{
  428. Packet: relayPacket,
  429. }
  430. requestPayload, err := protocol.CBOREncoding.Marshal(request)
  431. if err != nil {
  432. return "", nil, errors.Trace(err)
  433. }
  434. ok, responsePayload, err := sshClient.sshConn.SendRequest(
  435. protocol.PSIPHON_API_INPROXY_RELAY_REQUEST_NAME,
  436. true,
  437. requestPayload)
  438. if err != nil {
  439. return "", nil, errors.Trace(err)
  440. }
  441. if !ok {
  442. return "", nil, errors.TraceNew("client rejected request")
  443. }
  444. var response protocol.InproxyRelayResponse
  445. err = cbor.Unmarshal(responsePayload, &response)
  446. if err != nil {
  447. return "", nil, errors.Trace(err)
  448. }
  449. relayPacket = response.Packet
  450. }
  451. return "", nil, errors.Tracef("exceeded %d relay round trips", inproxy.MaxRelayRoundTrips)
  452. }
  453. // uniqueUserParams are the connected request parameters which are logged for
  454. // unique_user events.
  455. var uniqueUserParams = append(
  456. []requestParamSpec{
  457. {"last_connected", isLastConnected, 0}},
  458. baseParams...)
  459. var connectedRequestParams = append(
  460. []requestParamSpec{
  461. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  462. uniqueUserParams...)
  463. // updateOnConnectedParamNames are connected request parameters which are
  464. // copied to update data logged with server_tunnel: these fields either only
  465. // ship with or ship newer data with connected requests.
  466. var updateOnConnectedParamNames = append(
  467. []string{
  468. "last_connected",
  469. "establishment_duration",
  470. },
  471. fragmentor.GetUpstreamMetricsNames()...)
  472. // connectedAPIRequestHandler implements the "connected" API request. Clients
  473. // make the connected request once a tunnel connection has been established
  474. // and at least once per 24h for long-running tunnels. The last_connected
  475. // input value, which should be a connected_timestamp output from a previous
  476. // connected response, is used to calculate unique user stats.
  477. // connected_timestamp is truncated as a privacy measure.
  478. func connectedAPIRequestHandler(
  479. support *SupportServices,
  480. sshClient *sshClient,
  481. params common.APIParameters) ([]byte, error) {
  482. err := validateRequestParams(support.Config, params, connectedRequestParams)
  483. if err != nil {
  484. return nil, errors.Trace(err)
  485. }
  486. // Note: unlock before use is only safe as long as referenced sshClient data,
  487. // such as slices in handshakeState, is read-only after initially set.
  488. sshClient.Lock()
  489. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  490. sshClient.Unlock()
  491. lastConnected, _ := getStringRequestParam(params, "last_connected")
  492. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  493. // client may have performed more upstream fragmentation since the previous
  494. // metrics reported by the handshake request. Also, additional fields that
  495. // are reported only in the connected request are added to server_tunnel
  496. // here.
  497. sshClient.updateAPIParameters(copyUpdateOnConnectedParams(params))
  498. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  499. // The finest required granularity for unique users is daily. To save space,
  500. // only record a "unique_user" log event when the client's last_connected is
  501. // in the previous day relative to the new connected_timestamp.
  502. logUniqueUser := false
  503. if lastConnected == "None" {
  504. logUniqueUser = true
  505. } else {
  506. t1, _ := time.Parse(time.RFC3339, lastConnected)
  507. year, month, day := t1.Date()
  508. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  509. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  510. year, month, day = t2.Date()
  511. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  512. if t1.Before(t2) && d1 != d2 {
  513. logUniqueUser = true
  514. }
  515. }
  516. if logUniqueUser {
  517. log.LogRawFieldsWithTimestamp(
  518. getRequestLogFields(
  519. "unique_user",
  520. sshClient.sessionID,
  521. sshClient.getClientGeoIPData(),
  522. authorizedAccessTypes,
  523. params,
  524. uniqueUserParams))
  525. }
  526. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  527. connectedResponse := protocol.ConnectedResponse{
  528. ConnectedTimestamp: connectedTimestamp,
  529. Padding: strings.Repeat(" ", pad_response),
  530. }
  531. responsePayload, err := json.Marshal(connectedResponse)
  532. if err != nil {
  533. return nil, errors.Trace(err)
  534. }
  535. return responsePayload, nil
  536. }
  537. var statusRequestParams = baseParams
  538. var remoteServerListStatParams = append(
  539. []requestParamSpec{
  540. // Legacy clients don't record the session_id with remote_server_list_stats entries.
  541. {"session_id", isHexDigits, requestParamOptional},
  542. {"client_download_timestamp", isISO8601Date, 0},
  543. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  544. {"url", isAnyString, 0},
  545. {"etag", isAnyString, 0},
  546. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  547. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  548. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  549. {"fronting_provider_id", isAnyString, requestParamOptional},
  550. {"meek_dial_address", isDialAddress, requestParamOptional},
  551. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  552. {"meek_sni_server_name", isDomain, requestParamOptional},
  553. {"meek_host_header", isHostHeader, requestParamOptional},
  554. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  555. {"user_agent", isAnyString, requestParamOptional},
  556. {"tls_profile", isAnyString, requestParamOptional},
  557. {"tls_version", isAnyString, requestParamOptional},
  558. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  559. },
  560. baseParams...)
  561. // Backwards compatibility case: legacy clients do not include these fields in
  562. // the remote_server_list_stats entries. Use the values from the outer status
  563. // request as an approximation (these values reflect the client at persistent
  564. // stat shipping time, which may differ from the client at persistent stat
  565. // recording time). Note that all but client_build_rev, device_region, and
  566. // device_location are required fields.
  567. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  568. "propagation_channel_id",
  569. "sponsor_id",
  570. "client_version",
  571. "client_platform",
  572. "client_build_rev",
  573. "device_region",
  574. "device_location",
  575. }
  576. var failedTunnelStatParams = append(
  577. []requestParamSpec{
  578. {"server_entry_tag", isAnyString, requestParamOptional},
  579. {"session_id", isHexDigits, 0},
  580. {"last_connected", isLastConnected, 0},
  581. {"client_failed_timestamp", isISO8601Date, 0},
  582. {"record_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  583. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  584. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  585. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  586. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  587. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  588. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  589. {"tunnel_error", isAnyString, 0}},
  590. baseAndDialParams...)
  591. // statusAPIRequestHandler implements the "status" API request.
  592. // Clients make periodic status requests which deliver client-side
  593. // recorded data transfer and tunnel duration stats.
  594. // Note from psi_web implementation: no input validation on domains;
  595. // any string is accepted (regex transform may result in arbitrary
  596. // string). Stats processor must handle this input with care.
  597. func statusAPIRequestHandler(
  598. support *SupportServices,
  599. sshClient *sshClient,
  600. params common.APIParameters) ([]byte, error) {
  601. err := validateRequestParams(support.Config, params, statusRequestParams)
  602. if err != nil {
  603. return nil, errors.Trace(err)
  604. }
  605. sshClient.Lock()
  606. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  607. sshClient.Unlock()
  608. statusData, err := getJSONObjectRequestParam(params, "statusData")
  609. if err != nil {
  610. return nil, errors.Trace(err)
  611. }
  612. // Logs are queued until the input is fully validated. Otherwise, stats
  613. // could be double counted if the client has a bug in its request
  614. // formatting: partial stats would be logged (counted), the request would
  615. // fail, and clients would then resend all the same stats again.
  616. logQueue := make([]LogFields, 0)
  617. // Domain bytes transferred stats
  618. // Older clients may not submit this data
  619. // Clients are expected to send host_bytes/domain_bytes stats only when
  620. // configured to do so in the handshake reponse. Legacy clients may still
  621. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  622. if sshClient.acceptDomainBytes() && statusData["host_bytes"] != nil {
  623. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  624. if err != nil {
  625. return nil, errors.Trace(err)
  626. }
  627. for domain, bytes := range hostBytes {
  628. domainBytesFields := getRequestLogFields(
  629. "domain_bytes",
  630. sshClient.sessionID,
  631. sshClient.getClientGeoIPData(),
  632. authorizedAccessTypes,
  633. params,
  634. statusRequestParams)
  635. domainBytesFields["domain"] = domain
  636. domainBytesFields["bytes"] = bytes
  637. logQueue = append(logQueue, domainBytesFields)
  638. }
  639. }
  640. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  641. // not time-of-recording.
  642. // Remote server list download persistent stats.
  643. // Older clients may not submit this data.
  644. if statusData["remote_server_list_stats"] != nil {
  645. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  646. if err != nil {
  647. return nil, errors.Trace(err)
  648. }
  649. for _, remoteServerListStat := range remoteServerListStats {
  650. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  651. if _, ok := remoteServerListStat[name]; !ok {
  652. if field, ok := params[name]; ok {
  653. remoteServerListStat[name] = field
  654. }
  655. }
  656. }
  657. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  658. if err != nil {
  659. // Occasionally, clients may send corrupt persistent stat data. Do not
  660. // fail the status request, as this will lead to endless retries.
  661. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  662. continue
  663. }
  664. remoteServerListFields := getRequestLogFields(
  665. "remote_server_list",
  666. "", // Use the session_id the client recorded with the event
  667. sshClient.getClientGeoIPData(),
  668. authorizedAccessTypes,
  669. remoteServerListStat,
  670. remoteServerListStatParams)
  671. logQueue = append(logQueue, remoteServerListFields)
  672. }
  673. }
  674. // Failed tunnel persistent stats.
  675. // Older clients may not submit this data.
  676. var invalidServerEntryTags map[string]bool
  677. if statusData["failed_tunnel_stats"] != nil {
  678. // Note: no guarantee that PsinetDatabase won't reload between database calls
  679. db := support.PsinetDatabase
  680. invalidServerEntryTags = make(map[string]bool)
  681. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  682. if err != nil {
  683. return nil, errors.Trace(err)
  684. }
  685. for _, failedTunnelStat := range failedTunnelStats {
  686. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  687. if err != nil {
  688. // Occasionally, clients may send corrupt persistent stat data. Do not
  689. // fail the status request, as this will lead to endless retries.
  690. //
  691. // TODO: trigger pruning if the data corruption indicates corrupt server
  692. // entry storage?
  693. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  694. continue
  695. }
  696. failedTunnelFields := getRequestLogFields(
  697. "failed_tunnel",
  698. "", // Use the session_id the client recorded with the event
  699. sshClient.getClientGeoIPData(),
  700. authorizedAccessTypes,
  701. failedTunnelStat,
  702. failedTunnelStatParams)
  703. // Return a list of servers, identified by server entry tag, that are
  704. // invalid and presumed to be deleted. This information is used by clients
  705. // to prune deleted servers from their local datastores and stop attempting
  706. // connections to servers that no longer exist.
  707. //
  708. // This mechanism uses tags instead of server IPs: (a) to prevent an
  709. // enumeration attack, where a malicious client can query the entire IPv4
  710. // range and build a map of the Psiphon network; (b) to deal with recyling
  711. // cases where a server deleted and its IP is reused for a new server with
  712. // a distinct server entry.
  713. //
  714. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  715. // before returning a negative result, to mitigate accidental pruning.
  716. //
  717. // In addition, when the reported dial port number is 0, flag the server
  718. // entry as invalid to trigger client pruning. This covers a class of
  719. // invalid/semi-functional server entries, found in practice to be stored
  720. // by clients, where some protocol port number has been omitted -- due to
  721. // historical bugs in various server entry handling implementations. When
  722. // missing from a server entry loaded by a client, the port number
  723. // evaluates to 0, the zero value, which is not a valid port number even if
  724. // were not missing.
  725. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  726. if ok {
  727. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  728. if serverEntryValid {
  729. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  730. if err == nil && dialPortNumber == 0 {
  731. serverEntryValid = false
  732. }
  733. }
  734. if !serverEntryValid {
  735. invalidServerEntryTags[serverEntryTag] = true
  736. }
  737. // Add a field to the failed_tunnel log indicating if the server entry is
  738. // valid.
  739. failedTunnelFields["server_entry_valid"] = serverEntryValid
  740. }
  741. // Log failed_tunnel.
  742. logQueue = append(logQueue, failedTunnelFields)
  743. }
  744. }
  745. for _, logItem := range logQueue {
  746. log.LogRawFieldsWithTimestamp(logItem)
  747. }
  748. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  749. statusResponse := protocol.StatusResponse{
  750. Padding: strings.Repeat(" ", pad_response),
  751. }
  752. if len(invalidServerEntryTags) > 0 {
  753. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  754. i := 0
  755. for tag := range invalidServerEntryTags {
  756. statusResponse.InvalidServerEntryTags[i] = tag
  757. i++
  758. }
  759. }
  760. responsePayload, err := json.Marshal(statusResponse)
  761. if err != nil {
  762. return nil, errors.Trace(err)
  763. }
  764. return responsePayload, nil
  765. }
  766. // clientVerificationAPIRequestHandler is just a compliance stub
  767. // for older Android clients that still send verification requests
  768. func clientVerificationAPIRequestHandler(
  769. _ *SupportServices,
  770. _ *sshClient,
  771. _ common.APIParameters) ([]byte, error) {
  772. return make([]byte, 0), nil
  773. }
  774. var tacticsParams = []requestParamSpec{
  775. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  776. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  777. }
  778. var tacticsRequestParams = append(
  779. append(
  780. []requestParamSpec{
  781. {"session_id", isHexDigits, 0}},
  782. tacticsParams...),
  783. baseAndDialParams...)
  784. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  785. return func(params common.APIParameters) error {
  786. return validateRequestParams(config, params, tacticsRequestParams)
  787. }
  788. }
  789. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  790. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  791. logFields := getRequestLogFields(
  792. tactics.TACTICS_METRIC_EVENT_NAME,
  793. "", // Use the session_id the client reported
  794. GeoIPData(geoIPData),
  795. nil, // authorizedAccessTypes are not known yet
  796. params,
  797. tacticsRequestParams)
  798. return common.LogFields(logFields)
  799. }
  800. }
  801. var inproxyBrokerRequestParams = append(
  802. append(
  803. []requestParamSpec{
  804. {"session_id", isHexDigits, 0},
  805. {"fronting_provider_id", isAnyString, requestParamOptional}},
  806. tacticsParams...),
  807. baseParams...)
  808. func getInproxyBrokerAPIParameterValidator(config *Config) common.APIParameterValidator {
  809. return func(params common.APIParameters) error {
  810. return validateRequestParams(config, params, inproxyBrokerRequestParams)
  811. }
  812. }
  813. func getInproxyBrokerAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  814. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  815. logFields := getRequestLogFields(
  816. "inproxy_broker",
  817. "", // Use the session_id the client reported
  818. GeoIPData(geoIPData),
  819. nil,
  820. params,
  821. inproxyBrokerRequestParams)
  822. return common.LogFields(logFields)
  823. }
  824. }
  825. // requestParamSpec defines a request parameter. Each param is expected to be
  826. // a string, unless requestParamArray is specified, in which case an array of
  827. // strings is expected.
  828. type requestParamSpec struct {
  829. name string
  830. validator func(*Config, string) bool
  831. flags uint32
  832. }
  833. const (
  834. requestParamOptional = 1
  835. requestParamNotLogged = 1 << 1
  836. requestParamArray = 1 << 2
  837. requestParamJSON = 1 << 3
  838. requestParamLogStringAsInt = 1 << 4
  839. requestParamLogStringAsFloat = 1 << 5
  840. requestParamLogStringLengthAsInt = 1 << 6
  841. requestParamLogFlagAsBool = 1 << 7
  842. requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
  843. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  844. )
  845. // baseParams are the basic request parameters that are expected for all API
  846. // requests and log events.
  847. var baseParams = []requestParamSpec{
  848. {"propagation_channel_id", isHexDigits, 0},
  849. {"sponsor_id", isHexDigits, 0},
  850. {"client_version", isIntString, requestParamLogStringAsInt},
  851. {"client_platform", isClientPlatform, 0},
  852. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  853. {"client_build_rev", isHexDigits, requestParamOptional},
  854. {"device_region", isAnyString, requestParamOptional},
  855. {"device_location", isGeoHashString, requestParamOptional},
  856. {"network_type", isAnyString, requestParamOptional},
  857. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  858. }
  859. // baseDialParams are the dial parameters, per-tunnel network protocol and
  860. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  861. // tactics.
  862. var baseDialParams = []requestParamSpec{
  863. {"relay_protocol", isRelayProtocol, 0},
  864. {"ssh_client_version", isAnyString, requestParamOptional},
  865. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  866. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  867. {"fronting_provider_id", isAnyString, requestParamOptional},
  868. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  869. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  870. {"meek_sni_server_name", isDomain, requestParamOptional},
  871. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  872. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  873. {"user_agent", isAnyString, requestParamOptional},
  874. {"tls_profile", isAnyString, requestParamOptional},
  875. {"tls_version", isAnyString, requestParamOptional},
  876. {"server_entry_region", isRegionCode, requestParamOptional},
  877. {"server_entry_source", isServerEntrySource, requestParamOptional},
  878. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  879. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  880. {"quic_version", isAnyString, requestParamOptional},
  881. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  882. {"quic_disable_client_path_mtu_discovery", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  883. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  884. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  885. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  886. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  887. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  888. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  889. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  890. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  891. {"egress_region", isRegionCode, requestParamOptional},
  892. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  893. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  894. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  895. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  896. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  897. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  898. {"meek_redial_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  899. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  900. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  901. {"client_bpf", isAnyString, requestParamOptional},
  902. {"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  903. {"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
  904. {"conjure_transport", isAnyString, requestParamOptional},
  905. {"conjure_prefix", isAnyString, requestParamOptional},
  906. {"conjure_stun", isAnyString, requestParamOptional},
  907. {"conjure_empty_packet", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  908. {"conjure_network", isAnyString, requestParamOptional},
  909. {"conjure_port_number", isAnyString, requestParamOptional},
  910. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  911. {"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
  912. {"dns_preresolved", isAnyString, requestParamOptional},
  913. {"dns_preferred", isAnyString, requestParamOptional},
  914. {"dns_transform", isAnyString, requestParamOptional},
  915. {"dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  916. {"http_transform", isAnyString, requestParamOptional},
  917. {"seed_transform", isAnyString, requestParamOptional},
  918. {"ossh_prefix", isAnyString, requestParamOptional},
  919. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  920. {"tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  921. {"tls_ossh_sni_server_name", isDomain, requestParamOptional},
  922. {"tls_ossh_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  923. {"steering_ip", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  924. {"tls_sent_ticket", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  925. {"tls_did_resume", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  926. {"quic_sent_ticket", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  927. {"quic_did_resume", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  928. {"quic_dial_early", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  929. {"quic_obfuscated_psk", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  930. }
  931. var inproxyDialParams = []requestParamSpec{
  932. // Both the client and broker send inproxy_connection_id, and the values
  933. // must be the same. The broker's value is logged, so the client's value
  934. // is configured here as requestParamNotLogged.
  935. {"inproxy_connection_id", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  936. {"inproxy_relay_packet", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  937. {"inproxy_broker_is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  938. {"inproxy_broker_transport", isAnyString, requestParamOptional},
  939. {"inproxy_broker_fronting_provider_id", isAnyString, requestParamOptional},
  940. {"inproxy_broker_dial_address", isAnyString, requestParamOptional},
  941. {"inproxy_broker_resolved_ip_address", isAnyString, requestParamOptional},
  942. {"inproxy_broker_sni_server_name", isAnyString, requestParamOptional},
  943. {"inproxy_broker_host_header", isAnyString, requestParamOptional},
  944. {"inproxy_broker_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  945. {"inproxy_broker_user_agent", isAnyString, requestParamOptional},
  946. {"inproxy_broker_tls_profile", isAnyString, requestParamOptional},
  947. {"inproxy_broker_tls_version", isAnyString, requestParamOptional},
  948. {"inproxy_broker_tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  949. {"inproxy_broker_client_bpf", isAnyString, requestParamOptional},
  950. {"inproxy_broker_upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  951. {"inproxy_broker_http_transform", isAnyString, requestParamOptional},
  952. {"inproxy_broker_dns_preresolved", isAnyString, requestParamOptional},
  953. {"inproxy_broker_dns_preferred", isAnyString, requestParamOptional},
  954. {"inproxy_broker_dns_transform", isAnyString, requestParamOptional},
  955. {"inproxy_broker_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  956. {"inproxy_webrtc_dns_preresolved", isAnyString, requestParamOptional},
  957. {"inproxy_webrtc_dns_preferred", isAnyString, requestParamOptional},
  958. {"inproxy_webrtc_dns_transform", isAnyString, requestParamOptional},
  959. {"inproxy_webrtc_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  960. {"inproxy_webrtc_stun_server", isAnyString, requestParamOptional},
  961. {"inproxy_webrtc_stun_server_resolved_ip_address", isAnyString, requestParamOptional},
  962. {"inproxy_webrtc_stun_server_RFC5780", isAnyString, requestParamOptional},
  963. {"inproxy_webrtc_stun_server_RFC5780_resolved_ip_address", isAnyString, requestParamOptional},
  964. {"inproxy_webrtc_randomize_dtls", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  965. {"inproxy_webrtc_padded_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  966. {"inproxy_webrtc_padded_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  967. {"inproxy_webrtc_decoy_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  968. {"inproxy_webrtc_decoy_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  969. {"inproxy_webrtc_local_ice_candidate_type", isAnyString, requestParamOptional},
  970. {"inproxy_webrtc_local_ice_candidate_is_initiator", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  971. {"inproxy_webrtc_local_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  972. {"inproxy_webrtc_local_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  973. {"inproxy_webrtc_remote_ice_candidate_type", isAnyString, requestParamOptional},
  974. {"inproxy_webrtc_remote_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  975. {"inproxy_webrtc_remote_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  976. }
  977. // baseAndDialParams adds baseDialParams and inproxyDialParams to baseParams.
  978. var baseAndDialParams = append(
  979. append(
  980. append(
  981. []requestParamSpec{},
  982. baseParams...),
  983. baseDialParams...),
  984. inproxyDialParams...)
  985. func validateRequestParams(
  986. config *Config,
  987. params common.APIParameters,
  988. expectedParams []requestParamSpec) error {
  989. for _, expectedParam := range expectedParams {
  990. value := params[expectedParam.name]
  991. if value == nil {
  992. if expectedParam.flags&requestParamOptional != 0 {
  993. continue
  994. }
  995. return errors.Tracef("missing param: %s", expectedParam.name)
  996. }
  997. var err error
  998. switch {
  999. case expectedParam.flags&requestParamArray != 0:
  1000. err = validateStringArrayRequestParam(config, expectedParam, value)
  1001. case expectedParam.flags&requestParamJSON != 0:
  1002. // No validation: the JSON already unmarshalled; the parameter
  1003. // user will validate that the JSON contains the expected
  1004. // objects/data.
  1005. // TODO: without validation, any valid JSON will be logged
  1006. // by getRequestLogFields, even if the parameter user validates
  1007. // and rejects the parameter.
  1008. default:
  1009. err = validateStringRequestParam(config, expectedParam, value)
  1010. }
  1011. if err != nil {
  1012. return errors.Trace(err)
  1013. }
  1014. }
  1015. return nil
  1016. }
  1017. // copyBaseAndDialParams makes a copy of the params which includes only
  1018. // the baseAndDialParams.
  1019. func copyBaseAndDialParams(params common.APIParameters) common.APIParameters {
  1020. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  1021. // scalar types (int, string, etc.)
  1022. paramsCopy := make(common.APIParameters)
  1023. for _, baseParam := range baseAndDialParams {
  1024. value := params[baseParam.name]
  1025. if value == nil {
  1026. continue
  1027. }
  1028. paramsCopy[baseParam.name] = value
  1029. }
  1030. return paramsCopy
  1031. }
  1032. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  1033. // Note: not a deep copy
  1034. paramsCopy := make(common.APIParameters)
  1035. for _, name := range updateOnConnectedParamNames {
  1036. value := params[name]
  1037. if value == nil {
  1038. continue
  1039. }
  1040. paramsCopy[name] = value
  1041. }
  1042. return paramsCopy
  1043. }
  1044. func validateStringRequestParam(
  1045. config *Config,
  1046. expectedParam requestParamSpec,
  1047. value interface{}) error {
  1048. strValue, ok := value.(string)
  1049. if !ok {
  1050. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  1051. }
  1052. if !expectedParam.validator(config, strValue) {
  1053. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  1054. }
  1055. return nil
  1056. }
  1057. func validateStringArrayRequestParam(
  1058. config *Config,
  1059. expectedParam requestParamSpec,
  1060. value interface{}) error {
  1061. arrayValue, ok := value.([]interface{})
  1062. if !ok {
  1063. return errors.Tracef("unexpected array param type: %s", expectedParam.name)
  1064. }
  1065. for _, value := range arrayValue {
  1066. err := validateStringRequestParam(config, expectedParam, value)
  1067. if err != nil {
  1068. return errors.Trace(err)
  1069. }
  1070. }
  1071. return nil
  1072. }
  1073. // getRequestLogFields makes LogFields to log the API event following
  1074. // the legacy psi_web and current ELK naming conventions.
  1075. func getRequestLogFields(
  1076. eventName string,
  1077. sessionID string,
  1078. geoIPData GeoIPData,
  1079. authorizedAccessTypes []string,
  1080. params common.APIParameters,
  1081. expectedParams []requestParamSpec) LogFields {
  1082. logFields := make(LogFields)
  1083. // A sessionID is specified for SSH API requests, where the Psiphon server
  1084. // has already received a session ID in the SSH auth payload. In this
  1085. // case, use that session ID.
  1086. //
  1087. // sessionID is "" for other, non-SSH server cases including tactics,
  1088. // in-proxy broker, and client-side store and forward events including
  1089. // remote server list and failed tunnel.
  1090. if sessionID != "" {
  1091. logFields["session_id"] = sessionID
  1092. }
  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.Contains(geohashAlphabet, string(c)) {
  1522. return false
  1523. }
  1524. }
  1525. return true
  1526. }