api.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  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. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  281. // the JSON response, return an empty array instead of null for legacy
  282. // clients.
  283. handshakeResponse := protocol.HandshakeResponse{
  284. SSHSessionID: sessionID,
  285. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, geoIPData.ASN, isMobile),
  286. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  287. PageViewRegexes: make([]map[string]string, 0),
  288. HttpsRequestRegexes: httpsRequestRegexes,
  289. EncodedServerList: encodedServerList,
  290. ClientRegion: geoIPData.Country,
  291. ServerTimestamp: common.GetCurrentTimestamp(),
  292. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  293. TacticsPayload: marshaledTacticsPayload,
  294. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  295. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  296. Padding: strings.Repeat(" ", pad_response),
  297. }
  298. responsePayload, err := json.Marshal(handshakeResponse)
  299. if err != nil {
  300. return nil, errors.Trace(err)
  301. }
  302. return responsePayload, nil
  303. }
  304. // uniqueUserParams are the connected request parameters which are logged for
  305. // unique_user events.
  306. var uniqueUserParams = append(
  307. []requestParamSpec{
  308. {"last_connected", isLastConnected, 0}},
  309. baseSessionParams...)
  310. var connectedRequestParams = append(
  311. []requestParamSpec{
  312. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  313. uniqueUserParams...)
  314. // updateOnConnectedParamNames are connected request parameters which are
  315. // copied to update data logged with server_tunnel: these fields either only
  316. // ship with or ship newer data with connected requests.
  317. var updateOnConnectedParamNames = append(
  318. []string{
  319. "last_connected",
  320. "establishment_duration",
  321. },
  322. fragmentor.GetUpstreamMetricsNames()...)
  323. // connectedAPIRequestHandler implements the "connected" API request. Clients
  324. // make the connected request once a tunnel connection has been established
  325. // and at least once per 24h for long-running tunnels. The last_connected
  326. // input value, which should be a connected_timestamp output from a previous
  327. // connected response, is used to calculate unique user stats.
  328. // connected_timestamp is truncated as a privacy measure.
  329. func connectedAPIRequestHandler(
  330. support *SupportServices,
  331. geoIPData GeoIPData,
  332. authorizedAccessTypes []string,
  333. params common.APIParameters) ([]byte, error) {
  334. err := validateRequestParams(support.Config, params, connectedRequestParams)
  335. if err != nil {
  336. return nil, errors.Trace(err)
  337. }
  338. sessionID, _ := getStringRequestParam(params, "client_session_id")
  339. lastConnected, _ := getStringRequestParam(params, "last_connected")
  340. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  341. // client may have performed more upstream fragmentation since the previous
  342. // metrics reported by the handshake request. Also, additional fields that
  343. // are reported only in the connected request are added to server_tunnel
  344. // here.
  345. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  346. // applies here.
  347. err = support.TunnelServer.UpdateClientAPIParameters(
  348. sessionID, copyUpdateOnConnectedParams(params))
  349. if err != nil {
  350. return nil, errors.Trace(err)
  351. }
  352. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  353. // The finest required granularity for unique users is daily. To save space,
  354. // only record a "unique_user" log event when the client's last_connected is
  355. // in the previous day relative to the new connected_timestamp.
  356. logUniqueUser := false
  357. if lastConnected == "None" {
  358. logUniqueUser = true
  359. } else {
  360. t1, _ := time.Parse(time.RFC3339, lastConnected)
  361. year, month, day := t1.Date()
  362. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  363. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  364. year, month, day = t2.Date()
  365. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  366. if t1.Before(t2) && d1 != d2 {
  367. logUniqueUser = true
  368. }
  369. }
  370. if logUniqueUser {
  371. log.LogRawFieldsWithTimestamp(
  372. getRequestLogFields(
  373. "unique_user",
  374. geoIPData,
  375. authorizedAccessTypes,
  376. params,
  377. uniqueUserParams))
  378. }
  379. // TODO: retire the legacy "connected" log event
  380. log.LogRawFieldsWithTimestamp(
  381. getRequestLogFields(
  382. "connected",
  383. geoIPData,
  384. authorizedAccessTypes,
  385. params,
  386. connectedRequestParams))
  387. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  388. connectedResponse := protocol.ConnectedResponse{
  389. ConnectedTimestamp: connectedTimestamp,
  390. Padding: strings.Repeat(" ", pad_response),
  391. }
  392. responsePayload, err := json.Marshal(connectedResponse)
  393. if err != nil {
  394. return nil, errors.Trace(err)
  395. }
  396. return responsePayload, nil
  397. }
  398. var statusRequestParams = baseSessionParams
  399. var remoteServerListStatParams = append(
  400. []requestParamSpec{
  401. {"client_download_timestamp", isISO8601Date, 0},
  402. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  403. {"url", isAnyString, 0},
  404. {"etag", isAnyString, 0},
  405. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  406. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  407. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool}},
  408. baseSessionParams...)
  409. // Backwards compatibility case: legacy clients do not include these fields in
  410. // the remote_server_list_stats entries. Use the values from the outer status
  411. // request as an approximation (these values reflect the client at persistent
  412. // stat shipping time, which may differ from the client at persistent stat
  413. // recording time). Note that all but client_build_rev and device_region are
  414. // required fields.
  415. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  416. "session_id",
  417. "propagation_channel_id",
  418. "sponsor_id",
  419. "client_version",
  420. "client_platform",
  421. "client_build_rev",
  422. "device_region",
  423. }
  424. var failedTunnelStatParams = append(
  425. []requestParamSpec{
  426. {"server_entry_tag", isAnyString, requestParamOptional},
  427. {"session_id", isHexDigits, 0},
  428. {"last_connected", isLastConnected, 0},
  429. {"client_failed_timestamp", isISO8601Date, 0},
  430. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  431. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  432. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  433. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  434. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  435. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  436. {"tunnel_error", isAnyString, 0}},
  437. baseSessionAndDialParams...)
  438. // statusAPIRequestHandler implements the "status" API request.
  439. // Clients make periodic status requests which deliver client-side
  440. // recorded data transfer and tunnel duration stats.
  441. // Note from psi_web implementation: no input validation on domains;
  442. // any string is accepted (regex transform may result in arbitrary
  443. // string). Stats processor must handle this input with care.
  444. func statusAPIRequestHandler(
  445. support *SupportServices,
  446. geoIPData GeoIPData,
  447. authorizedAccessTypes []string,
  448. params common.APIParameters) ([]byte, error) {
  449. err := validateRequestParams(support.Config, params, statusRequestParams)
  450. if err != nil {
  451. return nil, errors.Trace(err)
  452. }
  453. sessionID, _ := getStringRequestParam(params, "client_session_id")
  454. statusData, err := getJSONObjectRequestParam(params, "statusData")
  455. if err != nil {
  456. return nil, errors.Trace(err)
  457. }
  458. // Logs are queued until the input is fully validated. Otherwise, stats
  459. // could be double counted if the client has a bug in its request
  460. // formatting: partial stats would be logged (counted), the request would
  461. // fail, and clients would then resend all the same stats again.
  462. logQueue := make([]LogFields, 0)
  463. // Domain bytes transferred stats
  464. // Older clients may not submit this data
  465. // Clients are expected to send host_bytes/domain_bytes stats only when
  466. // configured to do so in the handshake reponse. Legacy clients may still
  467. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  468. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  469. if err != nil {
  470. return nil, errors.Trace(err)
  471. }
  472. if domainBytesExpected && statusData["host_bytes"] != nil {
  473. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  474. if err != nil {
  475. return nil, errors.Trace(err)
  476. }
  477. for domain, bytes := range hostBytes {
  478. domainBytesFields := getRequestLogFields(
  479. "domain_bytes",
  480. geoIPData,
  481. authorizedAccessTypes,
  482. params,
  483. statusRequestParams)
  484. domainBytesFields["domain"] = domain
  485. domainBytesFields["bytes"] = bytes
  486. logQueue = append(logQueue, domainBytesFields)
  487. }
  488. }
  489. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  490. // not time-of-recording.
  491. // Remote server list download persistent stats.
  492. // Older clients may not submit this data.
  493. if statusData["remote_server_list_stats"] != nil {
  494. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  495. if err != nil {
  496. return nil, errors.Trace(err)
  497. }
  498. for _, remoteServerListStat := range remoteServerListStats {
  499. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  500. if _, ok := remoteServerListStat[name]; !ok {
  501. if field, ok := params[name]; ok {
  502. remoteServerListStat[name] = field
  503. }
  504. }
  505. }
  506. // For validation, copy expected fields from the outer
  507. // statusRequestParams.
  508. remoteServerListStat["server_secret"] = params["server_secret"]
  509. remoteServerListStat["client_session_id"] = params["client_session_id"]
  510. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  511. if err != nil {
  512. // Occasionally, clients may send corrupt persistent stat data. Do not
  513. // fail the status request, as this will lead to endless retries.
  514. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  515. continue
  516. }
  517. remoteServerListFields := getRequestLogFields(
  518. "remote_server_list",
  519. geoIPData,
  520. authorizedAccessTypes,
  521. remoteServerListStat,
  522. remoteServerListStatParams)
  523. logQueue = append(logQueue, remoteServerListFields)
  524. }
  525. }
  526. // Failed tunnel persistent stats.
  527. // Older clients may not submit this data.
  528. var invalidServerEntryTags map[string]bool
  529. if statusData["failed_tunnel_stats"] != nil {
  530. // Note: no guarantee that PsinetDatabase won't reload between database calls
  531. db := support.PsinetDatabase
  532. invalidServerEntryTags = make(map[string]bool)
  533. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  534. if err != nil {
  535. return nil, errors.Trace(err)
  536. }
  537. for _, failedTunnelStat := range failedTunnelStats {
  538. // failed_tunnel supplies a full set of base params, but the server secret
  539. // must use the correct value from the outer statusRequestParams.
  540. failedTunnelStat["server_secret"] = params["server_secret"]
  541. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  542. if err != nil {
  543. // Occasionally, clients may send corrupt persistent stat data. Do not
  544. // fail the status request, as this will lead to endless retries.
  545. //
  546. // TODO: trigger pruning if the data corruption indicates corrupt server
  547. // entry storage?
  548. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  549. continue
  550. }
  551. failedTunnelFields := getRequestLogFields(
  552. "failed_tunnel",
  553. geoIPData,
  554. authorizedAccessTypes,
  555. failedTunnelStat,
  556. failedTunnelStatParams)
  557. // Return a list of servers, identified by server entry tag, that are
  558. // invalid and presumed to be deleted. This information is used by clients
  559. // to prune deleted servers from their local datastores and stop attempting
  560. // connections to servers that no longer exist.
  561. //
  562. // This mechanism uses tags instead of server IPs: (a) to prevent an
  563. // enumeration attack, where a malicious client can query the entire IPv4
  564. // range and build a map of the Psiphon network; (b) to deal with recyling
  565. // cases where a server deleted and its IP is reused for a new server with
  566. // a distinct server entry.
  567. //
  568. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  569. // before returning a negative result, to mitigate accidental pruning.
  570. //
  571. // In addition, when the reported dial port number is 0, flag the server
  572. // entry as invalid to trigger client pruning. This covers a class of
  573. // invalid/semi-functional server entries, found in practice to be stored
  574. // by clients, where some protocol port number has been omitted -- due to
  575. // historical bugs in various server entry handling implementations. When
  576. // missing from a server entry loaded by a client, the port number
  577. // evaluates to 0, the zero value, which is not a valid port number even if
  578. // were not missing.
  579. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  580. if ok {
  581. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  582. if serverEntryValid {
  583. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  584. if err == nil && dialPortNumber == 0 {
  585. serverEntryValid = false
  586. }
  587. }
  588. if !serverEntryValid {
  589. invalidServerEntryTags[serverEntryTag] = true
  590. }
  591. // Add a field to the failed_tunnel log indicating if the server entry is
  592. // valid.
  593. failedTunnelFields["server_entry_valid"] = serverEntryValid
  594. }
  595. // Log failed_tunnel.
  596. logQueue = append(logQueue, failedTunnelFields)
  597. }
  598. }
  599. for _, logItem := range logQueue {
  600. log.LogRawFieldsWithTimestamp(logItem)
  601. }
  602. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  603. statusResponse := protocol.StatusResponse{
  604. Padding: strings.Repeat(" ", pad_response),
  605. }
  606. if len(invalidServerEntryTags) > 0 {
  607. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  608. i := 0
  609. for tag := range invalidServerEntryTags {
  610. statusResponse.InvalidServerEntryTags[i] = tag
  611. i++
  612. }
  613. }
  614. responsePayload, err := json.Marshal(statusResponse)
  615. if err != nil {
  616. return nil, errors.Trace(err)
  617. }
  618. return responsePayload, nil
  619. }
  620. // clientVerificationAPIRequestHandler is just a compliance stub
  621. // for older Android clients that still send verification requests
  622. func clientVerificationAPIRequestHandler(
  623. support *SupportServices,
  624. geoIPData GeoIPData,
  625. authorizedAccessTypes []string,
  626. params common.APIParameters) ([]byte, error) {
  627. return make([]byte, 0), nil
  628. }
  629. var tacticsParams = []requestParamSpec{
  630. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  631. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  632. }
  633. var tacticsRequestParams = append(
  634. append([]requestParamSpec(nil), tacticsParams...),
  635. baseSessionAndDialParams...)
  636. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  637. return func(params common.APIParameters) error {
  638. return validateRequestParams(config, params, tacticsRequestParams)
  639. }
  640. }
  641. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  642. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  643. logFields := getRequestLogFields(
  644. tactics.TACTICS_METRIC_EVENT_NAME,
  645. GeoIPData(geoIPData),
  646. nil, // authorizedAccessTypes are not known yet
  647. params,
  648. tacticsRequestParams)
  649. return common.LogFields(logFields)
  650. }
  651. }
  652. // requestParamSpec defines a request parameter. Each param is expected to be
  653. // a string, unless requestParamArray is specified, in which case an array of
  654. // strings is expected.
  655. type requestParamSpec struct {
  656. name string
  657. validator func(*Config, string) bool
  658. flags uint32
  659. }
  660. const (
  661. requestParamOptional = 1
  662. requestParamNotLogged = 1 << 1
  663. requestParamArray = 1 << 2
  664. requestParamJSON = 1 << 3
  665. requestParamLogStringAsInt = 1 << 4
  666. requestParamLogStringAsFloat = 1 << 5
  667. requestParamLogStringLengthAsInt = 1 << 6
  668. requestParamLogFlagAsBool = 1 << 7
  669. requestParamLogOnlyForFrontedMeek = 1 << 8
  670. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  671. )
  672. // baseParams are the basic request parameters that are expected for all API
  673. // requests and log events.
  674. var baseParams = []requestParamSpec{
  675. {"server_secret", isServerSecret, requestParamNotLogged},
  676. {"client_session_id", isHexDigits, requestParamNotLogged},
  677. {"propagation_channel_id", isHexDigits, 0},
  678. {"sponsor_id", isHexDigits, 0},
  679. {"client_version", isIntString, requestParamLogStringAsInt},
  680. {"client_platform", isClientPlatform, 0},
  681. {"client_build_rev", isHexDigits, requestParamOptional},
  682. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  683. {"device_region", isAnyString, requestParamOptional},
  684. }
  685. // baseSessionParams adds to baseParams the required session_id parameter. For
  686. // all requests except handshake, all existing clients are expected to send
  687. // session_id. Legacy clients may not send "session_id" in handshake.
  688. var baseSessionParams = append(
  689. []requestParamSpec{
  690. {"session_id", isHexDigits, 0}},
  691. baseParams...)
  692. // baseDialParams are the dial parameters, per-tunnel network protocol and
  693. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  694. // tactics.
  695. var baseDialParams = []requestParamSpec{
  696. {"relay_protocol", isRelayProtocol, 0},
  697. {"ssh_client_version", isAnyString, requestParamOptional},
  698. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  699. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  700. {"fronting_provider_id", isAnyString, requestParamOptional},
  701. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  702. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  703. {"meek_sni_server_name", isDomain, requestParamOptional},
  704. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  705. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  706. {"user_agent", isAnyString, requestParamOptional},
  707. {"tls_profile", isAnyString, requestParamOptional},
  708. {"tls_version", isAnyString, requestParamOptional},
  709. {"server_entry_region", isRegionCode, requestParamOptional},
  710. {"server_entry_source", isServerEntrySource, requestParamOptional},
  711. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  712. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  713. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  714. {"quic_version", isAnyString, requestParamOptional},
  715. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  716. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  717. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  718. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  719. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  720. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  721. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  722. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  723. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  724. {"egress_region", isRegionCode, requestParamOptional},
  725. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  726. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  727. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  728. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  729. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  730. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  731. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  732. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  733. {"client_bpf", isAnyString, requestParamOptional},
  734. {"network_type", isAnyString, requestParamOptional},
  735. }
  736. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  737. var baseSessionAndDialParams = append(
  738. append(
  739. []requestParamSpec{},
  740. baseSessionParams...),
  741. baseDialParams...)
  742. func validateRequestParams(
  743. config *Config,
  744. params common.APIParameters,
  745. expectedParams []requestParamSpec) error {
  746. for _, expectedParam := range expectedParams {
  747. value := params[expectedParam.name]
  748. if value == nil {
  749. if expectedParam.flags&requestParamOptional != 0 {
  750. continue
  751. }
  752. return errors.Tracef("missing param: %s", expectedParam.name)
  753. }
  754. var err error
  755. switch {
  756. case expectedParam.flags&requestParamArray != 0:
  757. err = validateStringArrayRequestParam(config, expectedParam, value)
  758. case expectedParam.flags&requestParamJSON != 0:
  759. // No validation: the JSON already unmarshalled; the parameter
  760. // user will validate that the JSON contains the expected
  761. // objects/data.
  762. // TODO: without validation, any valid JSON will be logged
  763. // by getRequestLogFields, even if the parameter user validates
  764. // and rejects the parameter.
  765. default:
  766. err = validateStringRequestParam(config, expectedParam, value)
  767. }
  768. if err != nil {
  769. return errors.Trace(err)
  770. }
  771. }
  772. return nil
  773. }
  774. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  775. // the baseSessionAndDialParams.
  776. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  777. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  778. // scalar types (int, string, etc.)
  779. paramsCopy := make(common.APIParameters)
  780. for _, baseParam := range baseSessionAndDialParams {
  781. value := params[baseParam.name]
  782. if value == nil {
  783. continue
  784. }
  785. paramsCopy[baseParam.name] = value
  786. }
  787. return paramsCopy
  788. }
  789. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  790. // Note: not a deep copy
  791. paramsCopy := make(common.APIParameters)
  792. for _, name := range updateOnConnectedParamNames {
  793. value := params[name]
  794. if value == nil {
  795. continue
  796. }
  797. paramsCopy[name] = value
  798. }
  799. return paramsCopy
  800. }
  801. func validateStringRequestParam(
  802. config *Config,
  803. expectedParam requestParamSpec,
  804. value interface{}) error {
  805. strValue, ok := value.(string)
  806. if !ok {
  807. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  808. }
  809. if !expectedParam.validator(config, strValue) {
  810. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  811. }
  812. return nil
  813. }
  814. func validateStringArrayRequestParam(
  815. config *Config,
  816. expectedParam requestParamSpec,
  817. value interface{}) error {
  818. arrayValue, ok := value.([]interface{})
  819. if !ok {
  820. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  821. }
  822. for _, value := range arrayValue {
  823. err := validateStringRequestParam(config, expectedParam, value)
  824. if err != nil {
  825. return errors.Trace(err)
  826. }
  827. }
  828. return nil
  829. }
  830. // getRequestLogFields makes LogFields to log the API event following
  831. // the legacy psi_web and current ELK naming conventions.
  832. func getRequestLogFields(
  833. eventName string,
  834. geoIPData GeoIPData,
  835. authorizedAccessTypes []string,
  836. params common.APIParameters,
  837. expectedParams []requestParamSpec) LogFields {
  838. logFields := make(LogFields)
  839. if eventName != "" {
  840. logFields["event_name"] = eventName
  841. }
  842. geoIPData.SetLogFields(logFields)
  843. if len(authorizedAccessTypes) > 0 {
  844. logFields["authorized_access_types"] = authorizedAccessTypes
  845. }
  846. if params == nil {
  847. return logFields
  848. }
  849. for _, expectedParam := range expectedParams {
  850. if expectedParam.flags&requestParamNotLogged != 0 {
  851. continue
  852. }
  853. var tunnelProtocol string
  854. if value, ok := params["relay_protocol"]; ok {
  855. tunnelProtocol, _ = value.(string)
  856. }
  857. if expectedParam.flags&requestParamLogOnlyForFrontedMeek != 0 &&
  858. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  859. continue
  860. }
  861. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  862. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  863. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  864. // Non-HTTP unfronted meek protocols never tranform the host header.
  865. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  866. continue
  867. }
  868. var transformedHostName string
  869. if value, ok := params["meek_transformed_host_name"]; ok {
  870. transformedHostName, _ = value.(string)
  871. }
  872. if transformedHostName != "1" {
  873. continue
  874. }
  875. }
  876. value := params[expectedParam.name]
  877. if value == nil {
  878. // Special case: older clients don't send this value,
  879. // so log a default.
  880. if expectedParam.name == "tunnel_whole_device" {
  881. value = "0"
  882. } else {
  883. // Skip omitted, optional params
  884. continue
  885. }
  886. }
  887. switch v := value.(type) {
  888. case string:
  889. strValue := v
  890. // Special cases:
  891. // - Number fields are encoded as integer types.
  892. // - For ELK performance we record certain domain-or-IP
  893. // fields as one of two different values based on type;
  894. // we also omit port from these host:port fields for now.
  895. // - Boolean fields that come into the api as "1"/"0"
  896. // must be logged as actual boolean values
  897. switch expectedParam.name {
  898. case "meek_dial_address":
  899. host, _, _ := net.SplitHostPort(strValue)
  900. if isIPAddress(nil, host) {
  901. logFields["meek_dial_ip_address"] = host
  902. } else {
  903. logFields["meek_dial_domain"] = host
  904. }
  905. case "upstream_proxy_type":
  906. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  907. logFields[expectedParam.name] = strings.ToLower(strValue)
  908. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  909. // Due to a client bug, clients may deliever an incorrect ""
  910. // value for speed_test_samples via the web API protocol. Omit
  911. // the field in this case.
  912. case "tunnel_error":
  913. // net/url.Error, returned from net/url.Parse, contains the original input
  914. // URL, which may contain PII. New clients strip this out by using
  915. // common.SafeParseURL. Legacy clients will still send the full error
  916. // message, so strip it out here. The target substring should be unique to
  917. // legacy clients.
  918. target := "upstreamproxy error: proxyURI url.Parse: parse "
  919. index := strings.Index(strValue, target)
  920. if index != -1 {
  921. strValue = strValue[:index+len(target)] + "<redacted>"
  922. }
  923. logFields[expectedParam.name] = strValue
  924. default:
  925. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  926. intValue, _ := strconv.Atoi(strValue)
  927. logFields[expectedParam.name] = intValue
  928. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  929. floatValue, _ := strconv.ParseFloat(strValue, 64)
  930. logFields[expectedParam.name] = floatValue
  931. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  932. logFields[expectedParam.name] = len(strValue)
  933. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  934. // Submitted value could be "0" or "1"
  935. // "0" and non "0"/"1" values should be transformed to false
  936. // "1" should be transformed to true
  937. if strValue == "1" {
  938. logFields[expectedParam.name] = true
  939. } else {
  940. logFields[expectedParam.name] = false
  941. }
  942. } else {
  943. logFields[expectedParam.name] = strValue
  944. }
  945. }
  946. case []interface{}:
  947. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  948. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  949. } else {
  950. logFields[expectedParam.name] = v
  951. }
  952. default:
  953. logFields[expectedParam.name] = v
  954. }
  955. }
  956. return logFields
  957. }
  958. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  959. // fields to more verbose names for metrics.
  960. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  961. // TODO: use reflection and add additional tags, e.g.,
  962. // `json:"s" log:"timestamp"` to remove hard-coded
  963. // tag value dependency?
  964. logSamples := make([]interface{}, len(samples))
  965. for i, sample := range samples {
  966. logSample := make(map[string]interface{})
  967. if m, ok := sample.(map[string]interface{}); ok {
  968. for k, v := range m {
  969. logK := k
  970. switch k {
  971. case "s":
  972. logK = "timestamp"
  973. case "r":
  974. logK = "server_region"
  975. case "p":
  976. logK = "relay_protocol"
  977. case "t":
  978. logK = "round_trip_time_ms"
  979. case "u":
  980. logK = "bytes_up"
  981. case "d":
  982. logK = "bytes_down"
  983. }
  984. logSample[logK] = v
  985. }
  986. }
  987. logSamples[i] = logSample
  988. }
  989. return logSamples
  990. }
  991. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  992. if params[name] == nil {
  993. return "", false
  994. }
  995. value, ok := params[name].(string)
  996. if !ok {
  997. return "", false
  998. }
  999. return value, true
  1000. }
  1001. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  1002. if params[name] == nil {
  1003. return "", errors.Tracef("missing param: %s", name)
  1004. }
  1005. value, ok := params[name].(string)
  1006. if !ok {
  1007. return "", errors.Tracef("invalid param: %s", name)
  1008. }
  1009. return value, nil
  1010. }
  1011. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1012. if params[name] == nil {
  1013. return 0, errors.Tracef("missing param: %s", name)
  1014. }
  1015. valueStr, ok := params[name].(string)
  1016. if !ok {
  1017. return 0, errors.Tracef("invalid param: %s", name)
  1018. }
  1019. value, err := strconv.Atoi(valueStr)
  1020. if !ok {
  1021. return 0, errors.Trace(err)
  1022. }
  1023. return value, nil
  1024. }
  1025. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1026. value, err := getIntStringRequestParam(params, name)
  1027. if err != nil {
  1028. return 0, errors.Trace(err)
  1029. }
  1030. if value < 0 {
  1031. value = 0
  1032. }
  1033. if value > PADDING_MAX_BYTES {
  1034. value = PADDING_MAX_BYTES
  1035. }
  1036. return int(value), nil
  1037. }
  1038. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1039. if params[name] == nil {
  1040. return nil, errors.Tracef("missing param: %s", name)
  1041. }
  1042. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1043. value, ok := params[name].(map[string]interface{})
  1044. if !ok {
  1045. return nil, errors.Tracef("invalid param: %s", name)
  1046. }
  1047. return common.APIParameters(value), nil
  1048. }
  1049. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1050. if params[name] == nil {
  1051. return nil, errors.Tracef("missing param: %s", name)
  1052. }
  1053. value, ok := params[name].([]interface{})
  1054. if !ok {
  1055. return nil, errors.Tracef("invalid param: %s", name)
  1056. }
  1057. result := make([]common.APIParameters, len(value))
  1058. for i, item := range value {
  1059. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1060. resultItem, ok := item.(map[string]interface{})
  1061. if !ok {
  1062. return nil, errors.Tracef("invalid param: %s", name)
  1063. }
  1064. result[i] = common.APIParameters(resultItem)
  1065. }
  1066. return result, nil
  1067. }
  1068. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1069. if params[name] == nil {
  1070. return nil, errors.Tracef("missing param: %s", name)
  1071. }
  1072. // TODO: can't use common.APIParameters type?
  1073. value, ok := params[name].(map[string]interface{})
  1074. if !ok {
  1075. return nil, errors.Tracef("invalid param: %s", name)
  1076. }
  1077. result := make(map[string]int64)
  1078. for k, v := range value {
  1079. numValue, ok := v.(float64)
  1080. if !ok {
  1081. return nil, errors.Tracef("invalid param: %s", name)
  1082. }
  1083. result[k] = int64(numValue)
  1084. }
  1085. return result, nil
  1086. }
  1087. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1088. if params[name] == nil {
  1089. return nil, errors.Tracef("missing param: %s", name)
  1090. }
  1091. value, ok := params[name].([]interface{})
  1092. if !ok {
  1093. return nil, errors.Tracef("invalid param: %s", name)
  1094. }
  1095. result := make([]string, len(value))
  1096. for i, v := range value {
  1097. strValue, ok := v.(string)
  1098. if !ok {
  1099. return nil, errors.Tracef("invalid param: %s", name)
  1100. }
  1101. result[i] = strValue
  1102. }
  1103. return result, nil
  1104. }
  1105. // Normalize reported client platform. Android clients, for example, report
  1106. // OS version, rooted status, and Google Play build status in the clientPlatform
  1107. // string along with "Android".
  1108. func normalizeClientPlatform(clientPlatform string) string {
  1109. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1110. return CLIENT_PLATFORM_ANDROID
  1111. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1112. return CLIENT_PLATFORM_IOS
  1113. }
  1114. return CLIENT_PLATFORM_WINDOWS
  1115. }
  1116. func isAnyString(config *Config, value string) bool {
  1117. return true
  1118. }
  1119. func isMobileClientPlatform(clientPlatform string) bool {
  1120. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1121. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1122. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1123. }
  1124. // Input validators follow the legacy validations rules in psi_web.
  1125. func isServerSecret(config *Config, value string) bool {
  1126. return subtle.ConstantTimeCompare(
  1127. []byte(value),
  1128. []byte(config.WebServerSecret)) == 1
  1129. }
  1130. func isHexDigits(_ *Config, value string) bool {
  1131. // Allows both uppercase in addition to lowercase, for legacy support.
  1132. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1133. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1134. })
  1135. }
  1136. func isBase64String(_ *Config, value string) bool {
  1137. _, err := base64.StdEncoding.DecodeString(value)
  1138. return err == nil
  1139. }
  1140. func isDigits(_ *Config, value string) bool {
  1141. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1142. return c < '0' || c > '9'
  1143. })
  1144. }
  1145. func isIntString(_ *Config, value string) bool {
  1146. _, err := strconv.Atoi(value)
  1147. return err == nil
  1148. }
  1149. func isFloatString(_ *Config, value string) bool {
  1150. _, err := strconv.ParseFloat(value, 64)
  1151. return err == nil
  1152. }
  1153. func isClientPlatform(_ *Config, value string) bool {
  1154. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1155. // Note: stricter than psi_web's Python string.whitespace
  1156. return unicode.Is(unicode.White_Space, c)
  1157. })
  1158. }
  1159. func isRelayProtocol(_ *Config, value string) bool {
  1160. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1161. }
  1162. func isBooleanFlag(_ *Config, value string) bool {
  1163. return value == "0" || value == "1"
  1164. }
  1165. func isUpstreamProxyType(_ *Config, value string) bool {
  1166. value = strings.ToLower(value)
  1167. return value == "http" || value == "socks5" || value == "socks4a"
  1168. }
  1169. func isRegionCode(_ *Config, value string) bool {
  1170. if len(value) != 2 {
  1171. return false
  1172. }
  1173. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1174. return c < 'A' || c > 'Z'
  1175. })
  1176. }
  1177. func isDialAddress(_ *Config, value string) bool {
  1178. // "<host>:<port>", where <host> is a domain or IP address
  1179. parts := strings.Split(value, ":")
  1180. if len(parts) != 2 {
  1181. return false
  1182. }
  1183. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1184. return false
  1185. }
  1186. if !isDigits(nil, parts[1]) {
  1187. return false
  1188. }
  1189. _, err := strconv.Atoi(parts[1])
  1190. if err != nil {
  1191. return false
  1192. }
  1193. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1194. return true
  1195. }
  1196. func isIPAddress(_ *Config, value string) bool {
  1197. return net.ParseIP(value) != nil
  1198. }
  1199. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1200. func isDomain(_ *Config, value string) bool {
  1201. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1202. //
  1203. // "ensures that each segment
  1204. // * contains at least one character and a maximum of 63 characters
  1205. // * consists only of allowed characters
  1206. // * doesn't begin or end with a hyphen"
  1207. //
  1208. if len(value) > 255 {
  1209. return false
  1210. }
  1211. value = strings.TrimSuffix(value, ".")
  1212. for _, part := range strings.Split(value, ".") {
  1213. // Note: regexp doesn't support the following Perl expression which
  1214. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1215. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1216. return false
  1217. }
  1218. if !isDomainRegex.Match([]byte(part)) {
  1219. return false
  1220. }
  1221. }
  1222. return true
  1223. }
  1224. func isHostHeader(_ *Config, value string) bool {
  1225. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1226. if strings.Contains(value, ":") {
  1227. return isDialAddress(nil, value)
  1228. }
  1229. return isIPAddress(nil, value) || isDomain(nil, value)
  1230. }
  1231. func isServerEntrySource(_ *Config, value string) bool {
  1232. return common.Contains(protocol.SupportedServerEntrySources, value)
  1233. }
  1234. var isISO8601DateRegex = regexp.MustCompile(
  1235. `(?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})))`)
  1236. func isISO8601Date(_ *Config, value string) bool {
  1237. return isISO8601DateRegex.Match([]byte(value))
  1238. }
  1239. func isLastConnected(_ *Config, value string) bool {
  1240. return value == "None" || isISO8601Date(nil, value)
  1241. }