api.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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.
  240. log.WithContextFields(
  241. getRequestLogFields(
  242. "",
  243. geoIPData,
  244. authorizedAccessTypes,
  245. params,
  246. baseRequestParams)).Info("handshake")
  247. handshakeResponse := protocol.HandshakeResponse{
  248. SSHSessionID: sessionID,
  249. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, isMobile),
  250. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  251. PageViewRegexes: make([]map[string]string, 0),
  252. HttpsRequestRegexes: httpsRequestRegexes,
  253. EncodedServerList: db.DiscoverServers(geoIPData.DiscoveryValue),
  254. ClientRegion: geoIPData.Country,
  255. ServerTimestamp: common.GetCurrentTimestamp(),
  256. ActiveAuthorizationIDs: activeAuthorizationIDs,
  257. TacticsPayload: marshaledTacticsPayload,
  258. }
  259. responsePayload, err := json.Marshal(handshakeResponse)
  260. if err != nil {
  261. return nil, common.ContextError(err)
  262. }
  263. return responsePayload, nil
  264. }
  265. var connectedRequestParams = append(
  266. []requestParamSpec{
  267. {"session_id", isHexDigits, 0},
  268. {"last_connected", isLastConnected, 0},
  269. {"establishment_duration", isIntString, requestParamOptional}},
  270. baseRequestParams...)
  271. // connectedAPIRequestHandler implements the "connected" API request.
  272. // Clients make the connected request once a tunnel connection has been
  273. // established and at least once per day. The last_connected input value,
  274. // which should be a connected_timestamp output from a previous connected
  275. // response, is used to calculate unique user stats.
  276. // connected_timestamp is truncated as a privacy measure.
  277. func connectedAPIRequestHandler(
  278. support *SupportServices,
  279. geoIPData GeoIPData,
  280. authorizedAccessTypes []string,
  281. params common.APIParameters) ([]byte, error) {
  282. err := validateRequestParams(support.Config, params, connectedRequestParams)
  283. if err != nil {
  284. return nil, common.ContextError(err)
  285. }
  286. log.LogRawFieldsWithTimestamp(
  287. getRequestLogFields(
  288. "connected",
  289. geoIPData,
  290. authorizedAccessTypes,
  291. params,
  292. connectedRequestParams))
  293. connectedResponse := protocol.ConnectedResponse{
  294. ConnectedTimestamp: common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  295. }
  296. responsePayload, err := json.Marshal(connectedResponse)
  297. if err != nil {
  298. return nil, common.ContextError(err)
  299. }
  300. return responsePayload, nil
  301. }
  302. var statusRequestParams = append(
  303. []requestParamSpec{
  304. {"session_id", isHexDigits, 0},
  305. {"connected", isBooleanFlag, 0}},
  306. baseRequestParams...)
  307. // statusAPIRequestHandler implements the "status" API request.
  308. // Clients make periodic status requests which deliver client-side
  309. // recorded data transfer and tunnel duration stats.
  310. // Note from psi_web implementation: no input validation on domains;
  311. // any string is accepted (regex transform may result in arbitrary
  312. // string). Stats processor must handle this input with care.
  313. func statusAPIRequestHandler(
  314. support *SupportServices,
  315. geoIPData GeoIPData,
  316. authorizedAccessTypes []string,
  317. params common.APIParameters) ([]byte, error) {
  318. err := validateRequestParams(support.Config, params, statusRequestParams)
  319. if err != nil {
  320. return nil, common.ContextError(err)
  321. }
  322. sessionID, _ := getStringRequestParam(params, "client_session_id")
  323. statusData, err := getJSONObjectRequestParam(params, "statusData")
  324. if err != nil {
  325. return nil, common.ContextError(err)
  326. }
  327. // Logs are queued until the input is fully validated. Otherwise, stats
  328. // could be double counted if the client has a bug in its request
  329. // formatting: partial stats would be logged (counted), the request would
  330. // fail, and clients would then resend all the same stats again.
  331. logQueue := make([]LogFields, 0)
  332. // Domain bytes transferred stats
  333. // Older clients may not submit this data
  334. // Clients are expected to send host_bytes/domain_bytes stats only when
  335. // configured to do so in the handshake reponse. Legacy clients may still
  336. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  337. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  338. if err != nil {
  339. return nil, common.ContextError(err)
  340. }
  341. if domainBytesExpected && statusData["host_bytes"] != nil {
  342. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  343. if err != nil {
  344. return nil, common.ContextError(err)
  345. }
  346. for domain, bytes := range hostBytes {
  347. domainBytesFields := getRequestLogFields(
  348. "domain_bytes",
  349. geoIPData,
  350. authorizedAccessTypes,
  351. params,
  352. statusRequestParams)
  353. domainBytesFields["domain"] = domain
  354. domainBytesFields["bytes"] = bytes
  355. logQueue = append(logQueue, domainBytesFields)
  356. }
  357. }
  358. // Remote server list download stats
  359. // Older clients may not submit this data
  360. if statusData["remote_server_list_stats"] != nil {
  361. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  362. if err != nil {
  363. return nil, common.ContextError(err)
  364. }
  365. for _, remoteServerListStat := range remoteServerListStats {
  366. remoteServerListFields := getRequestLogFields(
  367. "remote_server_list",
  368. geoIPData,
  369. authorizedAccessTypes,
  370. params,
  371. statusRequestParams)
  372. clientDownloadTimestamp, err := getStringRequestParam(remoteServerListStat, "client_download_timestamp")
  373. if err != nil {
  374. return nil, common.ContextError(err)
  375. }
  376. remoteServerListFields["client_download_timestamp"] = clientDownloadTimestamp
  377. url, err := getStringRequestParam(remoteServerListStat, "url")
  378. if err != nil {
  379. return nil, common.ContextError(err)
  380. }
  381. remoteServerListFields["url"] = url
  382. etag, err := getStringRequestParam(remoteServerListStat, "etag")
  383. if err != nil {
  384. return nil, common.ContextError(err)
  385. }
  386. remoteServerListFields["etag"] = etag
  387. logQueue = append(logQueue, remoteServerListFields)
  388. }
  389. }
  390. for _, logItem := range logQueue {
  391. log.LogRawFieldsWithTimestamp(logItem)
  392. }
  393. return make([]byte, 0), nil
  394. }
  395. // clientVerificationAPIRequestHandler is just a compliance stub
  396. // for older Android clients that still send verification requests
  397. func clientVerificationAPIRequestHandler(
  398. support *SupportServices,
  399. geoIPData GeoIPData,
  400. authorizedAccessTypes []string,
  401. params common.APIParameters) ([]byte, error) {
  402. return make([]byte, 0), nil
  403. }
  404. var tacticsParams = []requestParamSpec{
  405. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  406. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  407. }
  408. var tacticsRequestParams = append(
  409. append(
  410. []requestParamSpec{{"session_id", isHexDigits, 0}},
  411. tacticsParams...),
  412. baseRequestParams...)
  413. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  414. return func(params common.APIParameters) error {
  415. return validateRequestParams(config, params, tacticsRequestParams)
  416. }
  417. }
  418. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  419. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  420. logFields := getRequestLogFields(
  421. tactics.TACTICS_METRIC_EVENT_NAME,
  422. GeoIPData(geoIPData),
  423. nil, // authorizedAccessTypes are not known yet
  424. params,
  425. tacticsRequestParams)
  426. return common.LogFields(logFields)
  427. }
  428. }
  429. type requestParamSpec struct {
  430. name string
  431. validator func(*Config, string) bool
  432. flags uint32
  433. }
  434. const (
  435. requestParamOptional = 1
  436. requestParamNotLogged = 2
  437. requestParamArray = 4
  438. requestParamJSON = 8
  439. )
  440. // baseRequestParams is the list of required and optional
  441. // request parameters; derived from COMMON_INPUTS and
  442. // OPTIONAL_COMMON_INPUTS in psi_web.
  443. // Each param is expected to be a string, unless requestParamArray
  444. // is specified, in which case an array of string is expected.
  445. var baseRequestParams = []requestParamSpec{
  446. {"server_secret", isServerSecret, requestParamNotLogged},
  447. {"client_session_id", isHexDigits, requestParamNotLogged},
  448. {"propagation_channel_id", isHexDigits, 0},
  449. {"sponsor_id", isHexDigits, 0},
  450. {"client_version", isIntString, 0},
  451. {"client_platform", isClientPlatform, 0},
  452. {"client_build_rev", isHexDigits, requestParamOptional},
  453. {"relay_protocol", isRelayProtocol, 0},
  454. {"tunnel_whole_device", isBooleanFlag, requestParamOptional},
  455. {"device_region", isAnyString, requestParamOptional},
  456. {"ssh_client_version", isAnyString, requestParamOptional},
  457. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  458. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  459. {"meek_dial_address", isDialAddress, requestParamOptional},
  460. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  461. {"meek_sni_server_name", isDomain, requestParamOptional},
  462. {"meek_host_header", isHostHeader, requestParamOptional},
  463. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  464. {"user_agent", isAnyString, requestParamOptional},
  465. {"tls_profile", isAnyString, requestParamOptional},
  466. {"server_entry_region", isRegionCode, requestParamOptional},
  467. {"server_entry_source", isServerEntrySource, requestParamOptional},
  468. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  469. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  470. }
  471. func validateRequestParams(
  472. config *Config,
  473. params common.APIParameters,
  474. expectedParams []requestParamSpec) error {
  475. for _, expectedParam := range expectedParams {
  476. value := params[expectedParam.name]
  477. if value == nil {
  478. if expectedParam.flags&requestParamOptional != 0 {
  479. continue
  480. }
  481. return common.ContextError(
  482. fmt.Errorf("missing param: %s", expectedParam.name))
  483. }
  484. var err error
  485. switch {
  486. case expectedParam.flags&requestParamArray != 0:
  487. err = validateStringArrayRequestParam(config, expectedParam, value)
  488. case expectedParam.flags&requestParamJSON != 0:
  489. // No validation: the JSON already unmarshalled; the parameter
  490. // user will validate that the JSON contains the expected
  491. // objects/data.
  492. // TODO: without validation, any valid JSON will be logged
  493. // by getRequestLogFields, even if the parameter user validates
  494. // and rejects the parameter.
  495. default:
  496. err = validateStringRequestParam(config, expectedParam, value)
  497. }
  498. if err != nil {
  499. return common.ContextError(err)
  500. }
  501. }
  502. return nil
  503. }
  504. // copyBaseRequestParams makes a copy of the params which
  505. // includes only the baseRequestParams.
  506. func copyBaseRequestParams(params common.APIParameters) common.APIParameters {
  507. // Note: not a deep copy; assumes baseRequestParams values
  508. // are all scalar types (int, string, etc.)
  509. paramsCopy := make(common.APIParameters)
  510. for _, baseParam := range baseRequestParams {
  511. value := params[baseParam.name]
  512. if value == nil {
  513. continue
  514. }
  515. paramsCopy[baseParam.name] = value
  516. }
  517. return paramsCopy
  518. }
  519. func validateStringRequestParam(
  520. config *Config,
  521. expectedParam requestParamSpec,
  522. value interface{}) error {
  523. strValue, ok := value.(string)
  524. if !ok {
  525. return common.ContextError(
  526. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  527. }
  528. if !expectedParam.validator(config, strValue) {
  529. return common.ContextError(
  530. fmt.Errorf("invalid param: %s: %s", expectedParam.name, strValue))
  531. }
  532. return nil
  533. }
  534. func validateStringArrayRequestParam(
  535. config *Config,
  536. expectedParam requestParamSpec,
  537. value interface{}) error {
  538. arrayValue, ok := value.([]interface{})
  539. if !ok {
  540. return common.ContextError(
  541. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  542. }
  543. for _, value := range arrayValue {
  544. err := validateStringRequestParam(config, expectedParam, value)
  545. if err != nil {
  546. return common.ContextError(err)
  547. }
  548. }
  549. return nil
  550. }
  551. // getRequestLogFields makes LogFields to log the API event following
  552. // the legacy psi_web and current ELK naming conventions.
  553. func getRequestLogFields(
  554. eventName string,
  555. geoIPData GeoIPData,
  556. authorizedAccessTypes []string,
  557. params common.APIParameters,
  558. expectedParams []requestParamSpec) LogFields {
  559. logFields := make(LogFields)
  560. if eventName != "" {
  561. logFields["event_name"] = eventName
  562. }
  563. // In psi_web, the space replacement was done to accommodate space
  564. // delimited logging, which is no longer required; we retain the
  565. // transformation so that stats aggregation isn't impacted.
  566. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  567. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  568. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  569. if len(authorizedAccessTypes) > 0 {
  570. logFields["authorized_access_types"] = authorizedAccessTypes
  571. }
  572. if params == nil {
  573. return logFields
  574. }
  575. for _, expectedParam := range expectedParams {
  576. if expectedParam.flags&requestParamNotLogged != 0 {
  577. continue
  578. }
  579. value := params[expectedParam.name]
  580. if value == nil {
  581. // Special case: older clients don't send this value,
  582. // so log a default.
  583. if expectedParam.name == "tunnel_whole_device" {
  584. value = "0"
  585. } else {
  586. // Skip omitted, optional params
  587. continue
  588. }
  589. }
  590. switch v := value.(type) {
  591. case string:
  592. strValue := v
  593. // Special cases:
  594. // - Number fields are encoded as integer types.
  595. // - For ELK performance we record certain domain-or-IP
  596. // fields as one of two different values based on type;
  597. // we also omit port from these host:port fields for now.
  598. // - Boolean fields that come into the api as "1"/"0"
  599. // must be logged as actual boolean values
  600. switch expectedParam.name {
  601. case "client_version", "establishment_duration":
  602. intValue, _ := strconv.Atoi(strValue)
  603. logFields[expectedParam.name] = intValue
  604. case "meek_dial_address":
  605. host, _, _ := net.SplitHostPort(strValue)
  606. if isIPAddress(nil, host) {
  607. logFields["meek_dial_ip_address"] = host
  608. } else {
  609. logFields["meek_dial_domain"] = host
  610. }
  611. case "upstream_proxy_type":
  612. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  613. logFields[expectedParam.name] = strings.ToLower(strValue)
  614. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  615. // Due to a client bug, clients may deliever an incorrect ""
  616. // value for speed_test_samples via the web API protocol. Omit
  617. // the field in this case.
  618. case "tunnel_whole_device", "meek_transformed_host_name", "connected":
  619. // Submitted value could be "0" or "1"
  620. // "0" and non "0"/"1" values should be transformed to false
  621. // "1" should be transformed to true
  622. if strValue == "1" {
  623. logFields[expectedParam.name] = true
  624. } else {
  625. logFields[expectedParam.name] = false
  626. }
  627. default:
  628. logFields[expectedParam.name] = strValue
  629. }
  630. case []interface{}:
  631. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  632. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  633. } else {
  634. logFields[expectedParam.name] = v
  635. }
  636. default:
  637. logFields[expectedParam.name] = v
  638. }
  639. }
  640. return logFields
  641. }
  642. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  643. // fields to more verbose names for metrics.
  644. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  645. // TODO: use reflection and add additional tags, e.g.,
  646. // `json:"s" log:"timestamp"` to remove hard-coded
  647. // tag value dependency?
  648. logSamples := make([]interface{}, len(samples))
  649. for i, sample := range samples {
  650. logSample := make(map[string]interface{})
  651. if m, ok := sample.(map[string]interface{}); ok {
  652. for k, v := range m {
  653. logK := k
  654. switch k {
  655. case "s":
  656. logK = "timestamp"
  657. case "r":
  658. logK = "server_region"
  659. case "p":
  660. logK = "relay_protocol"
  661. case "t":
  662. logK = "round_trip_time_ms"
  663. case "u":
  664. logK = "bytes_up"
  665. case "d":
  666. logK = "bytes_down"
  667. }
  668. logSample[logK] = v
  669. }
  670. }
  671. logSamples[i] = logSample
  672. }
  673. return logSamples
  674. }
  675. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  676. if params[name] == nil {
  677. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  678. }
  679. value, ok := params[name].(string)
  680. if !ok {
  681. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  682. }
  683. return value, nil
  684. }
  685. func getInt64RequestParam(params common.APIParameters, name string) (int64, error) {
  686. if params[name] == nil {
  687. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  688. }
  689. value, ok := params[name].(float64)
  690. if !ok {
  691. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  692. }
  693. return int64(value), nil
  694. }
  695. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  696. if params[name] == nil {
  697. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  698. }
  699. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  700. value, ok := params[name].(map[string]interface{})
  701. if !ok {
  702. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  703. }
  704. return common.APIParameters(value), nil
  705. }
  706. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  707. if params[name] == nil {
  708. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  709. }
  710. value, ok := params[name].([]interface{})
  711. if !ok {
  712. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  713. }
  714. result := make([]common.APIParameters, len(value))
  715. for i, item := range value {
  716. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  717. resultItem, ok := item.(map[string]interface{})
  718. if !ok {
  719. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  720. }
  721. result[i] = common.APIParameters(resultItem)
  722. }
  723. return result, nil
  724. }
  725. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  726. if params[name] == nil {
  727. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  728. }
  729. // TODO: can't use common.APIParameters type?
  730. value, ok := params[name].(map[string]interface{})
  731. if !ok {
  732. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  733. }
  734. result := make(map[string]int64)
  735. for k, v := range value {
  736. numValue, ok := v.(float64)
  737. if !ok {
  738. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  739. }
  740. result[k] = int64(numValue)
  741. }
  742. return result, nil
  743. }
  744. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  745. if params[name] == nil {
  746. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  747. }
  748. value, ok := params[name].([]interface{})
  749. if !ok {
  750. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  751. }
  752. result := make([]string, len(value))
  753. for i, v := range value {
  754. strValue, ok := v.(string)
  755. if !ok {
  756. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  757. }
  758. result[i] = strValue
  759. }
  760. return result, nil
  761. }
  762. // Normalize reported client platform. Android clients, for example, report
  763. // OS version, rooted status, and Google Play build status in the clientPlatform
  764. // string along with "Android".
  765. func normalizeClientPlatform(clientPlatform string) string {
  766. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  767. return CLIENT_PLATFORM_ANDROID
  768. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  769. return CLIENT_PLATFORM_IOS
  770. }
  771. return CLIENT_PLATFORM_WINDOWS
  772. }
  773. func isAnyString(config *Config, value string) bool {
  774. return true
  775. }
  776. func isMobileClientPlatform(clientPlatform string) bool {
  777. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  778. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  779. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  780. }
  781. // Input validators follow the legacy validations rules in psi_web.
  782. func isServerSecret(config *Config, value string) bool {
  783. return subtle.ConstantTimeCompare(
  784. []byte(value),
  785. []byte(config.WebServerSecret)) == 1
  786. }
  787. func isHexDigits(_ *Config, value string) bool {
  788. // Allows both uppercase in addition to lowercase, for legacy support.
  789. return -1 == strings.IndexFunc(value, func(c rune) bool {
  790. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  791. })
  792. }
  793. func isDigits(_ *Config, value string) bool {
  794. return -1 == strings.IndexFunc(value, func(c rune) bool {
  795. return c < '0' || c > '9'
  796. })
  797. }
  798. func isIntString(_ *Config, value string) bool {
  799. _, err := strconv.Atoi(value)
  800. return err == nil
  801. }
  802. func isClientPlatform(_ *Config, value string) bool {
  803. return -1 == strings.IndexFunc(value, func(c rune) bool {
  804. // Note: stricter than psi_web's Python string.whitespace
  805. return unicode.Is(unicode.White_Space, c)
  806. })
  807. }
  808. func isRelayProtocol(_ *Config, value string) bool {
  809. return common.Contains(protocol.SupportedTunnelProtocols, value)
  810. }
  811. func isBooleanFlag(_ *Config, value string) bool {
  812. return value == "0" || value == "1"
  813. }
  814. func isUpstreamProxyType(_ *Config, value string) bool {
  815. value = strings.ToLower(value)
  816. return value == "http" || value == "socks5" || value == "socks4a"
  817. }
  818. func isRegionCode(_ *Config, value string) bool {
  819. if len(value) != 2 {
  820. return false
  821. }
  822. return -1 == strings.IndexFunc(value, func(c rune) bool {
  823. return c < 'A' || c > 'Z'
  824. })
  825. }
  826. func isDialAddress(_ *Config, value string) bool {
  827. // "<host>:<port>", where <host> is a domain or IP address
  828. parts := strings.Split(value, ":")
  829. if len(parts) != 2 {
  830. return false
  831. }
  832. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  833. return false
  834. }
  835. if !isDigits(nil, parts[1]) {
  836. return false
  837. }
  838. port, err := strconv.Atoi(parts[1])
  839. if err != nil {
  840. return false
  841. }
  842. return port > 0 && port < 65536
  843. }
  844. func isIPAddress(_ *Config, value string) bool {
  845. return net.ParseIP(value) != nil
  846. }
  847. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  848. func isDomain(_ *Config, value string) bool {
  849. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  850. //
  851. // "ensures that each segment
  852. // * contains at least one character and a maximum of 63 characters
  853. // * consists only of allowed characters
  854. // * doesn't begin or end with a hyphen"
  855. //
  856. if len(value) > 255 {
  857. return false
  858. }
  859. value = strings.TrimSuffix(value, ".")
  860. for _, part := range strings.Split(value, ".") {
  861. // Note: regexp doesn't support the following Perl expression which
  862. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  863. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  864. return false
  865. }
  866. if !isDomainRegex.Match([]byte(part)) {
  867. return false
  868. }
  869. }
  870. return true
  871. }
  872. func isHostHeader(_ *Config, value string) bool {
  873. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  874. if strings.Contains(value, ":") {
  875. return isDialAddress(nil, value)
  876. }
  877. return isIPAddress(nil, value) || isDomain(nil, value)
  878. }
  879. func isServerEntrySource(_ *Config, value string) bool {
  880. return common.Contains(protocol.SupportedServerEntrySources, value)
  881. }
  882. var isISO8601DateRegex = regexp.MustCompile(
  883. "(?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})))")
  884. func isISO8601Date(_ *Config, value string) bool {
  885. return isISO8601DateRegex.Match([]byte(value))
  886. }
  887. func isLastConnected(_ *Config, value string) bool {
  888. return value == "None" || value == "Unknown" || isISO8601Date(nil, value)
  889. }