api.go 64 KB

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