api.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. {"dial_port_number", isIntString, requestParamOptional},
  471. {"quic_version", isAnyString, requestParamOptional},
  472. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  473. {"upstream_bytes_to_fragment", isIntString, requestParamOptional},
  474. {"upstream_min_write_bytes", isIntString, requestParamOptional},
  475. {"upstream_max_write_bytes", isIntString, requestParamOptional},
  476. {"upstream_min_delay", isIntString, requestParamOptional},
  477. {"upstream_max_delay", isIntString, requestParamOptional},
  478. }
  479. func validateRequestParams(
  480. config *Config,
  481. params common.APIParameters,
  482. expectedParams []requestParamSpec) error {
  483. for _, expectedParam := range expectedParams {
  484. value := params[expectedParam.name]
  485. if value == nil {
  486. if expectedParam.flags&requestParamOptional != 0 {
  487. continue
  488. }
  489. return common.ContextError(
  490. fmt.Errorf("missing param: %s", expectedParam.name))
  491. }
  492. var err error
  493. switch {
  494. case expectedParam.flags&requestParamArray != 0:
  495. err = validateStringArrayRequestParam(config, expectedParam, value)
  496. case expectedParam.flags&requestParamJSON != 0:
  497. // No validation: the JSON already unmarshalled; the parameter
  498. // user will validate that the JSON contains the expected
  499. // objects/data.
  500. // TODO: without validation, any valid JSON will be logged
  501. // by getRequestLogFields, even if the parameter user validates
  502. // and rejects the parameter.
  503. default:
  504. err = validateStringRequestParam(config, expectedParam, value)
  505. }
  506. if err != nil {
  507. return common.ContextError(err)
  508. }
  509. }
  510. return nil
  511. }
  512. // copyBaseRequestParams makes a copy of the params which
  513. // includes only the baseRequestParams.
  514. func copyBaseRequestParams(params common.APIParameters) common.APIParameters {
  515. // Note: not a deep copy; assumes baseRequestParams values
  516. // are all scalar types (int, string, etc.)
  517. paramsCopy := make(common.APIParameters)
  518. for _, baseParam := range baseRequestParams {
  519. value := params[baseParam.name]
  520. if value == nil {
  521. continue
  522. }
  523. paramsCopy[baseParam.name] = value
  524. }
  525. return paramsCopy
  526. }
  527. func validateStringRequestParam(
  528. config *Config,
  529. expectedParam requestParamSpec,
  530. value interface{}) error {
  531. strValue, ok := value.(string)
  532. if !ok {
  533. return common.ContextError(
  534. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  535. }
  536. if !expectedParam.validator(config, strValue) {
  537. return common.ContextError(
  538. fmt.Errorf("invalid param: %s: %s", expectedParam.name, strValue))
  539. }
  540. return nil
  541. }
  542. func validateStringArrayRequestParam(
  543. config *Config,
  544. expectedParam requestParamSpec,
  545. value interface{}) error {
  546. arrayValue, ok := value.([]interface{})
  547. if !ok {
  548. return common.ContextError(
  549. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  550. }
  551. for _, value := range arrayValue {
  552. err := validateStringRequestParam(config, expectedParam, value)
  553. if err != nil {
  554. return common.ContextError(err)
  555. }
  556. }
  557. return nil
  558. }
  559. // getRequestLogFields makes LogFields to log the API event following
  560. // the legacy psi_web and current ELK naming conventions.
  561. func getRequestLogFields(
  562. eventName string,
  563. geoIPData GeoIPData,
  564. authorizedAccessTypes []string,
  565. params common.APIParameters,
  566. expectedParams []requestParamSpec) LogFields {
  567. logFields := make(LogFields)
  568. if eventName != "" {
  569. logFields["event_name"] = eventName
  570. }
  571. // In psi_web, the space replacement was done to accommodate space
  572. // delimited logging, which is no longer required; we retain the
  573. // transformation so that stats aggregation isn't impacted.
  574. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  575. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  576. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  577. if len(authorizedAccessTypes) > 0 {
  578. logFields["authorized_access_types"] = authorizedAccessTypes
  579. }
  580. if params == nil {
  581. return logFields
  582. }
  583. for _, expectedParam := range expectedParams {
  584. if expectedParam.flags&requestParamNotLogged != 0 {
  585. continue
  586. }
  587. value := params[expectedParam.name]
  588. if value == nil {
  589. // Special case: older clients don't send this value,
  590. // so log a default.
  591. if expectedParam.name == "tunnel_whole_device" {
  592. value = "0"
  593. } else {
  594. // Skip omitted, optional params
  595. continue
  596. }
  597. }
  598. switch v := value.(type) {
  599. case string:
  600. strValue := v
  601. // Special cases:
  602. // - Number fields are encoded as integer types.
  603. // - For ELK performance we record certain domain-or-IP
  604. // fields as one of two different values based on type;
  605. // we also omit port from these host:port fields for now.
  606. // - Boolean fields that come into the api as "1"/"0"
  607. // must be logged as actual boolean values
  608. switch expectedParam.name {
  609. case "client_version", "establishment_duration":
  610. intValue, _ := strconv.Atoi(strValue)
  611. logFields[expectedParam.name] = intValue
  612. case "meek_dial_address":
  613. host, _, _ := net.SplitHostPort(strValue)
  614. if isIPAddress(nil, host) {
  615. logFields["meek_dial_ip_address"] = host
  616. } else {
  617. logFields["meek_dial_domain"] = host
  618. }
  619. case "upstream_proxy_type":
  620. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  621. logFields[expectedParam.name] = strings.ToLower(strValue)
  622. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  623. // Due to a client bug, clients may deliever an incorrect ""
  624. // value for speed_test_samples via the web API protocol. Omit
  625. // the field in this case.
  626. case "tunnel_whole_device", "meek_transformed_host_name", "connected":
  627. // Submitted value could be "0" or "1"
  628. // "0" and non "0"/"1" values should be transformed to false
  629. // "1" should be transformed to true
  630. if strValue == "1" {
  631. logFields[expectedParam.name] = true
  632. } else {
  633. logFields[expectedParam.name] = false
  634. }
  635. default:
  636. logFields[expectedParam.name] = strValue
  637. }
  638. case []interface{}:
  639. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  640. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  641. } else {
  642. logFields[expectedParam.name] = v
  643. }
  644. default:
  645. logFields[expectedParam.name] = v
  646. }
  647. }
  648. return logFields
  649. }
  650. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  651. // fields to more verbose names for metrics.
  652. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  653. // TODO: use reflection and add additional tags, e.g.,
  654. // `json:"s" log:"timestamp"` to remove hard-coded
  655. // tag value dependency?
  656. logSamples := make([]interface{}, len(samples))
  657. for i, sample := range samples {
  658. logSample := make(map[string]interface{})
  659. if m, ok := sample.(map[string]interface{}); ok {
  660. for k, v := range m {
  661. logK := k
  662. switch k {
  663. case "s":
  664. logK = "timestamp"
  665. case "r":
  666. logK = "server_region"
  667. case "p":
  668. logK = "relay_protocol"
  669. case "t":
  670. logK = "round_trip_time_ms"
  671. case "u":
  672. logK = "bytes_up"
  673. case "d":
  674. logK = "bytes_down"
  675. }
  676. logSample[logK] = v
  677. }
  678. }
  679. logSamples[i] = logSample
  680. }
  681. return logSamples
  682. }
  683. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  684. if params[name] == nil {
  685. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  686. }
  687. value, ok := params[name].(string)
  688. if !ok {
  689. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  690. }
  691. return value, nil
  692. }
  693. func getInt64RequestParam(params common.APIParameters, name string) (int64, error) {
  694. if params[name] == nil {
  695. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  696. }
  697. value, ok := params[name].(float64)
  698. if !ok {
  699. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  700. }
  701. return int64(value), nil
  702. }
  703. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  704. if params[name] == nil {
  705. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  706. }
  707. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  708. value, ok := params[name].(map[string]interface{})
  709. if !ok {
  710. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  711. }
  712. return common.APIParameters(value), nil
  713. }
  714. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  715. if params[name] == nil {
  716. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  717. }
  718. value, ok := params[name].([]interface{})
  719. if !ok {
  720. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  721. }
  722. result := make([]common.APIParameters, len(value))
  723. for i, item := range value {
  724. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  725. resultItem, ok := item.(map[string]interface{})
  726. if !ok {
  727. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  728. }
  729. result[i] = common.APIParameters(resultItem)
  730. }
  731. return result, nil
  732. }
  733. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  734. if params[name] == nil {
  735. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  736. }
  737. // TODO: can't use common.APIParameters type?
  738. value, ok := params[name].(map[string]interface{})
  739. if !ok {
  740. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  741. }
  742. result := make(map[string]int64)
  743. for k, v := range value {
  744. numValue, ok := v.(float64)
  745. if !ok {
  746. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  747. }
  748. result[k] = int64(numValue)
  749. }
  750. return result, nil
  751. }
  752. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  753. if params[name] == nil {
  754. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  755. }
  756. value, ok := params[name].([]interface{})
  757. if !ok {
  758. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  759. }
  760. result := make([]string, len(value))
  761. for i, v := range value {
  762. strValue, ok := v.(string)
  763. if !ok {
  764. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  765. }
  766. result[i] = strValue
  767. }
  768. return result, nil
  769. }
  770. // Normalize reported client platform. Android clients, for example, report
  771. // OS version, rooted status, and Google Play build status in the clientPlatform
  772. // string along with "Android".
  773. func normalizeClientPlatform(clientPlatform string) string {
  774. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  775. return CLIENT_PLATFORM_ANDROID
  776. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  777. return CLIENT_PLATFORM_IOS
  778. }
  779. return CLIENT_PLATFORM_WINDOWS
  780. }
  781. func isAnyString(config *Config, value string) bool {
  782. return true
  783. }
  784. func isMobileClientPlatform(clientPlatform string) bool {
  785. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  786. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  787. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  788. }
  789. // Input validators follow the legacy validations rules in psi_web.
  790. func isServerSecret(config *Config, value string) bool {
  791. return subtle.ConstantTimeCompare(
  792. []byte(value),
  793. []byte(config.WebServerSecret)) == 1
  794. }
  795. func isHexDigits(_ *Config, value string) bool {
  796. // Allows both uppercase in addition to lowercase, for legacy support.
  797. return -1 == strings.IndexFunc(value, func(c rune) bool {
  798. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  799. })
  800. }
  801. func isDigits(_ *Config, value string) bool {
  802. return -1 == strings.IndexFunc(value, func(c rune) bool {
  803. return c < '0' || c > '9'
  804. })
  805. }
  806. func isIntString(_ *Config, value string) bool {
  807. _, err := strconv.Atoi(value)
  808. return err == nil
  809. }
  810. func isClientPlatform(_ *Config, value string) bool {
  811. return -1 == strings.IndexFunc(value, func(c rune) bool {
  812. // Note: stricter than psi_web's Python string.whitespace
  813. return unicode.Is(unicode.White_Space, c)
  814. })
  815. }
  816. func isRelayProtocol(_ *Config, value string) bool {
  817. return common.Contains(protocol.SupportedTunnelProtocols, value)
  818. }
  819. func isBooleanFlag(_ *Config, value string) bool {
  820. return value == "0" || value == "1"
  821. }
  822. func isUpstreamProxyType(_ *Config, value string) bool {
  823. value = strings.ToLower(value)
  824. return value == "http" || value == "socks5" || value == "socks4a"
  825. }
  826. func isRegionCode(_ *Config, value string) bool {
  827. if len(value) != 2 {
  828. return false
  829. }
  830. return -1 == strings.IndexFunc(value, func(c rune) bool {
  831. return c < 'A' || c > 'Z'
  832. })
  833. }
  834. func isDialAddress(_ *Config, value string) bool {
  835. // "<host>:<port>", where <host> is a domain or IP address
  836. parts := strings.Split(value, ":")
  837. if len(parts) != 2 {
  838. return false
  839. }
  840. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  841. return false
  842. }
  843. if !isDigits(nil, parts[1]) {
  844. return false
  845. }
  846. port, err := strconv.Atoi(parts[1])
  847. if err != nil {
  848. return false
  849. }
  850. return port > 0 && port < 65536
  851. }
  852. func isIPAddress(_ *Config, value string) bool {
  853. return net.ParseIP(value) != nil
  854. }
  855. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  856. func isDomain(_ *Config, value string) bool {
  857. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  858. //
  859. // "ensures that each segment
  860. // * contains at least one character and a maximum of 63 characters
  861. // * consists only of allowed characters
  862. // * doesn't begin or end with a hyphen"
  863. //
  864. if len(value) > 255 {
  865. return false
  866. }
  867. value = strings.TrimSuffix(value, ".")
  868. for _, part := range strings.Split(value, ".") {
  869. // Note: regexp doesn't support the following Perl expression which
  870. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  871. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  872. return false
  873. }
  874. if !isDomainRegex.Match([]byte(part)) {
  875. return false
  876. }
  877. }
  878. return true
  879. }
  880. func isHostHeader(_ *Config, value string) bool {
  881. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  882. if strings.Contains(value, ":") {
  883. return isDialAddress(nil, value)
  884. }
  885. return isIPAddress(nil, value) || isDomain(nil, value)
  886. }
  887. func isServerEntrySource(_ *Config, value string) bool {
  888. return common.Contains(protocol.SupportedServerEntrySources, value)
  889. }
  890. var isISO8601DateRegex = regexp.MustCompile(
  891. "(?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})))")
  892. func isISO8601Date(_ *Config, value string) bool {
  893. return isISO8601DateRegex.Match([]byte(value))
  894. }
  895. func isLastConnected(_ *Config, value string) bool {
  896. return value == "None" || value == "Unknown" || isISO8601Date(nil, value)
  897. }