api.go 69 KB

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