api.go 70 KB

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