api.go 33 KB

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