api.go 66 KB

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