api.go 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043
  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. SPONSOR_ID_LENGTH = 16
  45. )
  46. // sshAPIRequestHandler routes Psiphon API requests transported as
  47. // JSON objects via the SSH request mechanism.
  48. //
  49. // The API request parameters and event log values follow the legacy
  50. // psi_web protocol and naming conventions. The API is compatible with
  51. // all tunnel-core clients but are not backwards compatible with all
  52. // legacy clients.
  53. func sshAPIRequestHandler(
  54. support *SupportServices,
  55. sshClient *sshClient,
  56. name string,
  57. requestPayload []byte) ([]byte, error) {
  58. // Before invoking the handlers, enforce some preconditions:
  59. //
  60. // - A handshake request must precede any other requests.
  61. // - When the handshake results in a traffic rules state where
  62. // the client is immediately exhausted, no requests
  63. // may succeed. This case ensures that blocked clients do
  64. // not log "connected", etc.
  65. //
  66. // Only one handshake request may be made. There is no check here
  67. // to enforce that handshakeAPIRequestHandler will be called at
  68. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  69. // enforces that only a single handshake is made; enforcing that there
  70. // ensures no race condition even if concurrent requests are
  71. // in flight.
  72. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  73. completed, exhausted := sshClient.getHandshaked()
  74. if !completed {
  75. return nil, errors.TraceNew("handshake not completed")
  76. }
  77. if exhausted {
  78. return nil, errors.TraceNew("exhausted after handshake")
  79. }
  80. }
  81. // Here, the DSL request is and opaque payload. The DSL backend (or relay)
  82. // will handle the API parameters and this case skips APIParameters
  83. // processing.
  84. if name == protocol.PSIPHON_API_DSL_REQUEST_NAME {
  85. responsePayload, err := dslAPIRequestHandler(
  86. support, sshClient, requestPayload)
  87. return responsePayload, errors.Trace(err)
  88. }
  89. // Notes:
  90. //
  91. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  92. // by max SSH request packet size.
  93. //
  94. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  95. // array of base64-encoded strings; the base64 representation should
  96. // not be decoded to []byte values. The default behavior of
  97. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  98. // type map[string]interface{} will unmarshal a base64-encoded string
  99. // to a string, not a decoded []byte, as required.
  100. var params common.APIParameters
  101. // The request payload is either packed CBOR or legacy JSON.
  102. params, isPacked, err := protocol.GetPackedAPIParametersRequestPayload(requestPayload)
  103. if err != nil {
  104. return nil, errors.Tracef(
  105. "invalid packed payload for request name: %s: %s", name, err)
  106. }
  107. if !isPacked {
  108. err := json.Unmarshal(requestPayload, &params)
  109. if err != nil {
  110. return nil, errors.Tracef(
  111. "invalid payload for request name: %s: %s", name, err)
  112. }
  113. }
  114. switch name {
  115. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  116. responsePayload, err := handshakeAPIRequestHandler(
  117. support, protocol.PSIPHON_API_PROTOCOL_SSH, sshClient, params)
  118. if err != nil {
  119. // Handshake failed, disconnect the client.
  120. sshClient.stop()
  121. return nil, errors.Trace(err)
  122. }
  123. return responsePayload, nil
  124. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  125. responsePayload, err := connectedAPIRequestHandler(
  126. support, sshClient, params)
  127. return responsePayload, errors.Trace(err)
  128. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  129. responsePayload, err := statusAPIRequestHandler(
  130. support, sshClient, params)
  131. return responsePayload, errors.Trace(err)
  132. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  133. responsePayload, err := clientVerificationAPIRequestHandler(
  134. support, sshClient, params)
  135. return responsePayload, errors.Trace(err)
  136. }
  137. return nil, errors.Tracef("invalid request name: %s", name)
  138. }
  139. var handshakeRequestParams = append(
  140. append(
  141. []requestParamSpec{
  142. {"missing_server_entry_signature", isBase64String, requestParamOptional},
  143. {"missing_server_entry_provider_id", isBase64String, requestParamOptional},
  144. },
  145. baseAndDialParams...),
  146. tacticsParams...)
  147. // handshakeAPIRequestHandler implements the "handshake" API request.
  148. // Clients make the handshake immediately after establishing a tunnel
  149. // connection; the response tells the client what homepage to open, what
  150. // stats to record, etc.
  151. func handshakeAPIRequestHandler(
  152. support *SupportServices,
  153. apiProtocol string,
  154. sshClient *sshClient,
  155. params common.APIParameters) ([]byte, error) {
  156. var clientGeoIPData GeoIPData
  157. var inproxyClientIP string
  158. var inproxyProxyID inproxy.ID
  159. var inproxyMatchedPersonalCompartments bool
  160. var inproxyClientGeoIPData GeoIPData
  161. var inproxyRelayLogFields common.LogFields
  162. if sshClient.isInproxyTunnelProtocol {
  163. inproxyConnectionID, err := getStringRequestParam(params, "inproxy_connection_id")
  164. if err != nil {
  165. return nil, errors.Trace(err)
  166. }
  167. // Complete the in-proxy broker/server relay before the rest of
  168. // handshake in order to obtain the original client IP and other
  169. // inputs sent from the broker.
  170. //
  171. // In the best and typical case, the broker has already established a
  172. // secure session with this server and the inproxy_relay_packet is
  173. // the broker report application-level payload. Otherwise, if there
  174. // is no session or the session has expired, session handshake
  175. // messages will be relayed to the broker via the client, using SSH
  176. // requests to the client. These requests/responses happen while the
  177. // handshake response remains outstanding, as this handler needs the
  178. // original client IP and its geolocation data in order to determine
  179. // the correct landing pages, traffic rules, tactics, etc.
  180. //
  181. // The client should extends its handshake timeout to accommodate
  182. // potential relay round trips.
  183. inproxyRelayPacketStr, err := getStringRequestParam(params, "inproxy_relay_packet")
  184. if err != nil {
  185. return nil, errors.Trace(err)
  186. }
  187. inproxyRelayPacket, err := base64.RawStdEncoding.DecodeString(inproxyRelayPacketStr)
  188. if err != nil {
  189. return nil, errors.Trace(err)
  190. }
  191. inproxyClientIP,
  192. inproxyProxyID,
  193. inproxyMatchedPersonalCompartments,
  194. inproxyRelayLogFields,
  195. err =
  196. doHandshakeInproxyBrokerRelay(
  197. sshClient,
  198. inproxyConnectionID,
  199. inproxyRelayPacket)
  200. if err != nil {
  201. return nil, errors.Trace(err)
  202. }
  203. if net.ParseIP(inproxyClientIP) == nil {
  204. return nil, errors.TraceNew("invalid inproxy client IP")
  205. }
  206. inproxyClientGeoIPData = support.GeoIPService.Lookup(inproxyClientIP)
  207. clientGeoIPData = inproxyClientGeoIPData
  208. } else {
  209. clientGeoIPData = sshClient.getClientGeoIPData()
  210. }
  211. // Check input parameters
  212. // Note: ignoring legacy "known_servers" params
  213. err := validateRequestParams(params, handshakeRequestParams)
  214. if err != nil {
  215. return nil, errors.Trace(err)
  216. }
  217. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  218. clientVersion, _ := getStringRequestParam(params, "client_version")
  219. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  220. isMobile := isMobileClientPlatform(clientPlatform)
  221. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  222. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  223. // the client, a value of 0 will be used.
  224. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  225. var authorizations []string
  226. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  227. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  228. if err != nil {
  229. return nil, errors.Trace(err)
  230. }
  231. }
  232. deviceRegion, ok := getOptionalStringRequestParam(params, "device_region")
  233. if !ok {
  234. deviceRegion = GEOIP_UNKNOWN_VALUE
  235. }
  236. // splitTunnelOwnRegion indicates if the client is requesting split tunnel
  237. // mode to be applied to the client's own country. When omitted by the
  238. // client, the value will be false.
  239. //
  240. // When split_tunnel_regions is non-empty, split tunnel mode will be
  241. // applied for the specified country codes. When omitted by the client,
  242. // the value will be an empty slice.
  243. splitTunnelOwnRegion, _ := getBoolStringRequestParam(params, "split_tunnel")
  244. splitTunnelOtherRegions, _ := getStringArrayRequestParam(params, "split_tunnel_regions")
  245. ownRegion := ""
  246. if splitTunnelOwnRegion {
  247. ownRegion = clientGeoIPData.Country
  248. }
  249. var splitTunnelLookup *splitTunnelLookup
  250. if ownRegion != "" || len(splitTunnelOtherRegions) > 0 {
  251. splitTunnelLookup, err = newSplitTunnelLookup(ownRegion, splitTunnelOtherRegions)
  252. if err != nil {
  253. return nil, errors.Trace(err)
  254. }
  255. }
  256. // Note: no guarantee that PsinetDatabase won't reload between database calls
  257. db := support.PsinetDatabase
  258. httpsRequestRegexes, domainBytesChecksum := db.GetHttpsRequestRegexes(sponsorID)
  259. // When compressed tactics are requested, use CBOR binary encoding for the
  260. // response.
  261. var responseMarshaler func(any) ([]byte, error)
  262. responseMarshaler = json.Marshal
  263. compressTactics := protocol.GetCompressTactics(params)
  264. if compressTactics {
  265. responseMarshaler = protocol.CBOREncoding.Marshal
  266. }
  267. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  268. common.GeoIPData(clientGeoIPData), params, compressTactics)
  269. if err != nil {
  270. return nil, errors.Trace(err)
  271. }
  272. var newTacticsTag string
  273. if tacticsPayload != nil && len(tacticsPayload.Tactics) > 0 {
  274. newTacticsTag = tacticsPayload.Tag
  275. }
  276. // Flag the SSH client as having completed its handshake. This
  277. // may reselect traffic rules and starts allowing port forwards.
  278. apiParams := copyBaseAndDialParams(params)
  279. handshakeStateInfo, err := sshClient.setHandshakeState(
  280. handshakeState{
  281. completed: true,
  282. apiProtocol: apiProtocol,
  283. apiParams: apiParams,
  284. domainBytesChecksum: domainBytesChecksum,
  285. establishedTunnelsCount: establishedTunnelsCount,
  286. splitTunnelLookup: splitTunnelLookup,
  287. deviceRegion: deviceRegion,
  288. newTacticsTag: newTacticsTag,
  289. inproxyClientIP: inproxyClientIP,
  290. inproxyClientGeoIPData: inproxyClientGeoIPData,
  291. inproxyProxyID: inproxyProxyID,
  292. inproxyMatchedPersonal: inproxyMatchedPersonalCompartments,
  293. inproxyRelayLogFields: inproxyRelayLogFields,
  294. },
  295. authorizations)
  296. if err != nil {
  297. return nil, errors.Trace(err)
  298. }
  299. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  300. // the state change (for example, if a second handshake is performed)
  301. //
  302. // The handshake event is no longer shipped to log consumers, so this is
  303. // simply a diagnostic log. Since the "server_tunnel" event includes all
  304. // common API parameters and "handshake_completed" flag, this handshake
  305. // log is mostly redundant and set to debug level.
  306. if IsLogLevelDebug() {
  307. logFields := getRequestLogFields(
  308. "",
  309. "",
  310. sshClient.sessionID,
  311. clientGeoIPData,
  312. handshakeStateInfo.authorizedAccessTypes,
  313. params,
  314. handshakeRequestParams)
  315. log.WithTraceFields(logFields).Debug("handshake")
  316. }
  317. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  318. // TODO: as a future enhancement, use the packed, CBOR encoding --
  319. // protocol.EncodePackedServerEntryFields -- for server entries.
  320. // Discover new servers
  321. var encodedServerList []string
  322. if !sshClient.getDisableDiscovery() {
  323. encodedServerList = support.discovery.DiscoverServers(
  324. net.ParseIP(sshClient.getClientIP()))
  325. }
  326. // When the client indicates that it used an out-of-date server entry for
  327. // this connection, return a signed copy of the server entry for the client
  328. // to upgrade to. Out-of-date server entries are either unsigned or missing
  329. // a provider ID. See also: comment in psiphon.doHandshakeRequest.
  330. //
  331. // The missing_server_entry_signature parameter value is a server entry tag,
  332. // which is used to select the correct server entry for servers with multiple
  333. // entries. Identifying the server entries tags instead of server IPs prevents
  334. // an enumeration attack, where a malicious client can abuse this facilty to
  335. // check if an arbitrary IP address is a Psiphon server.
  336. //
  337. // The missing_server_entry_provider_id parameter value is a server entry
  338. // tag.
  339. serverEntryTag, ok := getOptionalStringRequestParam(
  340. params, "missing_server_entry_signature")
  341. if !ok {
  342. // Do not need to check this case if we'll already return the server
  343. // entry due to a missing signature.
  344. serverEntryTag, ok = getOptionalStringRequestParam(
  345. params, "missing_server_entry_provider_id")
  346. }
  347. if ok {
  348. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  349. if ok {
  350. encodedServerList = append(encodedServerList, ownServerEntry)
  351. }
  352. }
  353. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  354. // the JSON response, return an empty array instead of null for legacy
  355. // clients.
  356. homepages := db.GetRandomizedHomepages(
  357. sponsorID,
  358. clientGeoIPData.Country,
  359. clientGeoIPData.ASN,
  360. deviceRegion,
  361. isMobile)
  362. clientAddress := ""
  363. if protocol.TunnelProtocolIsDirect(sshClient.tunnelProtocol) {
  364. clientAddress = sshClient.peerAddr.String()
  365. } else {
  366. // Limitations for indirect protocols:
  367. //
  368. // - The peer port number will not correspond to the original client's
  369. // source port; 0 is reported instead.
  370. //
  371. // - For in-proxy protocols, while we assume that the the original
  372. // client IP from the broker is representative for geolocation, an
  373. // actual direct connection to the Psiphon server from the client
  374. // may route differently and use a different IP address.
  375. clientAddress = net.JoinHostPort(sshClient.getClientIP(), "0")
  376. }
  377. var marshaledTacticsPayload []byte
  378. if tacticsPayload != nil {
  379. marshaledTacticsPayload, err = responseMarshaler(tacticsPayload)
  380. if err != nil {
  381. return nil, errors.Trace(err)
  382. }
  383. }
  384. handshakeResponse := protocol.HandshakeResponse{
  385. Homepages: homepages,
  386. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  387. PageViewRegexes: make([]map[string]string, 0),
  388. HttpsRequestRegexes: httpsRequestRegexes,
  389. EncodedServerList: encodedServerList,
  390. ClientRegion: clientGeoIPData.Country,
  391. ClientAddress: clientAddress,
  392. ServerTimestamp: common.GetCurrentTimestamp(),
  393. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  394. TacticsPayload: marshaledTacticsPayload,
  395. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  396. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  397. SteeringIP: handshakeStateInfo.steeringIP,
  398. Padding: strings.Repeat(" ", pad_response),
  399. }
  400. responsePayload, err := responseMarshaler(handshakeResponse)
  401. if err != nil {
  402. return nil, errors.Trace(err)
  403. }
  404. return responsePayload, nil
  405. }
  406. func doHandshakeInproxyBrokerRelay(
  407. sshClient *sshClient,
  408. clientConnectionID string,
  409. initialRelayPacket []byte) (string, inproxy.ID, bool, common.LogFields, error) {
  410. connectionID, err := inproxy.IDFromString(clientConnectionID)
  411. if err != nil {
  412. return "", inproxy.ID{}, false, nil, errors.Trace(err)
  413. }
  414. clientIP := ""
  415. var proxyID inproxy.ID
  416. var matchedPersonalCompartments bool
  417. var logFields common.LogFields
  418. // This first packet from broker arrives via the client handshake. If
  419. // there is an established, non-expired session, this packet will contain
  420. // the application-level broker report and the relay will complete
  421. // immediately.
  422. relayPacket := initialRelayPacket
  423. for i := 0; i < inproxy.MaxRelayRoundTrips; i++ {
  424. // broker -> server
  425. relayPacket, err = sshClient.sshServer.inproxyBrokerSessions.HandlePacket(
  426. CommonLogger(log),
  427. relayPacket,
  428. connectionID,
  429. func(
  430. brokerVerifiedOriginalClientIP string,
  431. brokerReportedProxyID inproxy.ID,
  432. brokerMatchedPersonalCompartments bool,
  433. fields common.LogFields) {
  434. // Once the broker report is received, this callback is invoked.
  435. clientIP = brokerVerifiedOriginalClientIP
  436. proxyID = brokerReportedProxyID
  437. matchedPersonalCompartments = brokerMatchedPersonalCompartments
  438. logFields = fields
  439. })
  440. if err != nil {
  441. if relayPacket == nil {
  442. // If there is an error and no relay packet, the packet is
  443. // invalid. Drop the packet and return an error. Do _not_
  444. // reset the session, otherwise a malicious client could
  445. // interrupt a valid broker/server session with a malformed packet.
  446. return "", inproxy.ID{}, false, nil, errors.Trace(err)
  447. }
  448. // In the case of expired sessions, a reset session token is sent
  449. // to the broker, so this is not a failure condition; the error
  450. // is for logging only. Continue to ship relayPacket.
  451. log.WithTraceFields(LogFields{"error": err}).Warning(
  452. "HandlePacket returned packet and error")
  453. }
  454. if relayPacket == nil {
  455. // The relay is complete; the handler recording the clientIP and
  456. // logFields was invoked.
  457. return clientIP, proxyID, matchedPersonalCompartments, logFields, nil
  458. }
  459. // server -> broker
  460. // Send an SSH request back to client with next packet for broker;
  461. // then the client relays that to the broker and returns the broker's
  462. // next response in the SSH response.
  463. request := protocol.InproxyRelayRequest{
  464. Packet: relayPacket,
  465. }
  466. requestPayload, err := protocol.CBOREncoding.Marshal(request)
  467. if err != nil {
  468. return "", inproxy.ID{}, false, nil, errors.Trace(err)
  469. }
  470. ok, responsePayload, err := sshClient.sshConn.SendRequest(
  471. protocol.PSIPHON_API_INPROXY_RELAY_REQUEST_NAME,
  472. true,
  473. requestPayload)
  474. if err != nil {
  475. return "", inproxy.ID{}, false, nil, errors.Trace(err)
  476. }
  477. if !ok {
  478. return "", inproxy.ID{}, false, nil, errors.TraceNew("client rejected request")
  479. }
  480. var response protocol.InproxyRelayResponse
  481. err = cbor.Unmarshal(responsePayload, &response)
  482. if err != nil {
  483. return "", inproxy.ID{}, false, nil, errors.Trace(err)
  484. }
  485. relayPacket = response.Packet
  486. }
  487. return "", inproxy.ID{}, false, nil, errors.Tracef(
  488. "exceeded %d relay round trips", inproxy.MaxRelayRoundTrips)
  489. }
  490. // uniqueUserParams are the connected request parameters which are logged for
  491. // unique_user events.
  492. var uniqueUserParams = append(
  493. []requestParamSpec{
  494. {"last_connected", isLastConnected, 0}},
  495. baseParams...)
  496. var connectedRequestParams = append(
  497. []requestParamSpec{
  498. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  499. uniqueUserParams...)
  500. // updateOnConnectedParamNames are connected request parameters which are
  501. // copied to update data logged with server_tunnel: these fields either only
  502. // ship with or ship newer data with connected requests.
  503. var updateOnConnectedParamNames = append(
  504. []string{
  505. "last_connected",
  506. "establishment_duration",
  507. },
  508. fragmentor.GetUpstreamMetricsNames()...)
  509. // connectedAPIRequestHandler implements the "connected" API request. Clients
  510. // make the connected request once a tunnel connection has been established
  511. // and at least once per 24h for long-running tunnels. The last_connected
  512. // input value, which should be a connected_timestamp output from a previous
  513. // connected response, is used to calculate unique user stats.
  514. // connected_timestamp is truncated as a privacy measure.
  515. func connectedAPIRequestHandler(
  516. support *SupportServices,
  517. sshClient *sshClient,
  518. params common.APIParameters) ([]byte, error) {
  519. err := validateRequestParams(params, connectedRequestParams)
  520. if err != nil {
  521. return nil, errors.Trace(err)
  522. }
  523. // Note: unlock before use is only safe as long as referenced sshClient data,
  524. // such as slices in handshakeState, is read-only after initially set.
  525. sshClient.Lock()
  526. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  527. sshClient.Unlock()
  528. lastConnected, _ := getStringRequestParam(params, "last_connected")
  529. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  530. // client may have performed more upstream fragmentation since the previous
  531. // metrics reported by the handshake request. Also, additional fields that
  532. // are reported only in the connected request are added to server_tunnel
  533. // here.
  534. sshClient.updateAPIParameters(copyUpdateOnConnectedParams(params))
  535. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  536. // The finest required granularity for unique users is daily. To save space,
  537. // only record a "unique_user" log event when the client's last_connected is
  538. // in the previous day relative to the new connected_timestamp.
  539. logUniqueUser := false
  540. if lastConnected == "None" {
  541. logUniqueUser = true
  542. } else {
  543. t1, _ := time.Parse(time.RFC3339, lastConnected)
  544. year, month, day := t1.Date()
  545. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  546. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  547. year, month, day = t2.Date()
  548. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  549. if t1.Before(t2) && d1 != d2 {
  550. logUniqueUser = true
  551. }
  552. }
  553. if logUniqueUser {
  554. log.LogRawFieldsWithTimestamp(
  555. getRequestLogFields(
  556. "unique_user",
  557. "",
  558. sshClient.sessionID,
  559. sshClient.getClientGeoIPData(),
  560. authorizedAccessTypes,
  561. params,
  562. uniqueUserParams))
  563. }
  564. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  565. connectedResponse := protocol.ConnectedResponse{
  566. ConnectedTimestamp: connectedTimestamp,
  567. Padding: strings.Repeat(" ", pad_response),
  568. }
  569. responsePayload, err := json.Marshal(connectedResponse)
  570. if err != nil {
  571. return nil, errors.Trace(err)
  572. }
  573. return responsePayload, nil
  574. }
  575. var statusRequestParams = baseParams
  576. var remoteServerListStatParams = append(
  577. []requestParamSpec{
  578. // Legacy clients don't record the session_id with remote_server_list_stats entries.
  579. {"session_id", isHexDigits, requestParamOptional},
  580. {"client_download_timestamp", isISO8601Date, 0},
  581. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  582. {"url", isAnyString, 0},
  583. {"etag", isAnyString, 0},
  584. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  585. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  586. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  587. {"fronting_provider_id", isAnyString, requestParamOptional},
  588. {"meek_dial_address", isDialAddress, requestParamOptional},
  589. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  590. {"meek_sni_server_name", isDomain, requestParamOptional},
  591. {"meek_host_header", isHostHeader, requestParamOptional},
  592. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  593. {"user_agent", isAnyString, requestParamOptional},
  594. {"tls_profile", isAnyString, requestParamOptional},
  595. {"tls_version", isAnyString, requestParamOptional},
  596. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  597. },
  598. baseParams...)
  599. // Backwards compatibility case: legacy clients do not include these fields in
  600. // the remote_server_list_stats entries. Use the values from the outer status
  601. // request as an approximation (these values reflect the client at persistent
  602. // stat shipping time, which may differ from the client at persistent stat
  603. // recording time). Note that all but client_build_rev, device_region, and
  604. // device_location are required fields.
  605. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  606. "propagation_channel_id",
  607. "sponsor_id",
  608. "client_version",
  609. "client_platform",
  610. "client_build_rev",
  611. "device_region",
  612. "device_location",
  613. }
  614. var failedTunnelStatParams = append(
  615. []requestParamSpec{
  616. {"server_entry_tag", isAnyString, requestParamOptional},
  617. {"session_id", isHexDigits, 0},
  618. {"last_connected", isLastConnected, 0},
  619. {"client_failed_timestamp", isISO8601Date, 0},
  620. {"record_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  621. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  622. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  623. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  624. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  625. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  626. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  627. {"tunnel_error", isAnyString, 0}},
  628. baseAndDialParams...)
  629. // statusAPIRequestHandler implements the "status" API request.
  630. // Clients make periodic status requests which deliver client-side
  631. // recorded data transfer and tunnel duration stats.
  632. // Note from psi_web implementation: no input validation on domains;
  633. // any string is accepted (regex transform may result in arbitrary
  634. // string). Stats processor must handle this input with care.
  635. func statusAPIRequestHandler(
  636. support *SupportServices,
  637. sshClient *sshClient,
  638. params common.APIParameters) ([]byte, error) {
  639. err := validateRequestParams(params, statusRequestParams)
  640. if err != nil {
  641. return nil, errors.Trace(err)
  642. }
  643. sshClient.Lock()
  644. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  645. sshClient.Unlock()
  646. statusData, err := getJSONObjectRequestParam(params, "statusData")
  647. if err != nil {
  648. return nil, errors.Trace(err)
  649. }
  650. // Logs are queued until the input is fully validated. Otherwise, stats
  651. // could be double counted if the client has a bug in its request
  652. // formatting: partial stats would be logged (counted), the request would
  653. // fail, and clients would then resend all the same stats again.
  654. logQueue := make([]LogFields, 0)
  655. // Domain bytes transferred stats
  656. // Older clients may not submit this data
  657. // Clients are expected to send host_bytes/domain_bytes stats only when
  658. // configured to do so in the handshake reponse. Legacy clients may still
  659. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  660. if sshClient.acceptDomainBytes() && statusData["host_bytes"] != nil {
  661. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  662. if err != nil {
  663. return nil, errors.Trace(err)
  664. }
  665. for domain, bytes := range hostBytes {
  666. domainBytesFields := getRequestLogFields(
  667. "domain_bytes",
  668. "",
  669. sshClient.sessionID,
  670. sshClient.getClientGeoIPData(),
  671. authorizedAccessTypes,
  672. params,
  673. statusRequestParams)
  674. domainBytesFields["domain"] = domain
  675. domainBytesFields["bytes"] = bytes
  676. logQueue = append(logQueue, domainBytesFields)
  677. }
  678. }
  679. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  680. // not time-of-recording.
  681. // Remote server list download persistent stats.
  682. // Older clients may not submit this data.
  683. if statusData["remote_server_list_stats"] != nil {
  684. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  685. if err != nil {
  686. return nil, errors.Trace(err)
  687. }
  688. for _, remoteServerListStat := range remoteServerListStats {
  689. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  690. if _, ok := remoteServerListStat[name]; !ok {
  691. if field, ok := params[name]; ok {
  692. remoteServerListStat[name] = field
  693. }
  694. }
  695. }
  696. err := validateRequestParams(remoteServerListStat, remoteServerListStatParams)
  697. if err != nil {
  698. // Occasionally, clients may send corrupt persistent stat data. Do not
  699. // fail the status request, as this will lead to endless retries.
  700. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  701. continue
  702. }
  703. remoteServerListFields := getRequestLogFields(
  704. "remote_server_list",
  705. "",
  706. "", // Use the session_id the client recorded with the event
  707. sshClient.getClientGeoIPData(),
  708. authorizedAccessTypes,
  709. remoteServerListStat,
  710. remoteServerListStatParams)
  711. logQueue = append(logQueue, remoteServerListFields)
  712. }
  713. }
  714. // Failed tunnel persistent stats.
  715. // Older clients may not submit this data.
  716. // Note: no guarantee that PsinetDatabase won't reload between database calls
  717. db := support.PsinetDatabase
  718. invalidServerEntryTags := make(map[string]bool)
  719. if statusData["failed_tunnel_stats"] != nil {
  720. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  721. if err != nil {
  722. return nil, errors.Trace(err)
  723. }
  724. for _, failedTunnelStat := range failedTunnelStats {
  725. err := validateRequestParams(failedTunnelStat, failedTunnelStatParams)
  726. if err != nil {
  727. // Occasionally, clients may send corrupt persistent stat data. Do not
  728. // fail the status request, as this will lead to endless retries.
  729. //
  730. // TODO: trigger pruning if the data corruption indicates corrupt server
  731. // entry storage?
  732. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  733. continue
  734. }
  735. failedTunnelFields := getRequestLogFields(
  736. "failed_tunnel",
  737. "",
  738. "", // Use the session_id the client recorded with the event
  739. sshClient.getClientGeoIPData(),
  740. authorizedAccessTypes,
  741. failedTunnelStat,
  742. failedTunnelStatParams)
  743. // Return a list of servers, identified by server entry tag, that are
  744. // invalid and presumed to be deleted. This information is used by clients
  745. // to prune deleted servers from their local datastores and stop attempting
  746. // connections to servers that no longer exist.
  747. //
  748. // This mechanism uses tags instead of server IPs: (a) to prevent an
  749. // enumeration attack, where a malicious client can query the entire IPv4
  750. // range and build a map of the Psiphon network; (b) to deal with recyling
  751. // cases where a server deleted and its IP is reused for a new server with
  752. // a distinct server entry.
  753. //
  754. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  755. // before returning a negative result, to mitigate accidental pruning.
  756. //
  757. // In addition, when the reported dial port number is 0, flag the server
  758. // entry as invalid to trigger client pruning. This covers a class of
  759. // invalid/semi-functional server entries, found in practice to be stored
  760. // by clients, where some protocol port number has been omitted -- due to
  761. // historical bugs in various server entry handling implementations. When
  762. // missing from a server entry loaded by a client, the port number
  763. // evaluates to 0, the zero value, which is not a valid port number even if
  764. // it were not missing.
  765. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  766. if ok {
  767. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  768. if serverEntryValid {
  769. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  770. if err == nil && dialPortNumber == 0 {
  771. serverEntryValid = false
  772. }
  773. }
  774. if !serverEntryValid {
  775. invalidServerEntryTags[serverEntryTag] = true
  776. }
  777. // Add a field to the failed_tunnel log indicating if the server entry is
  778. // valid.
  779. failedTunnelFields["server_entry_valid"] = serverEntryValid
  780. }
  781. // Log failed_tunnel.
  782. logQueue = append(logQueue, failedTunnelFields)
  783. }
  784. }
  785. // Handle the prune check, which is an aggressive server entry prune
  786. // operation on top of the opportunistic pruning that is triggered by
  787. // failed_tunnel reports.
  788. if statusData["check_server_entry_tags"] != nil {
  789. checkServerEntryTags, err := getStringArrayRequestParam(statusData, "check_server_entry_tags")
  790. if err != nil {
  791. return nil, errors.Trace(err)
  792. }
  793. invalidCount := 0
  794. for _, serverEntryTag := range checkServerEntryTags {
  795. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  796. if !serverEntryValid {
  797. invalidServerEntryTags[serverEntryTag] = true
  798. invalidCount += 1
  799. }
  800. }
  801. // Prune metrics will be logged in server_tunnel.
  802. sshClient.Lock()
  803. sshClient.requestCheckServerEntryTags += 1
  804. sshClient.checkedServerEntryTags += len(checkServerEntryTags)
  805. sshClient.invalidServerEntryTags += invalidCount
  806. sshClient.Unlock()
  807. }
  808. for _, logItem := range logQueue {
  809. log.LogRawFieldsWithTimestamp(logItem)
  810. }
  811. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  812. statusResponse := protocol.StatusResponse{
  813. Padding: strings.Repeat(" ", pad_response),
  814. }
  815. if len(invalidServerEntryTags) > 0 {
  816. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  817. i := 0
  818. for tag := range invalidServerEntryTags {
  819. statusResponse.InvalidServerEntryTags[i] = tag
  820. i++
  821. }
  822. }
  823. responsePayload, err := json.Marshal(statusResponse)
  824. if err != nil {
  825. return nil, errors.Trace(err)
  826. }
  827. return responsePayload, nil
  828. }
  829. // clientVerificationAPIRequestHandler is just a compliance stub
  830. // for older Android clients that still send verification requests
  831. func clientVerificationAPIRequestHandler(
  832. _ *SupportServices,
  833. _ *sshClient,
  834. _ common.APIParameters) ([]byte, error) {
  835. return make([]byte, 0), nil
  836. }
  837. // dslAPIRequestHandler forwards DSL relay requests. The DSL backend
  838. // (or relay) will handle API parameter processing and event logging.
  839. func dslAPIRequestHandler(
  840. support *SupportServices,
  841. sshClient *sshClient,
  842. requestPayload []byte) ([]byte, error) {
  843. // Sanity check: don't relay more than the modest number of DSL requests
  844. // expected in the tunneled case. The DSL backend has its own rate limit
  845. // enforcement, but avoiding excess requests here saves on resources
  846. // consumed between the relay and backend.
  847. //
  848. // The equivalent pre-relay check in the in-proxy broker uses an explicit
  849. // rate limiter; here a simpler hard limit per tunnel suffices due to the
  850. // low limit size and the fact that tunnel dials are themselves rate
  851. // limited.
  852. ok := false
  853. sshClient.Lock()
  854. if sshClient.dslRequestCount < SSH_CLIENT_MAX_DSL_REQUEST_COUNT {
  855. ok = true
  856. sshClient.dslRequestCount += 1
  857. }
  858. sshClient.Unlock()
  859. if !ok {
  860. return nil, errors.TraceNew("too many DSL requests")
  861. }
  862. responsePayload, err := dslHandleRequest(
  863. sshClient.runCtx,
  864. support,
  865. nil, // no extendTimeout
  866. sshClient.getClientIP(),
  867. common.GeoIPData(sshClient.getClientGeoIPData()),
  868. true, // client request is tunneled
  869. requestPayload)
  870. return responsePayload, errors.Trace(err)
  871. }
  872. var tacticsParams = []requestParamSpec{
  873. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  874. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  875. }
  876. var tacticsRequestParams = append(
  877. append(
  878. []requestParamSpec{
  879. {"session_id", isHexDigits, 0}},
  880. tacticsParams...),
  881. baseAndDialParams...)
  882. func getTacticsAPIParameterValidator() common.APIParameterValidator {
  883. return func(params common.APIParameters) error {
  884. return validateRequestParams(params, tacticsRequestParams)
  885. }
  886. }
  887. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  888. return func(prefix string, geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  889. logFields := getRequestLogFields(
  890. tactics.TACTICS_METRIC_EVENT_NAME,
  891. prefix,
  892. "", // Use the session_id the client reported
  893. GeoIPData(geoIPData),
  894. nil, // authorizedAccessTypes are not known yet
  895. params,
  896. tacticsRequestParams)
  897. return common.LogFields(logFields)
  898. }
  899. }
  900. var inproxyBrokerRequestParams = append(
  901. append(
  902. []requestParamSpec{
  903. {"session_id", isHexDigits, 0},
  904. {"fronting_provider_id", isAnyString, requestParamOptional}},
  905. tacticsParams...),
  906. baseParams...)
  907. func getInproxyBrokerAPIParameterValidator() common.APIParameterValidator {
  908. return func(params common.APIParameters) error {
  909. return validateRequestParams(params, inproxyBrokerRequestParams)
  910. }
  911. }
  912. func getInproxyBrokerAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  913. return func(prefix string, geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  914. logFields := getRequestLogFields(
  915. "inproxy_broker",
  916. prefix,
  917. "", // Use the session_id the client reported
  918. GeoIPData(geoIPData),
  919. nil,
  920. params,
  921. inproxyBrokerRequestParams)
  922. return common.LogFields(logFields)
  923. }
  924. }
  925. func getInproxyBrokerServerReportParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  926. return func(prefix string, _ common.GeoIPData, params common.APIParameters) common.LogFields {
  927. logFields := getRequestLogFields(
  928. "",
  929. prefix,
  930. "", // Use the session_id in ProxyMetrics
  931. GeoIPData{}, // Proxy GeoIP data is added in sshClient.logTunnel
  932. nil,
  933. params,
  934. inproxyBrokerRequestParams)
  935. return common.LogFields(logFields)
  936. }
  937. }
  938. var dslRequestParams = append(
  939. append(
  940. []requestParamSpec{
  941. {"session_id", isHexDigits, 0},
  942. {"fronting_provider_id", isAnyString, requestParamOptional}},
  943. tacticsParams...),
  944. baseParams...)
  945. func getDSLAPIParameterValidator() common.APIParameterValidator {
  946. return func(params common.APIParameters) error {
  947. return validateRequestParams(params, dslRequestParams)
  948. }
  949. }
  950. func getDSLAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  951. return func(prefix string, geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  952. logFields := getRequestLogFields(
  953. "dsl_relay",
  954. prefix,
  955. "", // Use the session_id the client reported
  956. GeoIPData(geoIPData),
  957. nil,
  958. params,
  959. dslRequestParams)
  960. return common.LogFields(logFields)
  961. }
  962. }
  963. // TODO: add session_id to baseParams?
  964. var sessionBaseParams = append(
  965. []requestParamSpec{
  966. {"session_id", isHexDigits, 0}},
  967. baseParams...)
  968. // ValidateAndGetProtobufBaseParams unpacks and validates the input base API
  969. // parameters and returns the parameters in a pb/psiphond.BaseParams struct.
  970. //
  971. // Not all fields in pb/psiphond.BaseParams are populated; some fields, such
  972. // as GeoIP fields and authorized_access_types, are not accepted from clients
  973. // and are populated by the server; other fields, such as last_connected, are
  974. // only sent by the client for certain API requests.
  975. //
  976. // Note that the underlying protobuf converter code may intentionally panic in
  977. // unexpected cases such as a mismatch in log field and protobuf struct field
  978. // types.
  979. func ValidateAndGetProtobufBaseParams(
  980. packedParams protocol.PackedAPIParameters) (*pb.BaseParams, error) {
  981. params, err := protocol.DecodePackedAPIParameters(packedParams)
  982. if err != nil {
  983. return nil, errors.Trace(err)
  984. }
  985. expectedParams := sessionBaseParams
  986. err = validateRequestParams(
  987. params, expectedParams)
  988. if err != nil {
  989. return nil, errors.Trace(err)
  990. }
  991. logFields := getRequestLogFields(
  992. "", "", "", GeoIPData{}, nil, params, expectedParams)
  993. baseParams := protobufPopulateBaseParams(logFields)
  994. return baseParams, nil
  995. }
  996. // requestParamSpec defines a request parameter. Each param is expected to be
  997. // a string, unless requestParamArray is specified, in which case an array of
  998. // strings is expected.
  999. type requestParamSpec struct {
  1000. name string
  1001. validator func(string) bool
  1002. flags uint32
  1003. }
  1004. const (
  1005. requestParamOptional = 1
  1006. requestParamNotLogged = 1 << 1
  1007. requestParamArray = 1 << 2
  1008. requestParamJSON = 1 << 3
  1009. requestParamLogStringAsInt = 1 << 4
  1010. requestParamLogStringAsFloat = 1 << 5
  1011. requestParamLogStringLengthAsInt = 1 << 6
  1012. requestParamLogFlagAsBool = 1 << 7
  1013. requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
  1014. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  1015. requestParamLogOmittedFlagAsFalse = 1 << 10
  1016. )
  1017. // baseParams are the basic request parameters that are expected for all API
  1018. // requests and log events.
  1019. var baseParams = []requestParamSpec{
  1020. {"propagation_channel_id", isHexDigits, 0},
  1021. {"sponsor_id", isSponsorID, 0},
  1022. {"client_version", isIntString, requestParamLogStringAsInt},
  1023. {"client_platform", isClientPlatform, 0},
  1024. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  1025. {"client_build_rev", isHexDigits, requestParamOptional},
  1026. {"device_region", isAnyString, requestParamOptional},
  1027. {"device_location", isGeoHashString, requestParamOptional},
  1028. {"egress_region", isRegionCode, requestParamOptional},
  1029. {"network_type", isAnyString, requestParamOptional},
  1030. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  1031. {"compress_response", isIntString, requestParamOptional | requestParamNotLogged},
  1032. }
  1033. // baseDialParams are the dial parameters, per-tunnel network protocol and
  1034. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  1035. // tactics.
  1036. var baseDialParams = []requestParamSpec{
  1037. {"relay_protocol", isRelayProtocol, 0},
  1038. {"ssh_client_version", isAnyString, requestParamOptional},
  1039. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  1040. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  1041. {"fronting_provider_id", isAnyString, requestParamOptional},
  1042. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  1043. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  1044. {"meek_sni_server_name", isDomain, requestParamOptional},
  1045. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  1046. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1047. {"user_agent", isAnyString, requestParamOptional},
  1048. {"tls_profile", isAnyString, requestParamOptional},
  1049. {"tls_version", isAnyString, requestParamOptional},
  1050. {"server_entry_region", isRegionCode, requestParamOptional},
  1051. {"server_entry_source", isServerEntrySource, requestParamOptional},
  1052. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  1053. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1054. {"quic_version", isAnyString, requestParamOptional},
  1055. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  1056. {"quic_disable_client_path_mtu_discovery", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1057. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1058. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1059. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1060. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1061. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1062. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  1063. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1064. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool | requestParamLogOmittedFlagAsFalse},
  1065. {"replay_ignored_change", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool | requestParamLogOmittedFlagAsFalse},
  1066. {"dsl_prioritized", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool | requestParamLogOmittedFlagAsFalse},
  1067. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1068. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1069. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1070. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1071. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1072. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1073. {"meek_redial_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  1074. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1075. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  1076. {"client_bpf", isAnyString, requestParamOptional},
  1077. {"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1078. {"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1079. {"conjure_transport", isAnyString, requestParamOptional},
  1080. {"conjure_prefix", isAnyString, requestParamOptional},
  1081. {"conjure_stun", isAnyString, requestParamOptional},
  1082. {"conjure_empty_packet", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1083. {"conjure_network", isAnyString, requestParamOptional},
  1084. {"conjure_port_number", isAnyString, requestParamOptional},
  1085. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1086. {"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
  1087. {"dns_preresolved", isAnyString, requestParamOptional},
  1088. {"dns_preferred", isAnyString, requestParamOptional},
  1089. {"dns_transform", isAnyString, requestParamOptional},
  1090. {"dns_qname_random_casing", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1091. {"dns_qname_must_match", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1092. {"dns_qname_mismatches", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1093. {"dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1094. {"http_transform", isAnyString, requestParamOptional},
  1095. {"seed_transform", isAnyString, requestParamOptional},
  1096. {"ossh_prefix", isAnyString, requestParamOptional},
  1097. {"shadowsocks_prefix", isAnyString, requestParamOptional},
  1098. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1099. {"tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  1100. {"tls_ossh_sni_server_name", isDomain, requestParamOptional},
  1101. {"tls_ossh_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1102. {"steering_ip", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  1103. {"tls_sent_ticket", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1104. {"tls_did_resume", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1105. {"quic_sent_ticket", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1106. {"quic_did_resume", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1107. {"quic_dial_early", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1108. {"quic_obfuscated_psk", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  1109. {"server_entry_count", 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. }
  1589. return CLIENT_PLATFORM_WINDOWS
  1590. }
  1591. func isMobileClientPlatform(clientPlatform string) bool {
  1592. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1593. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1594. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1595. }
  1596. func isAnyString(value string) bool {
  1597. return true
  1598. }
  1599. // Input validators follow the legacy validations rules in psi_web.
  1600. func isSponsorID(value string) bool {
  1601. return len(value) == SPONSOR_ID_LENGTH && isHexDigits(value)
  1602. }
  1603. func isHexDigits(value string) bool {
  1604. // Allows both uppercase in addition to lowercase, for legacy support.
  1605. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1606. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1607. })
  1608. }
  1609. func isBase64String(value string) bool {
  1610. _, err := base64.StdEncoding.DecodeString(value)
  1611. return err == nil
  1612. }
  1613. func isUnpaddedBase64String(value string) bool {
  1614. _, err := base64.RawStdEncoding.DecodeString(value)
  1615. return err == nil
  1616. }
  1617. func isDigits(value string) bool {
  1618. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1619. return c < '0' || c > '9'
  1620. })
  1621. }
  1622. func isIntString(value string) bool {
  1623. _, err := strconv.Atoi(value)
  1624. return err == nil
  1625. }
  1626. func isFloatString(value string) bool {
  1627. _, err := strconv.ParseFloat(value, 64)
  1628. return err == nil
  1629. }
  1630. func isClientPlatform(value string) bool {
  1631. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1632. // Note: stricter than psi_web's Python string.whitespace
  1633. return unicode.Is(unicode.White_Space, c)
  1634. })
  1635. }
  1636. func isRelayProtocol(value string) bool {
  1637. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1638. }
  1639. func isBooleanFlag(value string) bool {
  1640. return value == "0" || value == "1"
  1641. }
  1642. func isUpstreamProxyType(value string) bool {
  1643. value = strings.ToLower(value)
  1644. return value == "http" || value == "socks5" || value == "socks4a"
  1645. }
  1646. func isRegionCode(value string) bool {
  1647. if len(value) != 2 {
  1648. return false
  1649. }
  1650. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1651. return c < 'A' || c > 'Z'
  1652. })
  1653. }
  1654. func isDialAddress(value string) bool {
  1655. // "<host>:<port>", where <host> is a domain or IP address
  1656. parts := strings.Split(value, ":")
  1657. if len(parts) != 2 {
  1658. return false
  1659. }
  1660. if !isIPAddress(parts[0]) && !isDomain(parts[0]) {
  1661. return false
  1662. }
  1663. if !isDigits(parts[1]) {
  1664. return false
  1665. }
  1666. _, err := strconv.Atoi(parts[1])
  1667. if err != nil {
  1668. return false
  1669. }
  1670. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1671. return true
  1672. }
  1673. func isIPAddress(value string) bool {
  1674. return net.ParseIP(value) != nil
  1675. }
  1676. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1677. func isDomain(value string) bool {
  1678. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1679. //
  1680. // "ensures that each segment
  1681. // * contains at least one character and a maximum of 63 characters
  1682. // * consists only of allowed characters
  1683. // * doesn't begin or end with a hyphen"
  1684. //
  1685. if len(value) > 255 {
  1686. return false
  1687. }
  1688. value = strings.TrimSuffix(value, ".")
  1689. for _, part := range strings.Split(value, ".") {
  1690. // Note: regexp doesn't support the following Perl expression which
  1691. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1692. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1693. return false
  1694. }
  1695. if !isDomainRegex.Match([]byte(part)) {
  1696. return false
  1697. }
  1698. }
  1699. return true
  1700. }
  1701. func isHostHeader(value string) bool {
  1702. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1703. if strings.Contains(value, ":") {
  1704. return isDialAddress(value)
  1705. }
  1706. return isIPAddress(value) || isDomain(value)
  1707. }
  1708. func isServerEntrySource(value string) bool {
  1709. return common.ContainsWildcard(protocol.SupportedServerEntrySources, value)
  1710. }
  1711. // ISO8601 with optional TZ offset; up to nanosecond precision.
  1712. const iso8601Date = "2006-01-02T15:04:05.999999999Z0700"
  1713. func isISO8601Date(value string) bool {
  1714. _, err := time.Parse(iso8601Date, value)
  1715. return err == nil
  1716. }
  1717. func isLastConnected(value string) bool {
  1718. return value == "None" || isISO8601Date(value)
  1719. }
  1720. const geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
  1721. func isGeoHashString(value string) bool {
  1722. // Verify that the string is between 1 and 12 characters long
  1723. // and contains only characters from the geohash alphabet.
  1724. if len(value) < 1 || len(value) > 12 {
  1725. return false
  1726. }
  1727. for _, c := range value {
  1728. if !strings.Contains(geohashAlphabet, string(c)) {
  1729. return false
  1730. }
  1731. }
  1732. return true
  1733. }