api.go 64 KB

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