api.go 66 KB

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