api.go 47 KB

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