api.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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/json"
  23. "errors"
  24. "fmt"
  25. "net"
  26. "regexp"
  27. "runtime/debug"
  28. "strconv"
  29. "strings"
  30. "unicode"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  34. )
  35. const (
  36. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  37. CLIENT_PLATFORM_ANDROID = "Android"
  38. CLIENT_PLATFORM_WINDOWS = "Windows"
  39. CLIENT_PLATFORM_IOS = "iOS"
  40. )
  41. // sshAPIRequestHandler routes Psiphon API requests transported as
  42. // JSON objects via the SSH request mechanism.
  43. //
  44. // The API request handlers, handshakeAPIRequestHandler, etc., are
  45. // reused by webServer which offers the Psiphon API via web transport.
  46. //
  47. // The API request parameters and event log values follow the legacy
  48. // psi_web protocol and naming conventions. The API is compatible with
  49. // all tunnel-core clients but are not backwards compatible with all
  50. // legacy clients.
  51. //
  52. func sshAPIRequestHandler(
  53. support *SupportServices,
  54. geoIPData GeoIPData,
  55. authorizedAccessTypes []string,
  56. name string,
  57. requestPayload []byte) ([]byte, error) {
  58. // Notes:
  59. //
  60. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  61. // by max SSH request packet size.
  62. //
  63. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  64. // array of base64-encoded strings; the base64 representation should
  65. // not be decoded to []byte values. The default behavior of
  66. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  67. // type map[string]interface{} will unmarshal a base64-encoded string
  68. // to a string, not a decoded []byte, as required.
  69. var params common.APIParameters
  70. err := json.Unmarshal(requestPayload, &params)
  71. if err != nil {
  72. return nil, common.ContextError(
  73. fmt.Errorf("invalid payload for request name: %s: %s", name, err))
  74. }
  75. return dispatchAPIRequestHandler(
  76. support,
  77. protocol.PSIPHON_SSH_API_PROTOCOL,
  78. geoIPData,
  79. authorizedAccessTypes,
  80. name,
  81. params)
  82. }
  83. // dispatchAPIRequestHandler is the common dispatch point for both
  84. // web and SSH API requests.
  85. func dispatchAPIRequestHandler(
  86. support *SupportServices,
  87. apiProtocol string,
  88. geoIPData GeoIPData,
  89. authorizedAccessTypes []string,
  90. name string,
  91. params common.APIParameters) (response []byte, reterr error) {
  92. // Recover from and log any unexpected panics caused by user input
  93. // handling bugs. User inputs should be properly validated; this
  94. // mechanism is only a last resort to prevent the process from
  95. // terminating in the case of a bug.
  96. defer func() {
  97. if e := recover(); e != nil {
  98. if intentionalPanic, ok := e.(IntentionalPanicError); ok {
  99. panic(intentionalPanic)
  100. } else {
  101. log.LogPanicRecover(e, debug.Stack())
  102. reterr = common.ContextError(errors.New("request handler panic"))
  103. }
  104. }
  105. }()
  106. // Before invoking the handlers, enforce some preconditions:
  107. //
  108. // - A handshake request must precede any other requests.
  109. // - When the handshake results in a traffic rules state where
  110. // the client is immediately exhausted, no requests
  111. // may succeed. This case ensures that blocked clients do
  112. // not log "connected", etc.
  113. //
  114. // Only one handshake request may be made. There is no check here
  115. // to enforce that handshakeAPIRequestHandler will be called at
  116. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  117. // enforces that only a single handshake is made; enforcing that there
  118. // ensures no race condition even if concurrent requests are
  119. // in flight.
  120. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  121. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  122. // applies here.
  123. sessionID, err := getStringRequestParam(params, "client_session_id")
  124. if err == nil {
  125. // Note: follows/duplicates baseRequestParams validation
  126. if !isHexDigits(support.Config, sessionID) {
  127. err = errors.New("invalid param: client_session_id")
  128. }
  129. }
  130. if err != nil {
  131. return nil, common.ContextError(err)
  132. }
  133. completed, exhausted, err := support.TunnelServer.GetClientHandshaked(sessionID)
  134. if err != nil {
  135. return nil, common.ContextError(err)
  136. }
  137. if !completed {
  138. return nil, common.ContextError(errors.New("handshake not completed"))
  139. }
  140. if exhausted {
  141. return nil, common.ContextError(errors.New("exhausted after handshake"))
  142. }
  143. }
  144. switch name {
  145. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  146. return handshakeAPIRequestHandler(support, apiProtocol, geoIPData, params)
  147. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  148. return connectedAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  149. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  150. return statusAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  151. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  152. return clientVerificationAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  153. }
  154. return nil, common.ContextError(fmt.Errorf("invalid request name: %s", name))
  155. }
  156. var handshakeRequestParams = append(
  157. append(
  158. // Note: legacy clients may not send "session_id" in handshake
  159. []requestParamSpec{{"session_id", isHexDigits, requestParamOptional}},
  160. tacticsParams...),
  161. baseRequestParams...)
  162. // handshakeAPIRequestHandler implements the "handshake" API request.
  163. // Clients make the handshake immediately after establishing a tunnel
  164. // connection; the response tells the client what homepage to open, what
  165. // stats to record, etc.
  166. func handshakeAPIRequestHandler(
  167. support *SupportServices,
  168. apiProtocol string,
  169. geoIPData GeoIPData,
  170. params common.APIParameters) ([]byte, error) {
  171. // Note: ignoring "known_servers" params
  172. err := validateRequestParams(support.Config, params, baseRequestParams)
  173. if err != nil {
  174. return nil, common.ContextError(err)
  175. }
  176. sessionID, _ := getStringRequestParam(params, "client_session_id")
  177. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  178. clientVersion, _ := getStringRequestParam(params, "client_version")
  179. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  180. isMobile := isMobileClientPlatform(clientPlatform)
  181. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  182. var authorizations []string
  183. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  184. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  185. if err != nil {
  186. return nil, common.ContextError(err)
  187. }
  188. }
  189. // Note: no guarantee that PsinetDatabase won't reload between database calls
  190. db := support.PsinetDatabase
  191. httpsRequestRegexes := db.GetHttpsRequestRegexes(sponsorID)
  192. // Flag the SSH client as having completed its handshake. This
  193. // may reselect traffic rules and starts allowing port forwards.
  194. // TODO: in the case of SSH API requests, the actual sshClient could
  195. // be passed in and used here. The session ID lookup is only strictly
  196. // necessary to support web API requests.
  197. activeAuthorizationIDs, authorizedAccessTypes, err := support.TunnelServer.SetClientHandshakeState(
  198. sessionID,
  199. handshakeState{
  200. completed: true,
  201. apiProtocol: apiProtocol,
  202. apiParams: copyBaseRequestParams(params),
  203. expectDomainBytes: len(httpsRequestRegexes) > 0,
  204. },
  205. authorizations)
  206. if err != nil {
  207. return nil, common.ContextError(err)
  208. }
  209. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  210. common.GeoIPData(geoIPData), params)
  211. if err != nil {
  212. return nil, common.ContextError(err)
  213. }
  214. var marshaledTacticsPayload []byte
  215. if tacticsPayload != nil {
  216. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  217. if err != nil {
  218. return nil, common.ContextError(err)
  219. }
  220. // Log a metric when new tactics are issued. Logging here indicates that
  221. // the handshake tactics mechansim is active; but logging for every
  222. // handshake creates unneccesary log data.
  223. if len(tacticsPayload.Tactics) > 0 {
  224. logFields := getRequestLogFields(
  225. tactics.TACTICS_METRIC_EVENT_NAME,
  226. geoIPData,
  227. authorizedAccessTypes,
  228. params,
  229. handshakeRequestParams)
  230. logFields[tactics.NEW_TACTICS_TAG_LOG_FIELD_NAME] = tacticsPayload.Tag
  231. logFields[tactics.IS_TACTICS_REQUEST_LOG_FIELD_NAME] = false
  232. log.LogRawFieldsWithTimestamp(logFields)
  233. }
  234. }
  235. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  236. // the state change (for example, if a second handshake is performed)
  237. //
  238. // The handshake event is no longer shipped to log consumers, so this is
  239. // simply a diagnostic log. Since the "server_tunnel" event includes all
  240. // common API parameters and "handshake_completed" flag, this handshake
  241. // log is mostly redundant and set to debug level.
  242. log.WithContextFields(
  243. getRequestLogFields(
  244. "",
  245. geoIPData,
  246. authorizedAccessTypes,
  247. params,
  248. baseRequestParams)).Debug("handshake")
  249. handshakeResponse := protocol.HandshakeResponse{
  250. SSHSessionID: sessionID,
  251. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, isMobile),
  252. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  253. PageViewRegexes: make([]map[string]string, 0),
  254. HttpsRequestRegexes: httpsRequestRegexes,
  255. EncodedServerList: db.DiscoverServers(geoIPData.DiscoveryValue),
  256. ClientRegion: geoIPData.Country,
  257. ServerTimestamp: common.GetCurrentTimestamp(),
  258. ActiveAuthorizationIDs: activeAuthorizationIDs,
  259. TacticsPayload: marshaledTacticsPayload,
  260. }
  261. responsePayload, err := json.Marshal(handshakeResponse)
  262. if err != nil {
  263. return nil, common.ContextError(err)
  264. }
  265. return responsePayload, nil
  266. }
  267. var connectedRequestParams = append(
  268. []requestParamSpec{
  269. {"session_id", isHexDigits, 0},
  270. {"last_connected", isLastConnected, 0},
  271. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  272. baseRequestParams...)
  273. // connectedAPIRequestHandler implements the "connected" API request.
  274. // Clients make the connected request once a tunnel connection has been
  275. // established and at least once per day. The last_connected input value,
  276. // which should be a connected_timestamp output from a previous connected
  277. // response, is used to calculate unique user stats.
  278. // connected_timestamp is truncated as a privacy measure.
  279. func connectedAPIRequestHandler(
  280. support *SupportServices,
  281. geoIPData GeoIPData,
  282. authorizedAccessTypes []string,
  283. params common.APIParameters) ([]byte, error) {
  284. err := validateRequestParams(support.Config, params, connectedRequestParams)
  285. if err != nil {
  286. return nil, common.ContextError(err)
  287. }
  288. // Update upstream fragmentor metrics, as the client may have performed
  289. // more upstream fragmentation since the previous metrics reported by the
  290. // handshake request.
  291. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  292. // applies here.
  293. sessionID, _ := getStringRequestParam(params, "client_session_id")
  294. err = support.TunnelServer.UpdateClientAPIParameters(
  295. sessionID, copyUpstreamFragmentorParams(params))
  296. if err != nil {
  297. return nil, common.ContextError(err)
  298. }
  299. log.LogRawFieldsWithTimestamp(
  300. getRequestLogFields(
  301. "connected",
  302. geoIPData,
  303. authorizedAccessTypes,
  304. params,
  305. connectedRequestParams))
  306. connectedResponse := protocol.ConnectedResponse{
  307. ConnectedTimestamp: common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  308. }
  309. responsePayload, err := json.Marshal(connectedResponse)
  310. if err != nil {
  311. return nil, common.ContextError(err)
  312. }
  313. return responsePayload, nil
  314. }
  315. var statusRequestParams = append(
  316. []requestParamSpec{
  317. {"session_id", isHexDigits, 0},
  318. {"connected", isBooleanFlag, 0}},
  319. baseRequestParams...)
  320. // statusAPIRequestHandler implements the "status" API request.
  321. // Clients make periodic status requests which deliver client-side
  322. // recorded data transfer and tunnel duration stats.
  323. // Note from psi_web implementation: no input validation on domains;
  324. // any string is accepted (regex transform may result in arbitrary
  325. // string). Stats processor must handle this input with care.
  326. func statusAPIRequestHandler(
  327. support *SupportServices,
  328. geoIPData GeoIPData,
  329. authorizedAccessTypes []string,
  330. params common.APIParameters) ([]byte, error) {
  331. err := validateRequestParams(support.Config, params, statusRequestParams)
  332. if err != nil {
  333. return nil, common.ContextError(err)
  334. }
  335. sessionID, _ := getStringRequestParam(params, "client_session_id")
  336. statusData, err := getJSONObjectRequestParam(params, "statusData")
  337. if err != nil {
  338. return nil, common.ContextError(err)
  339. }
  340. // Logs are queued until the input is fully validated. Otherwise, stats
  341. // could be double counted if the client has a bug in its request
  342. // formatting: partial stats would be logged (counted), the request would
  343. // fail, and clients would then resend all the same stats again.
  344. logQueue := make([]LogFields, 0)
  345. // Domain bytes transferred stats
  346. // Older clients may not submit this data
  347. // Clients are expected to send host_bytes/domain_bytes stats only when
  348. // configured to do so in the handshake reponse. Legacy clients may still
  349. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  350. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  351. if err != nil {
  352. return nil, common.ContextError(err)
  353. }
  354. if domainBytesExpected && statusData["host_bytes"] != nil {
  355. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  356. if err != nil {
  357. return nil, common.ContextError(err)
  358. }
  359. for domain, bytes := range hostBytes {
  360. domainBytesFields := getRequestLogFields(
  361. "domain_bytes",
  362. geoIPData,
  363. authorizedAccessTypes,
  364. params,
  365. statusRequestParams)
  366. domainBytesFields["domain"] = domain
  367. domainBytesFields["bytes"] = bytes
  368. logQueue = append(logQueue, domainBytesFields)
  369. }
  370. }
  371. // Remote server list download stats
  372. // Older clients may not submit this data
  373. if statusData["remote_server_list_stats"] != nil {
  374. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  375. if err != nil {
  376. return nil, common.ContextError(err)
  377. }
  378. for _, remoteServerListStat := range remoteServerListStats {
  379. remoteServerListFields := getRequestLogFields(
  380. "remote_server_list",
  381. geoIPData,
  382. authorizedAccessTypes,
  383. params,
  384. statusRequestParams)
  385. clientDownloadTimestamp, err := getStringRequestParam(remoteServerListStat, "client_download_timestamp")
  386. if err != nil {
  387. return nil, common.ContextError(err)
  388. }
  389. remoteServerListFields["client_download_timestamp"] = clientDownloadTimestamp
  390. url, err := getStringRequestParam(remoteServerListStat, "url")
  391. if err != nil {
  392. return nil, common.ContextError(err)
  393. }
  394. remoteServerListFields["url"] = url
  395. etag, err := getStringRequestParam(remoteServerListStat, "etag")
  396. if err != nil {
  397. return nil, common.ContextError(err)
  398. }
  399. remoteServerListFields["etag"] = etag
  400. logQueue = append(logQueue, remoteServerListFields)
  401. }
  402. }
  403. for _, logItem := range logQueue {
  404. log.LogRawFieldsWithTimestamp(logItem)
  405. }
  406. return make([]byte, 0), nil
  407. }
  408. // clientVerificationAPIRequestHandler is just a compliance stub
  409. // for older Android clients that still send verification requests
  410. func clientVerificationAPIRequestHandler(
  411. support *SupportServices,
  412. geoIPData GeoIPData,
  413. authorizedAccessTypes []string,
  414. params common.APIParameters) ([]byte, error) {
  415. return make([]byte, 0), nil
  416. }
  417. var tacticsParams = []requestParamSpec{
  418. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  419. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  420. }
  421. var tacticsRequestParams = append(
  422. append(
  423. []requestParamSpec{{"session_id", isHexDigits, 0}},
  424. tacticsParams...),
  425. baseRequestParams...)
  426. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  427. return func(params common.APIParameters) error {
  428. return validateRequestParams(config, params, tacticsRequestParams)
  429. }
  430. }
  431. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  432. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  433. logFields := getRequestLogFields(
  434. tactics.TACTICS_METRIC_EVENT_NAME,
  435. GeoIPData(geoIPData),
  436. nil, // authorizedAccessTypes are not known yet
  437. params,
  438. tacticsRequestParams)
  439. return common.LogFields(logFields)
  440. }
  441. }
  442. type requestParamSpec struct {
  443. name string
  444. validator func(*Config, string) bool
  445. flags uint32
  446. }
  447. const (
  448. requestParamOptional = 1
  449. requestParamNotLogged = 2
  450. requestParamArray = 4
  451. requestParamJSON = 8
  452. requestParamLogStringAsInt = 16
  453. )
  454. var upstreamFragmentorParams = []requestParamSpec{
  455. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  456. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  457. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  458. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  459. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  460. }
  461. // baseRequestParams is the list of required and optional
  462. // request parameters; derived from COMMON_INPUTS and
  463. // OPTIONAL_COMMON_INPUTS in psi_web.
  464. // Each param is expected to be a string, unless requestParamArray
  465. // is specified, in which case an array of string is expected.
  466. var baseRequestParams = append(
  467. []requestParamSpec{
  468. {"server_secret", isServerSecret, requestParamNotLogged},
  469. {"client_session_id", isHexDigits, requestParamNotLogged},
  470. {"propagation_channel_id", isHexDigits, 0},
  471. {"sponsor_id", isHexDigits, 0},
  472. {"client_version", isIntString, requestParamLogStringAsInt},
  473. {"client_platform", isClientPlatform, 0},
  474. {"client_build_rev", isHexDigits, requestParamOptional},
  475. {"relay_protocol", isRelayProtocol, 0},
  476. {"tunnel_whole_device", isBooleanFlag, requestParamOptional},
  477. {"device_region", isAnyString, requestParamOptional},
  478. {"ssh_client_version", isAnyString, requestParamOptional},
  479. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  480. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  481. {"meek_dial_address", isDialAddress, requestParamOptional},
  482. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  483. {"meek_sni_server_name", isDomain, requestParamOptional},
  484. {"meek_host_header", isHostHeader, requestParamOptional},
  485. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  486. {"user_agent", isAnyString, requestParamOptional},
  487. {"tls_profile", isAnyString, requestParamOptional},
  488. {"server_entry_region", isRegionCode, requestParamOptional},
  489. {"server_entry_source", isServerEntrySource, requestParamOptional},
  490. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  491. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  492. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  493. {"quic_version", isAnyString, requestParamOptional},
  494. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  495. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  496. },
  497. upstreamFragmentorParams...)
  498. func validateRequestParams(
  499. config *Config,
  500. params common.APIParameters,
  501. expectedParams []requestParamSpec) error {
  502. for _, expectedParam := range expectedParams {
  503. value := params[expectedParam.name]
  504. if value == nil {
  505. if expectedParam.flags&requestParamOptional != 0 {
  506. continue
  507. }
  508. return common.ContextError(
  509. fmt.Errorf("missing param: %s", expectedParam.name))
  510. }
  511. var err error
  512. switch {
  513. case expectedParam.flags&requestParamArray != 0:
  514. err = validateStringArrayRequestParam(config, expectedParam, value)
  515. case expectedParam.flags&requestParamJSON != 0:
  516. // No validation: the JSON already unmarshalled; the parameter
  517. // user will validate that the JSON contains the expected
  518. // objects/data.
  519. // TODO: without validation, any valid JSON will be logged
  520. // by getRequestLogFields, even if the parameter user validates
  521. // and rejects the parameter.
  522. default:
  523. err = validateStringRequestParam(config, expectedParam, value)
  524. }
  525. if err != nil {
  526. return common.ContextError(err)
  527. }
  528. }
  529. return nil
  530. }
  531. // copyBaseRequestParams makes a copy of the params which
  532. // includes only the baseRequestParams.
  533. func copyBaseRequestParams(params common.APIParameters) common.APIParameters {
  534. // Note: not a deep copy; assumes baseRequestParams values
  535. // are all scalar types (int, string, etc.)
  536. paramsCopy := make(common.APIParameters)
  537. for _, baseParam := range baseRequestParams {
  538. value := params[baseParam.name]
  539. if value == nil {
  540. continue
  541. }
  542. paramsCopy[baseParam.name] = value
  543. }
  544. return paramsCopy
  545. }
  546. func copyUpstreamFragmentorParams(params common.APIParameters) common.APIParameters {
  547. // Note: not a deep copy
  548. paramsCopy := make(common.APIParameters)
  549. for _, baseParam := range upstreamFragmentorParams {
  550. value := params[baseParam.name]
  551. if value == nil {
  552. continue
  553. }
  554. paramsCopy[baseParam.name] = value
  555. }
  556. return paramsCopy
  557. }
  558. func validateStringRequestParam(
  559. config *Config,
  560. expectedParam requestParamSpec,
  561. value interface{}) error {
  562. strValue, ok := value.(string)
  563. if !ok {
  564. return common.ContextError(
  565. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  566. }
  567. if !expectedParam.validator(config, strValue) {
  568. return common.ContextError(
  569. fmt.Errorf("invalid param: %s: %s", expectedParam.name, strValue))
  570. }
  571. return nil
  572. }
  573. func validateStringArrayRequestParam(
  574. config *Config,
  575. expectedParam requestParamSpec,
  576. value interface{}) error {
  577. arrayValue, ok := value.([]interface{})
  578. if !ok {
  579. return common.ContextError(
  580. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  581. }
  582. for _, value := range arrayValue {
  583. err := validateStringRequestParam(config, expectedParam, value)
  584. if err != nil {
  585. return common.ContextError(err)
  586. }
  587. }
  588. return nil
  589. }
  590. // getRequestLogFields makes LogFields to log the API event following
  591. // the legacy psi_web and current ELK naming conventions.
  592. func getRequestLogFields(
  593. eventName string,
  594. geoIPData GeoIPData,
  595. authorizedAccessTypes []string,
  596. params common.APIParameters,
  597. expectedParams []requestParamSpec) LogFields {
  598. logFields := make(LogFields)
  599. if eventName != "" {
  600. logFields["event_name"] = eventName
  601. }
  602. // In psi_web, the space replacement was done to accommodate space
  603. // delimited logging, which is no longer required; we retain the
  604. // transformation so that stats aggregation isn't impacted.
  605. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  606. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  607. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  608. if len(authorizedAccessTypes) > 0 {
  609. logFields["authorized_access_types"] = authorizedAccessTypes
  610. }
  611. if params == nil {
  612. return logFields
  613. }
  614. for _, expectedParam := range expectedParams {
  615. if expectedParam.flags&requestParamNotLogged != 0 {
  616. continue
  617. }
  618. value := params[expectedParam.name]
  619. if value == nil {
  620. // Special case: older clients don't send this value,
  621. // so log a default.
  622. if expectedParam.name == "tunnel_whole_device" {
  623. value = "0"
  624. } else {
  625. // Skip omitted, optional params
  626. continue
  627. }
  628. }
  629. switch v := value.(type) {
  630. case string:
  631. strValue := v
  632. // Special cases:
  633. // - Number fields are encoded as integer types.
  634. // - For ELK performance we record certain domain-or-IP
  635. // fields as one of two different values based on type;
  636. // we also omit port from these host:port fields for now.
  637. // - Boolean fields that come into the api as "1"/"0"
  638. // must be logged as actual boolean values
  639. switch expectedParam.name {
  640. case "meek_dial_address":
  641. host, _, _ := net.SplitHostPort(strValue)
  642. if isIPAddress(nil, host) {
  643. logFields["meek_dial_ip_address"] = host
  644. } else {
  645. logFields["meek_dial_domain"] = host
  646. }
  647. case "upstream_proxy_type":
  648. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  649. logFields[expectedParam.name] = strings.ToLower(strValue)
  650. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  651. // Due to a client bug, clients may deliever an incorrect ""
  652. // value for speed_test_samples via the web API protocol. Omit
  653. // the field in this case.
  654. case "tunnel_whole_device", "meek_transformed_host_name", "connected":
  655. // Submitted value could be "0" or "1"
  656. // "0" and non "0"/"1" values should be transformed to false
  657. // "1" should be transformed to true
  658. if strValue == "1" {
  659. logFields[expectedParam.name] = true
  660. } else {
  661. logFields[expectedParam.name] = false
  662. }
  663. default:
  664. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  665. intValue, _ := strconv.Atoi(strValue)
  666. logFields[expectedParam.name] = intValue
  667. } else {
  668. logFields[expectedParam.name] = strValue
  669. }
  670. }
  671. case []interface{}:
  672. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  673. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  674. } else {
  675. logFields[expectedParam.name] = v
  676. }
  677. default:
  678. logFields[expectedParam.name] = v
  679. }
  680. }
  681. return logFields
  682. }
  683. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  684. // fields to more verbose names for metrics.
  685. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  686. // TODO: use reflection and add additional tags, e.g.,
  687. // `json:"s" log:"timestamp"` to remove hard-coded
  688. // tag value dependency?
  689. logSamples := make([]interface{}, len(samples))
  690. for i, sample := range samples {
  691. logSample := make(map[string]interface{})
  692. if m, ok := sample.(map[string]interface{}); ok {
  693. for k, v := range m {
  694. logK := k
  695. switch k {
  696. case "s":
  697. logK = "timestamp"
  698. case "r":
  699. logK = "server_region"
  700. case "p":
  701. logK = "relay_protocol"
  702. case "t":
  703. logK = "round_trip_time_ms"
  704. case "u":
  705. logK = "bytes_up"
  706. case "d":
  707. logK = "bytes_down"
  708. }
  709. logSample[logK] = v
  710. }
  711. }
  712. logSamples[i] = logSample
  713. }
  714. return logSamples
  715. }
  716. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  717. if params[name] == nil {
  718. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  719. }
  720. value, ok := params[name].(string)
  721. if !ok {
  722. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  723. }
  724. return value, nil
  725. }
  726. func getInt64RequestParam(params common.APIParameters, name string) (int64, error) {
  727. if params[name] == nil {
  728. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  729. }
  730. value, ok := params[name].(float64)
  731. if !ok {
  732. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  733. }
  734. return int64(value), nil
  735. }
  736. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  737. if params[name] == nil {
  738. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  739. }
  740. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  741. value, ok := params[name].(map[string]interface{})
  742. if !ok {
  743. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  744. }
  745. return common.APIParameters(value), nil
  746. }
  747. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  748. if params[name] == nil {
  749. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  750. }
  751. value, ok := params[name].([]interface{})
  752. if !ok {
  753. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  754. }
  755. result := make([]common.APIParameters, len(value))
  756. for i, item := range value {
  757. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  758. resultItem, ok := item.(map[string]interface{})
  759. if !ok {
  760. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  761. }
  762. result[i] = common.APIParameters(resultItem)
  763. }
  764. return result, nil
  765. }
  766. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  767. if params[name] == nil {
  768. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  769. }
  770. // TODO: can't use common.APIParameters type?
  771. value, ok := params[name].(map[string]interface{})
  772. if !ok {
  773. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  774. }
  775. result := make(map[string]int64)
  776. for k, v := range value {
  777. numValue, ok := v.(float64)
  778. if !ok {
  779. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  780. }
  781. result[k] = int64(numValue)
  782. }
  783. return result, nil
  784. }
  785. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  786. if params[name] == nil {
  787. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  788. }
  789. value, ok := params[name].([]interface{})
  790. if !ok {
  791. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  792. }
  793. result := make([]string, len(value))
  794. for i, v := range value {
  795. strValue, ok := v.(string)
  796. if !ok {
  797. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  798. }
  799. result[i] = strValue
  800. }
  801. return result, nil
  802. }
  803. // Normalize reported client platform. Android clients, for example, report
  804. // OS version, rooted status, and Google Play build status in the clientPlatform
  805. // string along with "Android".
  806. func normalizeClientPlatform(clientPlatform string) string {
  807. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  808. return CLIENT_PLATFORM_ANDROID
  809. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  810. return CLIENT_PLATFORM_IOS
  811. }
  812. return CLIENT_PLATFORM_WINDOWS
  813. }
  814. func isAnyString(config *Config, value string) bool {
  815. return true
  816. }
  817. func isMobileClientPlatform(clientPlatform string) bool {
  818. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  819. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  820. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  821. }
  822. // Input validators follow the legacy validations rules in psi_web.
  823. func isServerSecret(config *Config, value string) bool {
  824. return subtle.ConstantTimeCompare(
  825. []byte(value),
  826. []byte(config.WebServerSecret)) == 1
  827. }
  828. func isHexDigits(_ *Config, value string) bool {
  829. // Allows both uppercase in addition to lowercase, for legacy support.
  830. return -1 == strings.IndexFunc(value, func(c rune) bool {
  831. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  832. })
  833. }
  834. func isDigits(_ *Config, value string) bool {
  835. return -1 == strings.IndexFunc(value, func(c rune) bool {
  836. return c < '0' || c > '9'
  837. })
  838. }
  839. func isIntString(_ *Config, value string) bool {
  840. _, err := strconv.Atoi(value)
  841. return err == nil
  842. }
  843. func isClientPlatform(_ *Config, value string) bool {
  844. return -1 == strings.IndexFunc(value, func(c rune) bool {
  845. // Note: stricter than psi_web's Python string.whitespace
  846. return unicode.Is(unicode.White_Space, c)
  847. })
  848. }
  849. func isRelayProtocol(_ *Config, value string) bool {
  850. return common.Contains(protocol.SupportedTunnelProtocols, value)
  851. }
  852. func isBooleanFlag(_ *Config, value string) bool {
  853. return value == "0" || value == "1"
  854. }
  855. func isUpstreamProxyType(_ *Config, value string) bool {
  856. value = strings.ToLower(value)
  857. return value == "http" || value == "socks5" || value == "socks4a"
  858. }
  859. func isRegionCode(_ *Config, value string) bool {
  860. if len(value) != 2 {
  861. return false
  862. }
  863. return -1 == strings.IndexFunc(value, func(c rune) bool {
  864. return c < 'A' || c > 'Z'
  865. })
  866. }
  867. func isDialAddress(_ *Config, value string) bool {
  868. // "<host>:<port>", where <host> is a domain or IP address
  869. parts := strings.Split(value, ":")
  870. if len(parts) != 2 {
  871. return false
  872. }
  873. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  874. return false
  875. }
  876. if !isDigits(nil, parts[1]) {
  877. return false
  878. }
  879. port, err := strconv.Atoi(parts[1])
  880. if err != nil {
  881. return false
  882. }
  883. return port > 0 && port < 65536
  884. }
  885. func isIPAddress(_ *Config, value string) bool {
  886. return net.ParseIP(value) != nil
  887. }
  888. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  889. func isDomain(_ *Config, value string) bool {
  890. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  891. //
  892. // "ensures that each segment
  893. // * contains at least one character and a maximum of 63 characters
  894. // * consists only of allowed characters
  895. // * doesn't begin or end with a hyphen"
  896. //
  897. if len(value) > 255 {
  898. return false
  899. }
  900. value = strings.TrimSuffix(value, ".")
  901. for _, part := range strings.Split(value, ".") {
  902. // Note: regexp doesn't support the following Perl expression which
  903. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  904. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  905. return false
  906. }
  907. if !isDomainRegex.Match([]byte(part)) {
  908. return false
  909. }
  910. }
  911. return true
  912. }
  913. func isHostHeader(_ *Config, value string) bool {
  914. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  915. if strings.Contains(value, ":") {
  916. return isDialAddress(nil, value)
  917. }
  918. return isIPAddress(nil, value) || isDomain(nil, value)
  919. }
  920. func isServerEntrySource(_ *Config, value string) bool {
  921. return common.Contains(protocol.SupportedServerEntrySources, value)
  922. }
  923. var isISO8601DateRegex = regexp.MustCompile(
  924. "(?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})))")
  925. func isISO8601Date(_ *Config, value string) bool {
  926. return isISO8601DateRegex.Match([]byte(value))
  927. }
  928. func isLastConnected(_ *Config, value string) bool {
  929. return value == "None" || value == "Unknown" || isISO8601Date(nil, value)
  930. }