api.go 61 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. 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. {"network_type", isAnyString, requestParamOptional}},
  814. tacticsParams...),
  815. baseSessionParams...)
  816. func getInproxyBrokerAPIParameterValidator(config *Config) common.APIParameterValidator {
  817. return func(params common.APIParameters) error {
  818. return validateRequestParams(config, params, inproxyBrokerRequestParams)
  819. }
  820. }
  821. func getInproxyBrokerAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  822. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  823. logFields := getRequestLogFields(
  824. "inproxy_broker",
  825. GeoIPData(geoIPData),
  826. nil,
  827. params,
  828. inproxyBrokerRequestParams)
  829. return common.LogFields(logFields)
  830. }
  831. }
  832. // requestParamSpec defines a request parameter. Each param is expected to be
  833. // a string, unless requestParamArray is specified, in which case an array of
  834. // strings is expected.
  835. type requestParamSpec struct {
  836. name string
  837. validator func(*Config, string) bool
  838. flags uint32
  839. }
  840. const (
  841. requestParamOptional = 1
  842. requestParamNotLogged = 1 << 1
  843. requestParamArray = 1 << 2
  844. requestParamJSON = 1 << 3
  845. requestParamLogStringAsInt = 1 << 4
  846. requestParamLogStringAsFloat = 1 << 5
  847. requestParamLogStringLengthAsInt = 1 << 6
  848. requestParamLogFlagAsBool = 1 << 7
  849. requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
  850. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  851. )
  852. // baseParams are the basic request parameters that are expected for all API
  853. // requests and log events.
  854. var baseParams = []requestParamSpec{
  855. {"client_session_id", isHexDigits, requestParamNotLogged},
  856. {"propagation_channel_id", isHexDigits, 0},
  857. {"sponsor_id", isHexDigits, 0},
  858. {"client_version", isIntString, requestParamLogStringAsInt},
  859. {"client_platform", isClientPlatform, 0},
  860. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  861. {"client_build_rev", isHexDigits, requestParamOptional},
  862. {"device_region", isAnyString, requestParamOptional},
  863. {"device_location", isGeoHashString, requestParamOptional},
  864. }
  865. // baseSessionParams adds to baseParams the required session_id parameter. For
  866. // all requests except handshake, all existing clients are expected to send
  867. // session_id. Legacy clients may not send "session_id" in handshake.
  868. var baseSessionParams = append(
  869. []requestParamSpec{
  870. {"session_id", isHexDigits, 0}},
  871. baseParams...)
  872. // baseDialParams are the dial parameters, per-tunnel network protocol and
  873. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  874. // tactics.
  875. var baseDialParams = []requestParamSpec{
  876. {"relay_protocol", isRelayProtocol, 0},
  877. {"ssh_client_version", isAnyString, requestParamOptional},
  878. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  879. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  880. {"fronting_provider_id", isAnyString, requestParamOptional},
  881. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  882. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  883. {"meek_sni_server_name", isDomain, requestParamOptional},
  884. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  885. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  886. {"user_agent", isAnyString, requestParamOptional},
  887. {"tls_profile", isAnyString, requestParamOptional},
  888. {"tls_version", isAnyString, requestParamOptional},
  889. {"server_entry_region", isRegionCode, requestParamOptional},
  890. {"server_entry_source", isServerEntrySource, requestParamOptional},
  891. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  892. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, 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. {"network_type", isAnyString, requestParamOptional},
  917. {"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  918. {"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
  919. {"conjure_transport", isAnyString, requestParamOptional},
  920. {"conjure_prefix", isAnyString, requestParamOptional},
  921. {"conjure_stun", isAnyString, requestParamOptional},
  922. {"conjure_empty_packet", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  923. {"conjure_network", isAnyString, requestParamOptional},
  924. {"conjure_port_number", isAnyString, requestParamOptional},
  925. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  926. {"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
  927. {"dns_preresolved", isAnyString, requestParamOptional},
  928. {"dns_preferred", isAnyString, requestParamOptional},
  929. {"dns_transform", isAnyString, requestParamOptional},
  930. {"dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  931. {"http_transform", isAnyString, requestParamOptional},
  932. {"seed_transform", isAnyString, requestParamOptional},
  933. {"ossh_prefix", isAnyString, requestParamOptional},
  934. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  935. {"tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  936. {"tls_ossh_sni_server_name", isDomain, requestParamOptional},
  937. {"tls_ossh_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  938. {"steering_ip", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  939. }
  940. var inproxyDialParams = []requestParamSpec{
  941. // Both the client and broker send inproxy_connection_id, and the values
  942. // must be the same. The broker's value is logged, so the client's value
  943. // is configured here as requestParamNotLogged.
  944. {"inproxy_connection_id", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  945. {"inproxy_relay_packet", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  946. {"inproxy_broker_is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  947. {"inproxy_broker_transport", isAnyString, requestParamOptional},
  948. {"inproxy_broker_fronting_provider_id", isAnyString, requestParamOptional},
  949. {"inproxy_broker_dial_address", isAnyString, requestParamOptional},
  950. {"inproxy_broker_resolved_ip_address", isAnyString, requestParamOptional},
  951. {"inproxy_broker_sni_server_name", isAnyString, requestParamOptional},
  952. {"inproxy_broker_host_header", isAnyString, requestParamOptional},
  953. {"inproxy_broker_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  954. {"inproxy_broker_user_agent", isAnyString, requestParamOptional},
  955. {"inproxy_broker_tls_profile", isAnyString, requestParamOptional},
  956. {"inproxy_broker_tls_version", isAnyString, requestParamOptional},
  957. {"inproxy_broker_tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  958. {"inproxy_broker_client_bpf", isAnyString, requestParamOptional},
  959. {"inproxy_broker_upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  960. {"inproxy_broker_http_transform", isAnyString, requestParamOptional},
  961. {"inproxy_broker_dns_preresolved", isAnyString, requestParamOptional},
  962. {"inproxy_broker_dns_preferred", isAnyString, requestParamOptional},
  963. {"inproxy_broker_dns_transform", isAnyString, requestParamOptional},
  964. {"inproxy_broker_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  965. {"inproxy_webrtc_dns_preresolved", isAnyString, requestParamOptional},
  966. {"inproxy_webrtc_dns_preferred", isAnyString, requestParamOptional},
  967. {"inproxy_webrtc_dns_transform", isAnyString, requestParamOptional},
  968. {"inproxy_webrtc_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  969. {"inproxy_webrtc_stun_server", isAnyString, requestParamOptional},
  970. {"inproxy_webrtc_stun_server_resolved_ip_address", isAnyString, requestParamOptional},
  971. {"inproxy_webrtc_stun_server_RFC5780", isAnyString, requestParamOptional},
  972. {"inproxy_webrtc_stun_server_RFC5780_resolved_ip_address", isAnyString, requestParamOptional},
  973. {"inproxy_webrtc_randomize_dtls", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  974. {"inproxy_webrtc_padded_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  975. {"inproxy_webrtc_padded_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  976. {"inproxy_webrtc_decoy_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  977. {"inproxy_webrtc_decoy_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  978. {"inproxy_webrtc_local_ice_candidate_type", isAnyString, requestParamOptional},
  979. {"inproxy_webrtc_local_ice_candidate_is_initiator", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  980. {"inproxy_webrtc_local_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  981. {"inproxy_webrtc_local_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  982. {"inproxy_webrtc_remote_ice_candidate_type", isAnyString, requestParamOptional},
  983. {"inproxy_webrtc_remote_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  984. {"inproxy_webrtc_remote_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  985. }
  986. // baseSessionAndDialParams adds baseDialParams and inproxyDialParams to baseSessionParams.
  987. var baseSessionAndDialParams = append(
  988. append(
  989. append(
  990. []requestParamSpec{},
  991. baseSessionParams...),
  992. baseDialParams...),
  993. inproxyDialParams...)
  994. func validateRequestParams(
  995. config *Config,
  996. params common.APIParameters,
  997. expectedParams []requestParamSpec) error {
  998. for _, expectedParam := range expectedParams {
  999. value := params[expectedParam.name]
  1000. if value == nil {
  1001. if expectedParam.flags&requestParamOptional != 0 {
  1002. continue
  1003. }
  1004. return errors.Tracef("missing param: %s", expectedParam.name)
  1005. }
  1006. var err error
  1007. switch {
  1008. case expectedParam.flags&requestParamArray != 0:
  1009. err = validateStringArrayRequestParam(config, expectedParam, value)
  1010. case expectedParam.flags&requestParamJSON != 0:
  1011. // No validation: the JSON already unmarshalled; the parameter
  1012. // user will validate that the JSON contains the expected
  1013. // objects/data.
  1014. // TODO: without validation, any valid JSON will be logged
  1015. // by getRequestLogFields, even if the parameter user validates
  1016. // and rejects the parameter.
  1017. default:
  1018. err = validateStringRequestParam(config, expectedParam, value)
  1019. }
  1020. if err != nil {
  1021. return errors.Trace(err)
  1022. }
  1023. }
  1024. return nil
  1025. }
  1026. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  1027. // the baseSessionAndDialParams.
  1028. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  1029. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  1030. // scalar types (int, string, etc.)
  1031. paramsCopy := make(common.APIParameters)
  1032. for _, baseParam := range baseSessionAndDialParams {
  1033. value := params[baseParam.name]
  1034. if value == nil {
  1035. continue
  1036. }
  1037. paramsCopy[baseParam.name] = value
  1038. }
  1039. return paramsCopy
  1040. }
  1041. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  1042. // Note: not a deep copy
  1043. paramsCopy := make(common.APIParameters)
  1044. for _, name := range updateOnConnectedParamNames {
  1045. value := params[name]
  1046. if value == nil {
  1047. continue
  1048. }
  1049. paramsCopy[name] = value
  1050. }
  1051. return paramsCopy
  1052. }
  1053. func validateStringRequestParam(
  1054. config *Config,
  1055. expectedParam requestParamSpec,
  1056. value interface{}) error {
  1057. strValue, ok := value.(string)
  1058. if !ok {
  1059. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  1060. }
  1061. if !expectedParam.validator(config, strValue) {
  1062. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  1063. }
  1064. return nil
  1065. }
  1066. func validateStringArrayRequestParam(
  1067. config *Config,
  1068. expectedParam requestParamSpec,
  1069. value interface{}) error {
  1070. arrayValue, ok := value.([]interface{})
  1071. if !ok {
  1072. return errors.Tracef("unexpected array param type: %s", expectedParam.name)
  1073. }
  1074. for _, value := range arrayValue {
  1075. err := validateStringRequestParam(config, expectedParam, value)
  1076. if err != nil {
  1077. return errors.Trace(err)
  1078. }
  1079. }
  1080. return nil
  1081. }
  1082. // getRequestLogFields makes LogFields to log the API event following
  1083. // the legacy psi_web and current ELK naming conventions.
  1084. func getRequestLogFields(
  1085. eventName string,
  1086. geoIPData GeoIPData,
  1087. authorizedAccessTypes []string,
  1088. params common.APIParameters,
  1089. expectedParams []requestParamSpec) LogFields {
  1090. logFields := make(LogFields)
  1091. if eventName != "" {
  1092. logFields["event_name"] = eventName
  1093. }
  1094. geoIPData.SetClientLogFields(logFields)
  1095. if len(authorizedAccessTypes) > 0 {
  1096. logFields["authorized_access_types"] = authorizedAccessTypes
  1097. }
  1098. if params == nil {
  1099. return logFields
  1100. }
  1101. for _, expectedParam := range expectedParams {
  1102. if expectedParam.flags&requestParamNotLogged != 0 {
  1103. continue
  1104. }
  1105. var tunnelProtocol string
  1106. if value, ok := params["relay_protocol"]; ok {
  1107. tunnelProtocol, _ = value.(string)
  1108. }
  1109. if expectedParam.flags&requestParamLogOnlyForFrontedMeekOrConjure != 0 &&
  1110. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) &&
  1111. !protocol.TunnelProtocolUsesConjure(tunnelProtocol) {
  1112. continue
  1113. }
  1114. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  1115. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  1116. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  1117. // Non-HTTP unfronted meek protocols never tranform the host header.
  1118. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  1119. continue
  1120. }
  1121. var transformedHostName string
  1122. if value, ok := params["meek_transformed_host_name"]; ok {
  1123. transformedHostName, _ = value.(string)
  1124. }
  1125. if transformedHostName != "1" {
  1126. continue
  1127. }
  1128. }
  1129. value := params[expectedParam.name]
  1130. if value == nil {
  1131. // Special case: older clients don't send this value,
  1132. // so log a default.
  1133. if expectedParam.name == "tunnel_whole_device" {
  1134. value = "0"
  1135. } else {
  1136. // Skip omitted, optional params
  1137. continue
  1138. }
  1139. }
  1140. switch v := value.(type) {
  1141. case string:
  1142. strValue := v
  1143. // Special cases:
  1144. // - Number fields are encoded as integer types.
  1145. // - For ELK performance we record certain domain-or-IP
  1146. // fields as one of two different values based on type;
  1147. // we also omit port from these host:port fields for now.
  1148. // - Boolean fields that come into the api as "1"/"0"
  1149. // must be logged as actual boolean values
  1150. switch expectedParam.name {
  1151. case "meek_dial_address":
  1152. host, _, _ := net.SplitHostPort(strValue)
  1153. if isIPAddress(nil, host) {
  1154. logFields["meek_dial_ip_address"] = host
  1155. } else {
  1156. logFields["meek_dial_domain"] = host
  1157. }
  1158. case "upstream_proxy_type":
  1159. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  1160. logFields[expectedParam.name] = strings.ToLower(strValue)
  1161. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  1162. // Due to a client bug, clients may deliever an incorrect ""
  1163. // value for speed_test_samples via the web API protocol. Omit
  1164. // the field in this case.
  1165. case "tunnel_error":
  1166. // net/url.Error, returned from net/url.Parse, contains the original input
  1167. // URL, which may contain PII. New clients strip this out by using
  1168. // common.SafeParseURL. Legacy clients will still send the full error
  1169. // message, so strip it out here. The target substring should be unique to
  1170. // legacy clients.
  1171. target := "upstreamproxy error: proxyURI url.Parse: parse "
  1172. index := strings.Index(strValue, target)
  1173. if index != -1 {
  1174. strValue = strValue[:index+len(target)] + "<redacted>"
  1175. }
  1176. logFields[expectedParam.name] = strValue
  1177. default:
  1178. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  1179. intValue, _ := strconv.Atoi(strValue)
  1180. logFields[expectedParam.name] = intValue
  1181. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  1182. floatValue, _ := strconv.ParseFloat(strValue, 64)
  1183. logFields[expectedParam.name] = floatValue
  1184. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  1185. logFields[expectedParam.name] = len(strValue)
  1186. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  1187. // Submitted value could be "0" or "1"
  1188. // "0" and non "0"/"1" values should be transformed to false
  1189. // "1" should be transformed to true
  1190. if strValue == "1" {
  1191. logFields[expectedParam.name] = true
  1192. } else {
  1193. logFields[expectedParam.name] = false
  1194. }
  1195. } else {
  1196. logFields[expectedParam.name] = strValue
  1197. }
  1198. }
  1199. case []interface{}:
  1200. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  1201. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  1202. } else {
  1203. logFields[expectedParam.name] = v
  1204. }
  1205. default:
  1206. logFields[expectedParam.name] = v
  1207. }
  1208. }
  1209. return logFields
  1210. }
  1211. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  1212. // fields to more verbose names for metrics.
  1213. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  1214. // TODO: use reflection and add additional tags, e.g.,
  1215. // `json:"s" log:"timestamp"` to remove hard-coded
  1216. // tag value dependency?
  1217. logSamples := make([]interface{}, len(samples))
  1218. for i, sample := range samples {
  1219. logSample := make(map[string]interface{})
  1220. if m, ok := sample.(map[string]interface{}); ok {
  1221. for k, v := range m {
  1222. logK := k
  1223. switch k {
  1224. case "s":
  1225. logK = "timestamp"
  1226. case "r":
  1227. logK = "server_region"
  1228. case "p":
  1229. logK = "relay_protocol"
  1230. case "t":
  1231. logK = "round_trip_time_ms"
  1232. case "u":
  1233. logK = "bytes_up"
  1234. case "d":
  1235. logK = "bytes_down"
  1236. }
  1237. logSample[logK] = v
  1238. }
  1239. }
  1240. logSamples[i] = logSample
  1241. }
  1242. return logSamples
  1243. }
  1244. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  1245. if params[name] == nil {
  1246. return "", false
  1247. }
  1248. value, ok := params[name].(string)
  1249. if !ok {
  1250. return "", false
  1251. }
  1252. return value, true
  1253. }
  1254. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  1255. if params[name] == nil {
  1256. return "", errors.Tracef("missing param: %s", name)
  1257. }
  1258. value, ok := params[name].(string)
  1259. if !ok {
  1260. return "", errors.Tracef("invalid param: %s", name)
  1261. }
  1262. return value, nil
  1263. }
  1264. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1265. if params[name] == nil {
  1266. return 0, errors.Tracef("missing param: %s", name)
  1267. }
  1268. valueStr, ok := params[name].(string)
  1269. if !ok {
  1270. return 0, errors.Tracef("invalid param: %s", name)
  1271. }
  1272. value, err := strconv.Atoi(valueStr)
  1273. if !ok {
  1274. return 0, errors.Trace(err)
  1275. }
  1276. return value, nil
  1277. }
  1278. func getBoolStringRequestParam(params common.APIParameters, name string) (bool, error) {
  1279. if params[name] == nil {
  1280. return false, errors.Tracef("missing param: %s", name)
  1281. }
  1282. valueStr, ok := params[name].(string)
  1283. if !ok {
  1284. return false, errors.Tracef("invalid param: %s", name)
  1285. }
  1286. if valueStr == "1" {
  1287. return true, nil
  1288. }
  1289. return false, nil
  1290. }
  1291. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1292. value, err := getIntStringRequestParam(params, name)
  1293. if err != nil {
  1294. return 0, errors.Trace(err)
  1295. }
  1296. if value < 0 {
  1297. value = 0
  1298. }
  1299. if value > PADDING_MAX_BYTES {
  1300. value = PADDING_MAX_BYTES
  1301. }
  1302. return int(value), nil
  1303. }
  1304. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1305. if params[name] == nil {
  1306. return nil, errors.Tracef("missing param: %s", name)
  1307. }
  1308. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1309. value, ok := params[name].(map[string]interface{})
  1310. if !ok {
  1311. return nil, errors.Tracef("invalid param: %s", name)
  1312. }
  1313. return common.APIParameters(value), nil
  1314. }
  1315. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1316. if params[name] == nil {
  1317. return nil, errors.Tracef("missing param: %s", name)
  1318. }
  1319. value, ok := params[name].([]interface{})
  1320. if !ok {
  1321. return nil, errors.Tracef("invalid param: %s", name)
  1322. }
  1323. result := make([]common.APIParameters, len(value))
  1324. for i, item := range value {
  1325. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1326. resultItem, ok := item.(map[string]interface{})
  1327. if !ok {
  1328. return nil, errors.Tracef("invalid param: %s", name)
  1329. }
  1330. result[i] = common.APIParameters(resultItem)
  1331. }
  1332. return result, nil
  1333. }
  1334. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1335. if params[name] == nil {
  1336. return nil, errors.Tracef("missing param: %s", name)
  1337. }
  1338. // TODO: can't use common.APIParameters type?
  1339. value, ok := params[name].(map[string]interface{})
  1340. if !ok {
  1341. return nil, errors.Tracef("invalid param: %s", name)
  1342. }
  1343. result := make(map[string]int64)
  1344. for k, v := range value {
  1345. numValue, ok := v.(float64)
  1346. if !ok {
  1347. return nil, errors.Tracef("invalid param: %s", name)
  1348. }
  1349. result[k] = int64(numValue)
  1350. }
  1351. return result, nil
  1352. }
  1353. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1354. if params[name] == nil {
  1355. return nil, errors.Tracef("missing param: %s", name)
  1356. }
  1357. switch value := params[name].(type) {
  1358. case []string:
  1359. return value, nil
  1360. case []interface{}:
  1361. // JSON unmarshaling may decode the parameter as []interface{}.
  1362. result := make([]string, len(value))
  1363. for i, v := range value {
  1364. strValue, ok := v.(string)
  1365. if !ok {
  1366. return nil, errors.Tracef("invalid param: %s", name)
  1367. }
  1368. result[i] = strValue
  1369. }
  1370. return result, nil
  1371. default:
  1372. return nil, errors.Tracef("invalid param: %s", name)
  1373. }
  1374. }
  1375. // Normalize reported client platform. Android clients, for example, report
  1376. // OS version, rooted status, and Google Play build status in the clientPlatform
  1377. // string along with "Android".
  1378. func normalizeClientPlatform(clientPlatform string) string {
  1379. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1380. return CLIENT_PLATFORM_ANDROID
  1381. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1382. return CLIENT_PLATFORM_IOS
  1383. }
  1384. return CLIENT_PLATFORM_WINDOWS
  1385. }
  1386. func isAnyString(config *Config, value string) bool {
  1387. return true
  1388. }
  1389. func isMobileClientPlatform(clientPlatform string) bool {
  1390. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1391. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1392. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1393. }
  1394. // Input validators follow the legacy validations rules in psi_web.
  1395. func isHexDigits(_ *Config, value string) bool {
  1396. // Allows both uppercase in addition to lowercase, for legacy support.
  1397. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1398. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1399. })
  1400. }
  1401. func isBase64String(_ *Config, value string) bool {
  1402. _, err := base64.StdEncoding.DecodeString(value)
  1403. return err == nil
  1404. }
  1405. func isUnpaddedBase64String(_ *Config, value string) bool {
  1406. _, err := base64.RawStdEncoding.DecodeString(value)
  1407. return err == nil
  1408. }
  1409. func isDigits(_ *Config, value string) bool {
  1410. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1411. return c < '0' || c > '9'
  1412. })
  1413. }
  1414. func isIntString(_ *Config, value string) bool {
  1415. _, err := strconv.Atoi(value)
  1416. return err == nil
  1417. }
  1418. func isFloatString(_ *Config, value string) bool {
  1419. _, err := strconv.ParseFloat(value, 64)
  1420. return err == nil
  1421. }
  1422. func isClientPlatform(_ *Config, value string) bool {
  1423. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1424. // Note: stricter than psi_web's Python string.whitespace
  1425. return unicode.Is(unicode.White_Space, c)
  1426. })
  1427. }
  1428. func isRelayProtocol(_ *Config, value string) bool {
  1429. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1430. }
  1431. func isBooleanFlag(_ *Config, value string) bool {
  1432. return value == "0" || value == "1"
  1433. }
  1434. func isUpstreamProxyType(_ *Config, value string) bool {
  1435. value = strings.ToLower(value)
  1436. return value == "http" || value == "socks5" || value == "socks4a"
  1437. }
  1438. func isRegionCode(_ *Config, value string) bool {
  1439. if len(value) != 2 {
  1440. return false
  1441. }
  1442. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1443. return c < 'A' || c > 'Z'
  1444. })
  1445. }
  1446. func isDialAddress(_ *Config, value string) bool {
  1447. // "<host>:<port>", where <host> is a domain or IP address
  1448. parts := strings.Split(value, ":")
  1449. if len(parts) != 2 {
  1450. return false
  1451. }
  1452. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1453. return false
  1454. }
  1455. if !isDigits(nil, parts[1]) {
  1456. return false
  1457. }
  1458. _, err := strconv.Atoi(parts[1])
  1459. if err != nil {
  1460. return false
  1461. }
  1462. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1463. return true
  1464. }
  1465. func isIPAddress(_ *Config, value string) bool {
  1466. return net.ParseIP(value) != nil
  1467. }
  1468. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1469. func isDomain(_ *Config, value string) bool {
  1470. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1471. //
  1472. // "ensures that each segment
  1473. // * contains at least one character and a maximum of 63 characters
  1474. // * consists only of allowed characters
  1475. // * doesn't begin or end with a hyphen"
  1476. //
  1477. if len(value) > 255 {
  1478. return false
  1479. }
  1480. value = strings.TrimSuffix(value, ".")
  1481. for _, part := range strings.Split(value, ".") {
  1482. // Note: regexp doesn't support the following Perl expression which
  1483. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1484. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1485. return false
  1486. }
  1487. if !isDomainRegex.Match([]byte(part)) {
  1488. return false
  1489. }
  1490. }
  1491. return true
  1492. }
  1493. func isHostHeader(_ *Config, value string) bool {
  1494. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1495. if strings.Contains(value, ":") {
  1496. return isDialAddress(nil, value)
  1497. }
  1498. return isIPAddress(nil, value) || isDomain(nil, value)
  1499. }
  1500. func isServerEntrySource(_ *Config, value string) bool {
  1501. return common.Contains(protocol.SupportedServerEntrySources, value)
  1502. }
  1503. var isISO8601DateRegex = regexp.MustCompile(
  1504. `(?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})))`)
  1505. func isISO8601Date(_ *Config, value string) bool {
  1506. return isISO8601DateRegex.Match([]byte(value))
  1507. }
  1508. func isLastConnected(_ *Config, value string) bool {
  1509. return value == "None" || isISO8601Date(nil, value)
  1510. }
  1511. const geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
  1512. func isGeoHashString(_ *Config, value string) bool {
  1513. // Verify that the string is between 1 and 12 characters long
  1514. // and contains only characters from the geohash alphabet.
  1515. if len(value) < 1 || len(value) > 12 {
  1516. return false
  1517. }
  1518. for _, c := range value {
  1519. if strings.Index(geohashAlphabet, string(c)) == -1 {
  1520. return false
  1521. }
  1522. }
  1523. return true
  1524. }