api.go 66 KB

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