api.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  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. "crypto/hmac"
  22. "crypto/sha256"
  23. "crypto/subtle"
  24. "encoding/base64"
  25. "encoding/json"
  26. std_errors "errors"
  27. "net"
  28. "regexp"
  29. "strconv"
  30. "strings"
  31. "time"
  32. "unicode"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  38. )
  39. const (
  40. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  41. PADDING_MAX_BYTES = 16 * 1024
  42. CLIENT_PLATFORM_ANDROID = "Android"
  43. CLIENT_PLATFORM_WINDOWS = "Windows"
  44. CLIENT_PLATFORM_IOS = "iOS"
  45. )
  46. // sshAPIRequestHandler routes Psiphon API requests transported as
  47. // JSON objects via the SSH request mechanism.
  48. //
  49. // The API request handlers, handshakeAPIRequestHandler, etc., are
  50. // reused by webServer which offers the Psiphon API via web transport.
  51. //
  52. // The API request parameters and event log values follow the legacy
  53. // psi_web protocol and naming conventions. The API is compatible with
  54. // all tunnel-core clients but are not backwards compatible with all
  55. // legacy clients.
  56. func sshAPIRequestHandler(
  57. support *SupportServices,
  58. clientAddr string,
  59. geoIPData GeoIPData,
  60. authorizedAccessTypes []string,
  61. name string,
  62. requestPayload []byte) ([]byte, error) {
  63. // Notes:
  64. //
  65. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  66. // by max SSH request packet size.
  67. //
  68. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  69. // array of base64-encoded strings; the base64 representation should
  70. // not be decoded to []byte values. The default behavior of
  71. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  72. // type map[string]interface{} will unmarshal a base64-encoded string
  73. // to a string, not a decoded []byte, as required.
  74. var params common.APIParameters
  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. return dispatchAPIRequestHandler(
  81. support,
  82. protocol.PSIPHON_SSH_API_PROTOCOL,
  83. clientAddr,
  84. geoIPData,
  85. authorizedAccessTypes,
  86. name,
  87. params)
  88. }
  89. // dispatchAPIRequestHandler is the common dispatch point for both
  90. // web and SSH API requests.
  91. func dispatchAPIRequestHandler(
  92. support *SupportServices,
  93. apiProtocol string,
  94. clientAddr string,
  95. geoIPData GeoIPData,
  96. authorizedAccessTypes []string,
  97. name string,
  98. params common.APIParameters) (response []byte, reterr error) {
  99. // Before invoking the handlers, enforce some preconditions:
  100. //
  101. // - A handshake request must precede any other requests.
  102. // - When the handshake results in a traffic rules state where
  103. // the client is immediately exhausted, no requests
  104. // may succeed. This case ensures that blocked clients do
  105. // not log "connected", etc.
  106. //
  107. // Only one handshake request may be made. There is no check here
  108. // to enforce that handshakeAPIRequestHandler will be called at
  109. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  110. // enforces that only a single handshake is made; enforcing that there
  111. // ensures no race condition even if concurrent requests are
  112. // in flight.
  113. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  114. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  115. // applies here.
  116. sessionID, err := getStringRequestParam(params, "client_session_id")
  117. if err == nil {
  118. // Note: follows/duplicates baseParams validation
  119. if !isHexDigits(support.Config, sessionID) {
  120. err = std_errors.New("invalid param: client_session_id")
  121. }
  122. }
  123. if err != nil {
  124. return nil, errors.Trace(err)
  125. }
  126. completed, exhausted, err := support.TunnelServer.GetClientHandshaked(sessionID)
  127. if err != nil {
  128. return nil, errors.Trace(err)
  129. }
  130. if !completed {
  131. return nil, errors.TraceNew("handshake not completed")
  132. }
  133. if exhausted {
  134. return nil, errors.TraceNew("exhausted after handshake")
  135. }
  136. }
  137. switch name {
  138. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  139. return handshakeAPIRequestHandler(
  140. support, apiProtocol, clientAddr, geoIPData, params)
  141. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  142. return connectedAPIRequestHandler(
  143. support, clientAddr, geoIPData, authorizedAccessTypes, params)
  144. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  145. return statusAPIRequestHandler(
  146. support, clientAddr, geoIPData, authorizedAccessTypes, params)
  147. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  148. return clientVerificationAPIRequestHandler(
  149. support, clientAddr, geoIPData, authorizedAccessTypes, params)
  150. }
  151. return nil, errors.Tracef("invalid request name: %s", name)
  152. }
  153. var handshakeRequestParams = append(
  154. append(
  155. append(
  156. []requestParamSpec{
  157. // Legacy clients may not send "session_id" in handshake
  158. {"session_id", isHexDigits, requestParamOptional},
  159. {"missing_server_entry_signature", isBase64String, requestParamOptional}},
  160. baseParams...),
  161. baseDialParams...),
  162. tacticsParams...)
  163. // handshakeAPIRequestHandler implements the "handshake" API request.
  164. // Clients make the handshake immediately after establishing a tunnel
  165. // connection; the response tells the client what homepage to open, what
  166. // stats to record, etc.
  167. func handshakeAPIRequestHandler(
  168. support *SupportServices,
  169. apiProtocol string,
  170. clientAddr string,
  171. geoIPData GeoIPData,
  172. params common.APIParameters) ([]byte, error) {
  173. // Note: ignoring legacy "known_servers" params
  174. err := validateRequestParams(support.Config, params, handshakeRequestParams)
  175. if err != nil {
  176. return nil, errors.Trace(err)
  177. }
  178. sessionID, _ := getStringRequestParam(params, "client_session_id")
  179. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  180. clientVersion, _ := getStringRequestParam(params, "client_version")
  181. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  182. isMobile := isMobileClientPlatform(clientPlatform)
  183. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  184. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  185. // the client, a value of 0 will be used.
  186. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  187. // splitTunnelOwnRegion indicates if the client is requesting split tunnel
  188. // mode to be applied to the client's own country. When omitted by the
  189. // client, the value will be false.
  190. //
  191. // When split_tunnel_regions is non-empty, split tunnel mode will be
  192. // applied for the specified country codes. When omitted by the client,
  193. // the value will be an empty slice.
  194. splitTunnelOwnRegion, _ := getBoolStringRequestParam(params, "split_tunnel")
  195. splitTunnelOtherRegions, _ := getStringArrayRequestParam(params, "split_tunnel_regions")
  196. ownRegion := ""
  197. if splitTunnelOwnRegion {
  198. ownRegion = geoIPData.Country
  199. }
  200. var splitTunnelLookup *splitTunnelLookup
  201. if ownRegion != "" || len(splitTunnelOtherRegions) > 0 {
  202. splitTunnelLookup, err = newSplitTunnelLookup(ownRegion, splitTunnelOtherRegions)
  203. if err != nil {
  204. return nil, errors.Trace(err)
  205. }
  206. }
  207. var authorizations []string
  208. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  209. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  210. if err != nil {
  211. return nil, errors.Trace(err)
  212. }
  213. }
  214. deviceRegion, ok := getOptionalStringRequestParam(params, "device_region")
  215. if !ok {
  216. deviceRegion = GEOIP_UNKNOWN_VALUE
  217. }
  218. // Note: no guarantee that PsinetDatabase won't reload between database calls
  219. db := support.PsinetDatabase
  220. httpsRequestRegexes, domainBytesChecksum := db.GetHttpsRequestRegexes(sponsorID)
  221. // Flag the SSH client as having completed its handshake. This
  222. // may reselect traffic rules and starts allowing port forwards.
  223. // TODO: in the case of SSH API requests, the actual sshClient could
  224. // be passed in and used here. The session ID lookup is only strictly
  225. // necessary to support web API requests.
  226. handshakeStateInfo, err := support.TunnelServer.SetClientHandshakeState(
  227. sessionID,
  228. handshakeState{
  229. completed: true,
  230. apiProtocol: apiProtocol,
  231. apiParams: copyBaseSessionAndDialParams(params),
  232. domainBytesChecksum: domainBytesChecksum,
  233. establishedTunnelsCount: establishedTunnelsCount,
  234. splitTunnelLookup: splitTunnelLookup,
  235. deviceRegion: deviceRegion,
  236. },
  237. authorizations)
  238. if err != nil {
  239. return nil, errors.Trace(err)
  240. }
  241. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  242. common.GeoIPData(geoIPData), params)
  243. if err != nil {
  244. return nil, errors.Trace(err)
  245. }
  246. var marshaledTacticsPayload []byte
  247. if tacticsPayload != nil {
  248. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  249. if err != nil {
  250. return nil, errors.Trace(err)
  251. }
  252. // Log a metric when new tactics are issued. Logging here indicates that
  253. // the handshake tactics mechanism is active; but logging for every
  254. // handshake creates unneccesary log data.
  255. if len(tacticsPayload.Tactics) > 0 {
  256. logFields := getRequestLogFields(
  257. tactics.TACTICS_METRIC_EVENT_NAME,
  258. geoIPData,
  259. handshakeStateInfo.authorizedAccessTypes,
  260. params,
  261. handshakeRequestParams)
  262. logFields[tactics.NEW_TACTICS_TAG_LOG_FIELD_NAME] = tacticsPayload.Tag
  263. logFields[tactics.IS_TACTICS_REQUEST_LOG_FIELD_NAME] = false
  264. log.LogRawFieldsWithTimestamp(logFields)
  265. }
  266. }
  267. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  268. // the state change (for example, if a second handshake is performed)
  269. //
  270. // The handshake event is no longer shipped to log consumers, so this is
  271. // simply a diagnostic log. Since the "server_tunnel" event includes all
  272. // common API parameters and "handshake_completed" flag, this handshake
  273. // log is mostly redundant and set to debug level.
  274. log.WithTraceFields(
  275. getRequestLogFields(
  276. "",
  277. geoIPData,
  278. handshakeStateInfo.authorizedAccessTypes,
  279. params,
  280. handshakeRequestParams)).Debug("handshake")
  281. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  282. // Discover new servers
  283. disableDiscovery, err := support.TunnelServer.GetClientDisableDiscovery(sessionID)
  284. if err != nil {
  285. return nil, errors.Trace(err)
  286. }
  287. var encodedServerList []string
  288. if !disableDiscovery {
  289. host, _, err := net.SplitHostPort(clientAddr)
  290. if err != nil {
  291. return nil, errors.Trace(err)
  292. }
  293. clientIP := net.ParseIP(host)
  294. if clientIP == nil {
  295. return nil, errors.TraceNew("missing client IP")
  296. }
  297. encodedServerList = db.DiscoverServers(
  298. calculateDiscoveryValue(support.Config.DiscoveryValueHMACKey, clientIP))
  299. }
  300. // When the client indicates that it used an unsigned server entry for this
  301. // connection, return a signed copy of the server entry for the client to
  302. // upgrade to. See also: comment in psiphon.doHandshakeRequest.
  303. //
  304. // The missing_server_entry_signature parameter value is a server entry tag,
  305. // which is used to select the correct server entry for servers with multiple
  306. // entries. Identifying the server entries tags instead of server IPs prevents
  307. // an enumeration attack, where a malicious client can abuse this facilty to
  308. // check if an arbitrary IP address is a Psiphon server.
  309. serverEntryTag, ok := getOptionalStringRequestParam(
  310. params, "missing_server_entry_signature")
  311. if ok {
  312. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  313. if ok {
  314. encodedServerList = append(encodedServerList, ownServerEntry)
  315. }
  316. }
  317. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  318. // the JSON response, return an empty array instead of null for legacy
  319. // clients.
  320. homepages := db.GetRandomizedHomepages(
  321. sponsorID, geoIPData.Country, geoIPData.ASN, deviceRegion, isMobile)
  322. handshakeResponse := protocol.HandshakeResponse{
  323. SSHSessionID: sessionID,
  324. Homepages: homepages,
  325. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  326. PageViewRegexes: make([]map[string]string, 0),
  327. HttpsRequestRegexes: httpsRequestRegexes,
  328. EncodedServerList: encodedServerList,
  329. ClientRegion: geoIPData.Country,
  330. ClientAddress: clientAddr,
  331. ServerTimestamp: common.GetCurrentTimestamp(),
  332. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  333. TacticsPayload: marshaledTacticsPayload,
  334. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  335. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  336. Padding: strings.Repeat(" ", pad_response),
  337. }
  338. responsePayload, err := json.Marshal(handshakeResponse)
  339. if err != nil {
  340. return nil, errors.Trace(err)
  341. }
  342. return responsePayload, nil
  343. }
  344. // calculateDiscoveryValue derives a value from the client IP address to be
  345. // used as input in the server discovery algorithm.
  346. // See https://github.com/Psiphon-Inc/psiphon-automation/tree/master/Automation/psi_ops_discovery.py
  347. // for full details.
  348. func calculateDiscoveryValue(discoveryValueHMACKey string, ipAddress net.IP) int {
  349. // From: psi_ops_discovery.calculate_ip_address_strategy_value:
  350. // # Mix bits from all octets of the client IP address to determine the
  351. // # bucket. An HMAC is used to prevent pre-calculation of buckets for IPs.
  352. // return ord(hmac.new(HMAC_KEY, ip_address, hashlib.sha256).digest()[0])
  353. // TODO: use 3-octet algorithm?
  354. hash := hmac.New(sha256.New, []byte(discoveryValueHMACKey))
  355. hash.Write([]byte(ipAddress.String()))
  356. return int(hash.Sum(nil)[0])
  357. }
  358. // uniqueUserParams are the connected request parameters which are logged for
  359. // unique_user events.
  360. var uniqueUserParams = append(
  361. []requestParamSpec{
  362. {"last_connected", isLastConnected, 0}},
  363. baseSessionParams...)
  364. var connectedRequestParams = append(
  365. []requestParamSpec{
  366. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  367. uniqueUserParams...)
  368. // updateOnConnectedParamNames are connected request parameters which are
  369. // copied to update data logged with server_tunnel: these fields either only
  370. // ship with or ship newer data with connected requests.
  371. var updateOnConnectedParamNames = append(
  372. []string{
  373. "last_connected",
  374. "establishment_duration",
  375. },
  376. fragmentor.GetUpstreamMetricsNames()...)
  377. // connectedAPIRequestHandler implements the "connected" API request. Clients
  378. // make the connected request once a tunnel connection has been established
  379. // and at least once per 24h for long-running tunnels. The last_connected
  380. // input value, which should be a connected_timestamp output from a previous
  381. // connected response, is used to calculate unique user stats.
  382. // connected_timestamp is truncated as a privacy measure.
  383. func connectedAPIRequestHandler(
  384. support *SupportServices,
  385. clientAddr string,
  386. geoIPData GeoIPData,
  387. authorizedAccessTypes []string,
  388. params common.APIParameters) ([]byte, error) {
  389. err := validateRequestParams(support.Config, params, connectedRequestParams)
  390. if err != nil {
  391. return nil, errors.Trace(err)
  392. }
  393. sessionID, _ := getStringRequestParam(params, "client_session_id")
  394. lastConnected, _ := getStringRequestParam(params, "last_connected")
  395. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  396. // client may have performed more upstream fragmentation since the previous
  397. // metrics reported by the handshake request. Also, additional fields that
  398. // are reported only in the connected request are added to server_tunnel
  399. // here.
  400. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  401. // applies here.
  402. err = support.TunnelServer.UpdateClientAPIParameters(
  403. sessionID, copyUpdateOnConnectedParams(params))
  404. if err != nil {
  405. return nil, errors.Trace(err)
  406. }
  407. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  408. // The finest required granularity for unique users is daily. To save space,
  409. // only record a "unique_user" log event when the client's last_connected is
  410. // in the previous day relative to the new connected_timestamp.
  411. logUniqueUser := false
  412. if lastConnected == "None" {
  413. logUniqueUser = true
  414. } else {
  415. t1, _ := time.Parse(time.RFC3339, lastConnected)
  416. year, month, day := t1.Date()
  417. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  418. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  419. year, month, day = t2.Date()
  420. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  421. if t1.Before(t2) && d1 != d2 {
  422. logUniqueUser = true
  423. }
  424. }
  425. if logUniqueUser {
  426. log.LogRawFieldsWithTimestamp(
  427. getRequestLogFields(
  428. "unique_user",
  429. geoIPData,
  430. authorizedAccessTypes,
  431. params,
  432. uniqueUserParams))
  433. }
  434. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  435. connectedResponse := protocol.ConnectedResponse{
  436. ConnectedTimestamp: connectedTimestamp,
  437. Padding: strings.Repeat(" ", pad_response),
  438. }
  439. responsePayload, err := json.Marshal(connectedResponse)
  440. if err != nil {
  441. return nil, errors.Trace(err)
  442. }
  443. return responsePayload, nil
  444. }
  445. var statusRequestParams = baseSessionParams
  446. var remoteServerListStatParams = append(
  447. []requestParamSpec{
  448. {"client_download_timestamp", isISO8601Date, 0},
  449. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  450. {"url", isAnyString, 0},
  451. {"etag", isAnyString, 0},
  452. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  453. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  454. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  455. {"fronting_provider_id", isAnyString, requestParamOptional},
  456. {"meek_dial_address", isDialAddress, requestParamOptional},
  457. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  458. {"meek_sni_server_name", isDomain, requestParamOptional},
  459. {"meek_host_header", isHostHeader, requestParamOptional},
  460. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  461. {"user_agent", isAnyString, requestParamOptional},
  462. {"tls_profile", isAnyString, requestParamOptional},
  463. {"tls_version", isAnyString, requestParamOptional},
  464. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  465. },
  466. baseSessionParams...)
  467. // Backwards compatibility case: legacy clients do not include these fields in
  468. // the remote_server_list_stats entries. Use the values from the outer status
  469. // request as an approximation (these values reflect the client at persistent
  470. // stat shipping time, which may differ from the client at persistent stat
  471. // recording time). Note that all but client_build_rev, device_region, and
  472. // device_location are required fields.
  473. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  474. "session_id",
  475. "propagation_channel_id",
  476. "sponsor_id",
  477. "client_version",
  478. "client_platform",
  479. "client_build_rev",
  480. "device_region",
  481. "device_location",
  482. }
  483. var failedTunnelStatParams = append(
  484. []requestParamSpec{
  485. {"server_entry_tag", isAnyString, requestParamOptional},
  486. {"session_id", isHexDigits, 0},
  487. {"last_connected", isLastConnected, 0},
  488. {"client_failed_timestamp", isISO8601Date, 0},
  489. {"record_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  490. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  491. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  492. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  493. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  494. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  495. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  496. {"tunnel_error", isAnyString, 0}},
  497. baseSessionAndDialParams...)
  498. // statusAPIRequestHandler implements the "status" API request.
  499. // Clients make periodic status requests which deliver client-side
  500. // recorded data transfer and tunnel duration stats.
  501. // Note from psi_web implementation: no input validation on domains;
  502. // any string is accepted (regex transform may result in arbitrary
  503. // string). Stats processor must handle this input with care.
  504. func statusAPIRequestHandler(
  505. support *SupportServices,
  506. clientAddr string,
  507. geoIPData GeoIPData,
  508. authorizedAccessTypes []string,
  509. params common.APIParameters) ([]byte, error) {
  510. err := validateRequestParams(support.Config, params, statusRequestParams)
  511. if err != nil {
  512. return nil, errors.Trace(err)
  513. }
  514. sessionID, _ := getStringRequestParam(params, "client_session_id")
  515. statusData, err := getJSONObjectRequestParam(params, "statusData")
  516. if err != nil {
  517. return nil, errors.Trace(err)
  518. }
  519. // Logs are queued until the input is fully validated. Otherwise, stats
  520. // could be double counted if the client has a bug in its request
  521. // formatting: partial stats would be logged (counted), the request would
  522. // fail, and clients would then resend all the same stats again.
  523. logQueue := make([]LogFields, 0)
  524. // Domain bytes transferred stats
  525. // Older clients may not submit this data
  526. // Clients are expected to send host_bytes/domain_bytes stats only when
  527. // configured to do so in the handshake reponse. Legacy clients may still
  528. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  529. acceptDomainBytes, err := support.TunnelServer.AcceptClientDomainBytes(sessionID)
  530. if err != nil {
  531. return nil, errors.Trace(err)
  532. }
  533. if acceptDomainBytes && statusData["host_bytes"] != nil {
  534. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  535. if err != nil {
  536. return nil, errors.Trace(err)
  537. }
  538. for domain, bytes := range hostBytes {
  539. domainBytesFields := getRequestLogFields(
  540. "domain_bytes",
  541. geoIPData,
  542. authorizedAccessTypes,
  543. params,
  544. statusRequestParams)
  545. domainBytesFields["domain"] = domain
  546. domainBytesFields["bytes"] = bytes
  547. logQueue = append(logQueue, domainBytesFields)
  548. }
  549. }
  550. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  551. // not time-of-recording.
  552. // Remote server list download persistent stats.
  553. // Older clients may not submit this data.
  554. if statusData["remote_server_list_stats"] != nil {
  555. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  556. if err != nil {
  557. return nil, errors.Trace(err)
  558. }
  559. for _, remoteServerListStat := range remoteServerListStats {
  560. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  561. if _, ok := remoteServerListStat[name]; !ok {
  562. if field, ok := params[name]; ok {
  563. remoteServerListStat[name] = field
  564. }
  565. }
  566. }
  567. // For validation, copy expected fields from the outer
  568. // statusRequestParams.
  569. remoteServerListStat["server_secret"] = params["server_secret"]
  570. remoteServerListStat["client_session_id"] = params["client_session_id"]
  571. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  572. if err != nil {
  573. // Occasionally, clients may send corrupt persistent stat data. Do not
  574. // fail the status request, as this will lead to endless retries.
  575. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  576. continue
  577. }
  578. remoteServerListFields := getRequestLogFields(
  579. "remote_server_list",
  580. geoIPData,
  581. authorizedAccessTypes,
  582. remoteServerListStat,
  583. remoteServerListStatParams)
  584. logQueue = append(logQueue, remoteServerListFields)
  585. }
  586. }
  587. // Failed tunnel persistent stats.
  588. // Older clients may not submit this data.
  589. var invalidServerEntryTags map[string]bool
  590. if statusData["failed_tunnel_stats"] != nil {
  591. // Note: no guarantee that PsinetDatabase won't reload between database calls
  592. db := support.PsinetDatabase
  593. invalidServerEntryTags = make(map[string]bool)
  594. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  595. if err != nil {
  596. return nil, errors.Trace(err)
  597. }
  598. for _, failedTunnelStat := range failedTunnelStats {
  599. // failed_tunnel supplies a full set of base params, but the server secret
  600. // must use the correct value from the outer statusRequestParams.
  601. failedTunnelStat["server_secret"] = params["server_secret"]
  602. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  603. if err != nil {
  604. // Occasionally, clients may send corrupt persistent stat data. Do not
  605. // fail the status request, as this will lead to endless retries.
  606. //
  607. // TODO: trigger pruning if the data corruption indicates corrupt server
  608. // entry storage?
  609. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  610. continue
  611. }
  612. failedTunnelFields := getRequestLogFields(
  613. "failed_tunnel",
  614. geoIPData,
  615. authorizedAccessTypes,
  616. failedTunnelStat,
  617. failedTunnelStatParams)
  618. // Return a list of servers, identified by server entry tag, that are
  619. // invalid and presumed to be deleted. This information is used by clients
  620. // to prune deleted servers from their local datastores and stop attempting
  621. // connections to servers that no longer exist.
  622. //
  623. // This mechanism uses tags instead of server IPs: (a) to prevent an
  624. // enumeration attack, where a malicious client can query the entire IPv4
  625. // range and build a map of the Psiphon network; (b) to deal with recyling
  626. // cases where a server deleted and its IP is reused for a new server with
  627. // a distinct server entry.
  628. //
  629. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  630. // before returning a negative result, to mitigate accidental pruning.
  631. //
  632. // In addition, when the reported dial port number is 0, flag the server
  633. // entry as invalid to trigger client pruning. This covers a class of
  634. // invalid/semi-functional server entries, found in practice to be stored
  635. // by clients, where some protocol port number has been omitted -- due to
  636. // historical bugs in various server entry handling implementations. When
  637. // missing from a server entry loaded by a client, the port number
  638. // evaluates to 0, the zero value, which is not a valid port number even if
  639. // were not missing.
  640. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  641. if ok {
  642. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  643. if serverEntryValid {
  644. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  645. if err == nil && dialPortNumber == 0 {
  646. serverEntryValid = false
  647. }
  648. }
  649. if !serverEntryValid {
  650. invalidServerEntryTags[serverEntryTag] = true
  651. }
  652. // Add a field to the failed_tunnel log indicating if the server entry is
  653. // valid.
  654. failedTunnelFields["server_entry_valid"] = serverEntryValid
  655. }
  656. // Log failed_tunnel.
  657. logQueue = append(logQueue, failedTunnelFields)
  658. }
  659. }
  660. for _, logItem := range logQueue {
  661. log.LogRawFieldsWithTimestamp(logItem)
  662. }
  663. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  664. statusResponse := protocol.StatusResponse{
  665. Padding: strings.Repeat(" ", pad_response),
  666. }
  667. if len(invalidServerEntryTags) > 0 {
  668. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  669. i := 0
  670. for tag := range invalidServerEntryTags {
  671. statusResponse.InvalidServerEntryTags[i] = tag
  672. i++
  673. }
  674. }
  675. responsePayload, err := json.Marshal(statusResponse)
  676. if err != nil {
  677. return nil, errors.Trace(err)
  678. }
  679. return responsePayload, nil
  680. }
  681. // clientVerificationAPIRequestHandler is just a compliance stub
  682. // for older Android clients that still send verification requests
  683. func clientVerificationAPIRequestHandler(
  684. support *SupportServices,
  685. clientAddr string,
  686. geoIPData GeoIPData,
  687. authorizedAccessTypes []string,
  688. params common.APIParameters) ([]byte, error) {
  689. return make([]byte, 0), nil
  690. }
  691. var tacticsParams = []requestParamSpec{
  692. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  693. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  694. }
  695. var tacticsRequestParams = append(
  696. append([]requestParamSpec(nil), tacticsParams...),
  697. baseSessionAndDialParams...)
  698. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  699. return func(params common.APIParameters) error {
  700. return validateRequestParams(config, params, tacticsRequestParams)
  701. }
  702. }
  703. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  704. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  705. logFields := getRequestLogFields(
  706. tactics.TACTICS_METRIC_EVENT_NAME,
  707. GeoIPData(geoIPData),
  708. nil, // authorizedAccessTypes are not known yet
  709. params,
  710. tacticsRequestParams)
  711. return common.LogFields(logFields)
  712. }
  713. }
  714. // requestParamSpec defines a request parameter. Each param is expected to be
  715. // a string, unless requestParamArray is specified, in which case an array of
  716. // strings is expected.
  717. type requestParamSpec struct {
  718. name string
  719. validator func(*Config, string) bool
  720. flags uint32
  721. }
  722. const (
  723. requestParamOptional = 1
  724. requestParamNotLogged = 1 << 1
  725. requestParamArray = 1 << 2
  726. requestParamJSON = 1 << 3
  727. requestParamLogStringAsInt = 1 << 4
  728. requestParamLogStringAsFloat = 1 << 5
  729. requestParamLogStringLengthAsInt = 1 << 6
  730. requestParamLogFlagAsBool = 1 << 7
  731. requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
  732. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  733. )
  734. // baseParams are the basic request parameters that are expected for all API
  735. // requests and log events.
  736. var baseParams = []requestParamSpec{
  737. {"server_secret", isServerSecret, requestParamNotLogged},
  738. {"client_session_id", isHexDigits, requestParamNotLogged},
  739. {"propagation_channel_id", isHexDigits, 0},
  740. {"sponsor_id", isHexDigits, 0},
  741. {"client_version", isIntString, requestParamLogStringAsInt},
  742. {"client_platform", isClientPlatform, 0},
  743. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  744. {"client_build_rev", isHexDigits, requestParamOptional},
  745. {"device_region", isAnyString, requestParamOptional},
  746. {"device_location", isGeoHashString, requestParamOptional},
  747. }
  748. // baseSessionParams adds to baseParams the required session_id parameter. For
  749. // all requests except handshake, all existing clients are expected to send
  750. // session_id. Legacy clients may not send "session_id" in handshake.
  751. var baseSessionParams = append(
  752. []requestParamSpec{
  753. {"session_id", isHexDigits, 0}},
  754. baseParams...)
  755. // baseDialParams are the dial parameters, per-tunnel network protocol and
  756. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  757. // tactics.
  758. var baseDialParams = []requestParamSpec{
  759. {"relay_protocol", isRelayProtocol, 0},
  760. {"ssh_client_version", isAnyString, requestParamOptional},
  761. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  762. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  763. {"fronting_provider_id", isAnyString, requestParamOptional},
  764. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  765. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  766. {"meek_sni_server_name", isDomain, requestParamOptional},
  767. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  768. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  769. {"user_agent", isAnyString, requestParamOptional},
  770. {"tls_profile", isAnyString, requestParamOptional},
  771. {"tls_version", isAnyString, requestParamOptional},
  772. {"server_entry_region", isRegionCode, requestParamOptional},
  773. {"server_entry_source", isServerEntrySource, requestParamOptional},
  774. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  775. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  776. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  777. {"quic_version", isAnyString, requestParamOptional},
  778. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  779. {"quic_disable_client_path_mtu_discovery", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  780. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  781. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  782. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  783. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  784. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  785. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  786. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  787. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  788. {"egress_region", isRegionCode, requestParamOptional},
  789. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  790. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  791. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  792. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  793. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  794. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  795. {"meek_redial_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  796. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  797. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  798. {"client_bpf", isAnyString, requestParamOptional},
  799. {"network_type", isAnyString, requestParamOptional},
  800. {"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  801. {"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
  802. {"conjure_transport", isAnyString, requestParamOptional},
  803. {"conjure_prefix", isAnyString, requestParamOptional},
  804. {"conjure_stun", isAnyString, requestParamOptional},
  805. {"conjure_empty_packet", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  806. {"conjure_network", isAnyString, requestParamOptional},
  807. {"conjure_port_number", isAnyString, requestParamOptional},
  808. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  809. {"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
  810. {"dns_preresolved", isAnyString, requestParamOptional},
  811. {"dns_preferred", isAnyString, requestParamOptional},
  812. {"dns_transform", isAnyString, requestParamOptional},
  813. {"dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  814. {"http_transform", isAnyString, requestParamOptional},
  815. {"seed_transform", isAnyString, requestParamOptional},
  816. {"ossh_prefix", isAnyString, requestParamOptional},
  817. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  818. {"tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  819. {"tls_ossh_sni_server_name", isDomain, requestParamOptional},
  820. {"tls_ossh_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  821. }
  822. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  823. var baseSessionAndDialParams = append(
  824. append(
  825. []requestParamSpec{},
  826. baseSessionParams...),
  827. baseDialParams...)
  828. func validateRequestParams(
  829. config *Config,
  830. params common.APIParameters,
  831. expectedParams []requestParamSpec) error {
  832. for _, expectedParam := range expectedParams {
  833. value := params[expectedParam.name]
  834. if value == nil {
  835. if expectedParam.flags&requestParamOptional != 0 {
  836. continue
  837. }
  838. return errors.Tracef("missing param: %s", expectedParam.name)
  839. }
  840. var err error
  841. switch {
  842. case expectedParam.flags&requestParamArray != 0:
  843. err = validateStringArrayRequestParam(config, expectedParam, value)
  844. case expectedParam.flags&requestParamJSON != 0:
  845. // No validation: the JSON already unmarshalled; the parameter
  846. // user will validate that the JSON contains the expected
  847. // objects/data.
  848. // TODO: without validation, any valid JSON will be logged
  849. // by getRequestLogFields, even if the parameter user validates
  850. // and rejects the parameter.
  851. default:
  852. err = validateStringRequestParam(config, expectedParam, value)
  853. }
  854. if err != nil {
  855. return errors.Trace(err)
  856. }
  857. }
  858. return nil
  859. }
  860. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  861. // the baseSessionAndDialParams.
  862. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  863. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  864. // scalar types (int, string, etc.)
  865. paramsCopy := make(common.APIParameters)
  866. for _, baseParam := range baseSessionAndDialParams {
  867. value := params[baseParam.name]
  868. if value == nil {
  869. continue
  870. }
  871. paramsCopy[baseParam.name] = value
  872. }
  873. return paramsCopy
  874. }
  875. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  876. // Note: not a deep copy
  877. paramsCopy := make(common.APIParameters)
  878. for _, name := range updateOnConnectedParamNames {
  879. value := params[name]
  880. if value == nil {
  881. continue
  882. }
  883. paramsCopy[name] = value
  884. }
  885. return paramsCopy
  886. }
  887. func validateStringRequestParam(
  888. config *Config,
  889. expectedParam requestParamSpec,
  890. value interface{}) error {
  891. strValue, ok := value.(string)
  892. if !ok {
  893. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  894. }
  895. if !expectedParam.validator(config, strValue) {
  896. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  897. }
  898. return nil
  899. }
  900. func validateStringArrayRequestParam(
  901. config *Config,
  902. expectedParam requestParamSpec,
  903. value interface{}) error {
  904. arrayValue, ok := value.([]interface{})
  905. if !ok {
  906. return errors.Tracef("unexpected array param type: %s", expectedParam.name)
  907. }
  908. for _, value := range arrayValue {
  909. err := validateStringRequestParam(config, expectedParam, value)
  910. if err != nil {
  911. return errors.Trace(err)
  912. }
  913. }
  914. return nil
  915. }
  916. // getRequestLogFields makes LogFields to log the API event following
  917. // the legacy psi_web and current ELK naming conventions.
  918. func getRequestLogFields(
  919. eventName string,
  920. geoIPData GeoIPData,
  921. authorizedAccessTypes []string,
  922. params common.APIParameters,
  923. expectedParams []requestParamSpec) LogFields {
  924. logFields := make(LogFields)
  925. if eventName != "" {
  926. logFields["event_name"] = eventName
  927. }
  928. geoIPData.SetLogFields(logFields)
  929. if len(authorizedAccessTypes) > 0 {
  930. logFields["authorized_access_types"] = authorizedAccessTypes
  931. }
  932. if params == nil {
  933. return logFields
  934. }
  935. for _, expectedParam := range expectedParams {
  936. if expectedParam.flags&requestParamNotLogged != 0 {
  937. continue
  938. }
  939. var tunnelProtocol string
  940. if value, ok := params["relay_protocol"]; ok {
  941. tunnelProtocol, _ = value.(string)
  942. }
  943. if expectedParam.flags&requestParamLogOnlyForFrontedMeekOrConjure != 0 &&
  944. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) &&
  945. !protocol.TunnelProtocolUsesConjure(tunnelProtocol) {
  946. continue
  947. }
  948. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  949. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  950. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  951. // Non-HTTP unfronted meek protocols never tranform the host header.
  952. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  953. continue
  954. }
  955. var transformedHostName string
  956. if value, ok := params["meek_transformed_host_name"]; ok {
  957. transformedHostName, _ = value.(string)
  958. }
  959. if transformedHostName != "1" {
  960. continue
  961. }
  962. }
  963. value := params[expectedParam.name]
  964. if value == nil {
  965. // Special case: older clients don't send this value,
  966. // so log a default.
  967. if expectedParam.name == "tunnel_whole_device" {
  968. value = "0"
  969. } else {
  970. // Skip omitted, optional params
  971. continue
  972. }
  973. }
  974. switch v := value.(type) {
  975. case string:
  976. strValue := v
  977. // Special cases:
  978. // - Number fields are encoded as integer types.
  979. // - For ELK performance we record certain domain-or-IP
  980. // fields as one of two different values based on type;
  981. // we also omit port from these host:port fields for now.
  982. // - Boolean fields that come into the api as "1"/"0"
  983. // must be logged as actual boolean values
  984. switch expectedParam.name {
  985. case "meek_dial_address":
  986. host, _, _ := net.SplitHostPort(strValue)
  987. if isIPAddress(nil, host) {
  988. logFields["meek_dial_ip_address"] = host
  989. } else {
  990. logFields["meek_dial_domain"] = host
  991. }
  992. case "upstream_proxy_type":
  993. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  994. logFields[expectedParam.name] = strings.ToLower(strValue)
  995. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  996. // Due to a client bug, clients may deliever an incorrect ""
  997. // value for speed_test_samples via the web API protocol. Omit
  998. // the field in this case.
  999. case "tunnel_error":
  1000. // net/url.Error, returned from net/url.Parse, contains the original input
  1001. // URL, which may contain PII. New clients strip this out by using
  1002. // common.SafeParseURL. Legacy clients will still send the full error
  1003. // message, so strip it out here. The target substring should be unique to
  1004. // legacy clients.
  1005. target := "upstreamproxy error: proxyURI url.Parse: parse "
  1006. index := strings.Index(strValue, target)
  1007. if index != -1 {
  1008. strValue = strValue[:index+len(target)] + "<redacted>"
  1009. }
  1010. logFields[expectedParam.name] = strValue
  1011. default:
  1012. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  1013. intValue, _ := strconv.Atoi(strValue)
  1014. logFields[expectedParam.name] = intValue
  1015. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  1016. floatValue, _ := strconv.ParseFloat(strValue, 64)
  1017. logFields[expectedParam.name] = floatValue
  1018. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  1019. logFields[expectedParam.name] = len(strValue)
  1020. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  1021. // Submitted value could be "0" or "1"
  1022. // "0" and non "0"/"1" values should be transformed to false
  1023. // "1" should be transformed to true
  1024. if strValue == "1" {
  1025. logFields[expectedParam.name] = true
  1026. } else {
  1027. logFields[expectedParam.name] = false
  1028. }
  1029. } else {
  1030. logFields[expectedParam.name] = strValue
  1031. }
  1032. }
  1033. case []interface{}:
  1034. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  1035. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  1036. } else {
  1037. logFields[expectedParam.name] = v
  1038. }
  1039. default:
  1040. logFields[expectedParam.name] = v
  1041. }
  1042. }
  1043. return logFields
  1044. }
  1045. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  1046. // fields to more verbose names for metrics.
  1047. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  1048. // TODO: use reflection and add additional tags, e.g.,
  1049. // `json:"s" log:"timestamp"` to remove hard-coded
  1050. // tag value dependency?
  1051. logSamples := make([]interface{}, len(samples))
  1052. for i, sample := range samples {
  1053. logSample := make(map[string]interface{})
  1054. if m, ok := sample.(map[string]interface{}); ok {
  1055. for k, v := range m {
  1056. logK := k
  1057. switch k {
  1058. case "s":
  1059. logK = "timestamp"
  1060. case "r":
  1061. logK = "server_region"
  1062. case "p":
  1063. logK = "relay_protocol"
  1064. case "t":
  1065. logK = "round_trip_time_ms"
  1066. case "u":
  1067. logK = "bytes_up"
  1068. case "d":
  1069. logK = "bytes_down"
  1070. }
  1071. logSample[logK] = v
  1072. }
  1073. }
  1074. logSamples[i] = logSample
  1075. }
  1076. return logSamples
  1077. }
  1078. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  1079. if params[name] == nil {
  1080. return "", false
  1081. }
  1082. value, ok := params[name].(string)
  1083. if !ok {
  1084. return "", false
  1085. }
  1086. return value, true
  1087. }
  1088. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  1089. if params[name] == nil {
  1090. return "", errors.Tracef("missing param: %s", name)
  1091. }
  1092. value, ok := params[name].(string)
  1093. if !ok {
  1094. return "", errors.Tracef("invalid param: %s", name)
  1095. }
  1096. return value, nil
  1097. }
  1098. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1099. if params[name] == nil {
  1100. return 0, errors.Tracef("missing param: %s", name)
  1101. }
  1102. valueStr, ok := params[name].(string)
  1103. if !ok {
  1104. return 0, errors.Tracef("invalid param: %s", name)
  1105. }
  1106. value, err := strconv.Atoi(valueStr)
  1107. if !ok {
  1108. return 0, errors.Trace(err)
  1109. }
  1110. return value, nil
  1111. }
  1112. func getBoolStringRequestParam(params common.APIParameters, name string) (bool, error) {
  1113. if params[name] == nil {
  1114. return false, errors.Tracef("missing param: %s", name)
  1115. }
  1116. valueStr, ok := params[name].(string)
  1117. if !ok {
  1118. return false, errors.Tracef("invalid param: %s", name)
  1119. }
  1120. if valueStr == "1" {
  1121. return true, nil
  1122. }
  1123. return false, nil
  1124. }
  1125. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1126. value, err := getIntStringRequestParam(params, name)
  1127. if err != nil {
  1128. return 0, errors.Trace(err)
  1129. }
  1130. if value < 0 {
  1131. value = 0
  1132. }
  1133. if value > PADDING_MAX_BYTES {
  1134. value = PADDING_MAX_BYTES
  1135. }
  1136. return int(value), nil
  1137. }
  1138. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1139. if params[name] == nil {
  1140. return nil, errors.Tracef("missing param: %s", name)
  1141. }
  1142. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1143. value, ok := params[name].(map[string]interface{})
  1144. if !ok {
  1145. return nil, errors.Tracef("invalid param: %s", name)
  1146. }
  1147. return common.APIParameters(value), nil
  1148. }
  1149. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1150. if params[name] == nil {
  1151. return nil, errors.Tracef("missing param: %s", name)
  1152. }
  1153. value, ok := params[name].([]interface{})
  1154. if !ok {
  1155. return nil, errors.Tracef("invalid param: %s", name)
  1156. }
  1157. result := make([]common.APIParameters, len(value))
  1158. for i, item := range value {
  1159. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1160. resultItem, ok := item.(map[string]interface{})
  1161. if !ok {
  1162. return nil, errors.Tracef("invalid param: %s", name)
  1163. }
  1164. result[i] = common.APIParameters(resultItem)
  1165. }
  1166. return result, nil
  1167. }
  1168. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1169. if params[name] == nil {
  1170. return nil, errors.Tracef("missing param: %s", name)
  1171. }
  1172. // TODO: can't use common.APIParameters type?
  1173. value, ok := params[name].(map[string]interface{})
  1174. if !ok {
  1175. return nil, errors.Tracef("invalid param: %s", name)
  1176. }
  1177. result := make(map[string]int64)
  1178. for k, v := range value {
  1179. numValue, ok := v.(float64)
  1180. if !ok {
  1181. return nil, errors.Tracef("invalid param: %s", name)
  1182. }
  1183. result[k] = int64(numValue)
  1184. }
  1185. return result, nil
  1186. }
  1187. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1188. if params[name] == nil {
  1189. return nil, errors.Tracef("missing param: %s", name)
  1190. }
  1191. value, ok := params[name].([]interface{})
  1192. if !ok {
  1193. return nil, errors.Tracef("invalid param: %s", name)
  1194. }
  1195. result := make([]string, len(value))
  1196. for i, v := range value {
  1197. strValue, ok := v.(string)
  1198. if !ok {
  1199. return nil, errors.Tracef("invalid param: %s", name)
  1200. }
  1201. result[i] = strValue
  1202. }
  1203. return result, nil
  1204. }
  1205. // Normalize reported client platform. Android clients, for example, report
  1206. // OS version, rooted status, and Google Play build status in the clientPlatform
  1207. // string along with "Android".
  1208. func normalizeClientPlatform(clientPlatform string) string {
  1209. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1210. return CLIENT_PLATFORM_ANDROID
  1211. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1212. return CLIENT_PLATFORM_IOS
  1213. }
  1214. return CLIENT_PLATFORM_WINDOWS
  1215. }
  1216. func isAnyString(config *Config, value string) bool {
  1217. return true
  1218. }
  1219. func isMobileClientPlatform(clientPlatform string) bool {
  1220. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1221. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1222. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1223. }
  1224. // Input validators follow the legacy validations rules in psi_web.
  1225. func isServerSecret(config *Config, value string) bool {
  1226. return subtle.ConstantTimeCompare(
  1227. []byte(value),
  1228. []byte(config.WebServerSecret)) == 1
  1229. }
  1230. func isHexDigits(_ *Config, value string) bool {
  1231. // Allows both uppercase in addition to lowercase, for legacy support.
  1232. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1233. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1234. })
  1235. }
  1236. func isBase64String(_ *Config, value string) bool {
  1237. _, err := base64.StdEncoding.DecodeString(value)
  1238. return err == nil
  1239. }
  1240. func isDigits(_ *Config, value string) bool {
  1241. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1242. return c < '0' || c > '9'
  1243. })
  1244. }
  1245. func isIntString(_ *Config, value string) bool {
  1246. _, err := strconv.Atoi(value)
  1247. return err == nil
  1248. }
  1249. func isFloatString(_ *Config, value string) bool {
  1250. _, err := strconv.ParseFloat(value, 64)
  1251. return err == nil
  1252. }
  1253. func isClientPlatform(_ *Config, value string) bool {
  1254. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1255. // Note: stricter than psi_web's Python string.whitespace
  1256. return unicode.Is(unicode.White_Space, c)
  1257. })
  1258. }
  1259. func isRelayProtocol(_ *Config, value string) bool {
  1260. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1261. }
  1262. func isBooleanFlag(_ *Config, value string) bool {
  1263. return value == "0" || value == "1"
  1264. }
  1265. func isUpstreamProxyType(_ *Config, value string) bool {
  1266. value = strings.ToLower(value)
  1267. return value == "http" || value == "socks5" || value == "socks4a"
  1268. }
  1269. func isRegionCode(_ *Config, value string) bool {
  1270. if len(value) != 2 {
  1271. return false
  1272. }
  1273. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1274. return c < 'A' || c > 'Z'
  1275. })
  1276. }
  1277. func isDialAddress(_ *Config, value string) bool {
  1278. // "<host>:<port>", where <host> is a domain or IP address
  1279. parts := strings.Split(value, ":")
  1280. if len(parts) != 2 {
  1281. return false
  1282. }
  1283. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1284. return false
  1285. }
  1286. if !isDigits(nil, parts[1]) {
  1287. return false
  1288. }
  1289. _, err := strconv.Atoi(parts[1])
  1290. if err != nil {
  1291. return false
  1292. }
  1293. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1294. return true
  1295. }
  1296. func isIPAddress(_ *Config, value string) bool {
  1297. return net.ParseIP(value) != nil
  1298. }
  1299. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1300. func isDomain(_ *Config, value string) bool {
  1301. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1302. //
  1303. // "ensures that each segment
  1304. // * contains at least one character and a maximum of 63 characters
  1305. // * consists only of allowed characters
  1306. // * doesn't begin or end with a hyphen"
  1307. //
  1308. if len(value) > 255 {
  1309. return false
  1310. }
  1311. value = strings.TrimSuffix(value, ".")
  1312. for _, part := range strings.Split(value, ".") {
  1313. // Note: regexp doesn't support the following Perl expression which
  1314. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1315. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1316. return false
  1317. }
  1318. if !isDomainRegex.Match([]byte(part)) {
  1319. return false
  1320. }
  1321. }
  1322. return true
  1323. }
  1324. func isHostHeader(_ *Config, value string) bool {
  1325. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1326. if strings.Contains(value, ":") {
  1327. return isDialAddress(nil, value)
  1328. }
  1329. return isIPAddress(nil, value) || isDomain(nil, value)
  1330. }
  1331. func isServerEntrySource(_ *Config, value string) bool {
  1332. return common.Contains(protocol.SupportedServerEntrySources, value)
  1333. }
  1334. var isISO8601DateRegex = regexp.MustCompile(
  1335. `(?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})))`)
  1336. func isISO8601Date(_ *Config, value string) bool {
  1337. return isISO8601DateRegex.Match([]byte(value))
  1338. }
  1339. func isLastConnected(_ *Config, value string) bool {
  1340. return value == "None" || isISO8601Date(nil, value)
  1341. }
  1342. const geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
  1343. func isGeoHashString(_ *Config, value string) bool {
  1344. // Verify that the string is between 1 and 12 characters long
  1345. // and contains only characters from the geohash alphabet.
  1346. if len(value) < 1 || len(value) > 12 {
  1347. return false
  1348. }
  1349. for _, c := range value {
  1350. if strings.Index(geohashAlphabet, string(c)) == -1 {
  1351. return false
  1352. }
  1353. }
  1354. return true
  1355. }