api.go 61 KB

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