api.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. )
  34. const (
  35. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  36. CLIENT_VERIFICATION_TTL_SECONDS = 60 * 60 * 24 * 7 // 7 days
  37. CLIENT_PLATFORM_ANDROID = "Android"
  38. CLIENT_PLATFORM_WINDOWS = "Windows"
  39. CLIENT_PLATFORM_IOS = "iOS"
  40. )
  41. var CLIENT_VERIFICATION_REQUIRED = false
  42. type requestJSONObject map[string]interface{}
  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 requestJSONObject
  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 requestJSONObject) (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, 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. // handshakeAPIRequestHandler implements the "handshake" API request.
  159. // Clients make the handshake immediately after establishing a tunnel
  160. // connection; the response tells the client what homepage to open, what
  161. // stats to record, etc.
  162. func handshakeAPIRequestHandler(
  163. support *SupportServices,
  164. apiProtocol string,
  165. geoIPData GeoIPData,
  166. params requestJSONObject) ([]byte, error) {
  167. // Note: ignoring "known_servers" params
  168. err := validateRequestParams(support, params, baseRequestParams)
  169. if err != nil {
  170. return nil, common.ContextError(err)
  171. }
  172. sessionID, _ := getStringRequestParam(params, "client_session_id")
  173. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  174. clientVersion, _ := getStringRequestParam(params, "client_version")
  175. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  176. isMobile := isMobileClientPlatform(clientPlatform)
  177. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  178. var authorizations []string
  179. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  180. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  181. if err != nil {
  182. return nil, common.ContextError(err)
  183. }
  184. }
  185. // Note: no guarantee that PsinetDatabase won't reload between database calls
  186. db := support.PsinetDatabase
  187. httpsRequestRegexes := db.GetHttpsRequestRegexes(sponsorID)
  188. // Flag the SSH client as having completed its handshake. This
  189. // may reselect traffic rules and starts allowing port forwards.
  190. // TODO: in the case of SSH API requests, the actual sshClient could
  191. // be passed in and used here. The session ID lookup is only strictly
  192. // necessary to support web API requests.
  193. activeAuthorizationIDs, authorizedAccessTypes, err := support.TunnelServer.SetClientHandshakeState(
  194. sessionID,
  195. handshakeState{
  196. completed: true,
  197. apiProtocol: apiProtocol,
  198. apiParams: copyBaseRequestParams(params),
  199. expectDomainBytes: len(httpsRequestRegexes) > 0,
  200. },
  201. authorizations)
  202. if err != nil {
  203. return nil, common.ContextError(err)
  204. }
  205. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  206. // the state change (for example, if a second handshake is performed)
  207. //
  208. // The handshake event is no longer shipped to log consumers, so this is
  209. // simply a diagnostic log.
  210. log.WithContextFields(
  211. getRequestLogFields(
  212. "",
  213. geoIPData,
  214. authorizedAccessTypes,
  215. params,
  216. baseRequestParams)).Info("handshake")
  217. handshakeResponse := protocol.HandshakeResponse{
  218. SSHSessionID: sessionID,
  219. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, isMobile),
  220. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  221. PageViewRegexes: make([]map[string]string, 0),
  222. HttpsRequestRegexes: httpsRequestRegexes,
  223. EncodedServerList: db.DiscoverServers(geoIPData.DiscoveryValue),
  224. ClientRegion: geoIPData.Country,
  225. ServerTimestamp: common.GetCurrentTimestamp(),
  226. ActiveAuthorizationIDs: activeAuthorizationIDs,
  227. }
  228. responsePayload, err := json.Marshal(handshakeResponse)
  229. if err != nil {
  230. return nil, common.ContextError(err)
  231. }
  232. return responsePayload, nil
  233. }
  234. var connectedRequestParams = append(
  235. []requestParamSpec{
  236. {"session_id", isHexDigits, 0},
  237. {"last_connected", isLastConnected, 0},
  238. {"establishment_duration", isIntString, requestParamOptional}},
  239. baseRequestParams...)
  240. // connectedAPIRequestHandler implements the "connected" API request.
  241. // Clients make the connected request once a tunnel connection has been
  242. // established and at least once per day. The last_connected input value,
  243. // which should be a connected_timestamp output from a previous connected
  244. // response, is used to calculate unique user stats.
  245. func connectedAPIRequestHandler(
  246. support *SupportServices,
  247. geoIPData GeoIPData,
  248. authorizedAccessTypes []string,
  249. params requestJSONObject) ([]byte, error) {
  250. err := validateRequestParams(support, params, connectedRequestParams)
  251. if err != nil {
  252. return nil, common.ContextError(err)
  253. }
  254. log.LogRawFieldsWithTimestamp(
  255. getRequestLogFields(
  256. "connected",
  257. geoIPData,
  258. authorizedAccessTypes,
  259. params,
  260. connectedRequestParams))
  261. connectedResponse := protocol.ConnectedResponse{
  262. ConnectedTimestamp: common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  263. }
  264. responsePayload, err := json.Marshal(connectedResponse)
  265. if err != nil {
  266. return nil, common.ContextError(err)
  267. }
  268. return responsePayload, nil
  269. }
  270. var statusRequestParams = append(
  271. []requestParamSpec{
  272. {"session_id", isHexDigits, 0},
  273. {"connected", isBooleanFlag, 0}},
  274. baseRequestParams...)
  275. // statusAPIRequestHandler implements the "status" API request.
  276. // Clients make periodic status requests which deliver client-side
  277. // recorded data transfer and tunnel duration stats.
  278. // Note from psi_web implementation: no input validation on domains;
  279. // any string is accepted (regex transform may result in arbitrary
  280. // string). Stats processor must handle this input with care.
  281. func statusAPIRequestHandler(
  282. support *SupportServices,
  283. geoIPData GeoIPData,
  284. authorizedAccessTypes []string,
  285. params requestJSONObject) ([]byte, error) {
  286. err := validateRequestParams(support, params, statusRequestParams)
  287. if err != nil {
  288. return nil, common.ContextError(err)
  289. }
  290. sessionID, _ := getStringRequestParam(params, "client_session_id")
  291. statusData, err := getJSONObjectRequestParam(params, "statusData")
  292. if err != nil {
  293. return nil, common.ContextError(err)
  294. }
  295. // Logs are queued until the input is fully validated. Otherwise, stats
  296. // could be double counted if the client has a bug in its request
  297. // formatting: partial stats would be logged (counted), the request would
  298. // fail, and clients would then resend all the same stats again.
  299. logQueue := make([]LogFields, 0)
  300. // Domain bytes transferred stats
  301. // Older clients may not submit this data
  302. // Clients are expected to send host_bytes/domain_bytes stats only when
  303. // configured to do so in the handshake reponse. Legacy clients may still
  304. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  305. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  306. if err != nil {
  307. return nil, common.ContextError(err)
  308. }
  309. if domainBytesExpected && statusData["host_bytes"] != nil {
  310. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  311. if err != nil {
  312. return nil, common.ContextError(err)
  313. }
  314. for domain, bytes := range hostBytes {
  315. domainBytesFields := getRequestLogFields(
  316. "domain_bytes",
  317. geoIPData,
  318. authorizedAccessTypes,
  319. params,
  320. statusRequestParams)
  321. domainBytesFields["domain"] = domain
  322. domainBytesFields["bytes"] = bytes
  323. logQueue = append(logQueue, domainBytesFields)
  324. }
  325. }
  326. // Remote server list download stats
  327. // Older clients may not submit this data
  328. if statusData["remote_server_list_stats"] != nil {
  329. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  330. if err != nil {
  331. return nil, common.ContextError(err)
  332. }
  333. for _, remoteServerListStat := range remoteServerListStats {
  334. remoteServerListFields := getRequestLogFields(
  335. "remote_server_list",
  336. geoIPData,
  337. authorizedAccessTypes,
  338. params,
  339. statusRequestParams)
  340. clientDownloadTimestamp, err := getStringRequestParam(remoteServerListStat, "client_download_timestamp")
  341. if err != nil {
  342. return nil, common.ContextError(err)
  343. }
  344. remoteServerListFields["client_download_timestamp"] = clientDownloadTimestamp
  345. url, err := getStringRequestParam(remoteServerListStat, "url")
  346. if err != nil {
  347. return nil, common.ContextError(err)
  348. }
  349. remoteServerListFields["url"] = url
  350. etag, err := getStringRequestParam(remoteServerListStat, "etag")
  351. if err != nil {
  352. return nil, common.ContextError(err)
  353. }
  354. remoteServerListFields["etag"] = etag
  355. logQueue = append(logQueue, remoteServerListFields)
  356. }
  357. }
  358. for _, logItem := range logQueue {
  359. log.LogRawFieldsWithTimestamp(logItem)
  360. }
  361. return make([]byte, 0), nil
  362. }
  363. // clientVerificationAPIRequestHandler implements the
  364. // "client verification" API request. Clients make the client
  365. // verification request once per tunnel connection. The payload
  366. // attests that client is a legitimate Psiphon client.
  367. func clientVerificationAPIRequestHandler(
  368. support *SupportServices,
  369. geoIPData GeoIPData,
  370. authorizedAccessTypes []string,
  371. params requestJSONObject) ([]byte, error) {
  372. err := validateRequestParams(support, params, baseRequestParams)
  373. if err != nil {
  374. return nil, common.ContextError(err)
  375. }
  376. // Ignoring error as params are validated
  377. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  378. // Client sends empty payload to receive TTL
  379. // NOTE: these events are not currently logged
  380. if params["verificationData"] == nil {
  381. if CLIENT_VERIFICATION_REQUIRED {
  382. var clientVerificationResponse struct {
  383. ClientVerificationTTLSeconds int `json:"client_verification_ttl_seconds"`
  384. }
  385. clientVerificationResponse.ClientVerificationTTLSeconds = CLIENT_VERIFICATION_TTL_SECONDS
  386. responsePayload, err := json.Marshal(clientVerificationResponse)
  387. if err != nil {
  388. return nil, common.ContextError(err)
  389. }
  390. return responsePayload, nil
  391. }
  392. return make([]byte, 0), nil
  393. } else {
  394. verificationData, err := getJSONObjectRequestParam(params, "verificationData")
  395. if err != nil {
  396. return nil, common.ContextError(err)
  397. }
  398. logFields := getRequestLogFields(
  399. "client_verification",
  400. geoIPData,
  401. authorizedAccessTypes,
  402. params,
  403. baseRequestParams)
  404. var verified bool
  405. var safetyNetCheckLogs LogFields
  406. switch normalizeClientPlatform(clientPlatform) {
  407. case CLIENT_PLATFORM_ANDROID:
  408. verified, safetyNetCheckLogs = verifySafetyNetPayload(verificationData)
  409. logFields["safetynet_check"] = safetyNetCheckLogs
  410. }
  411. log.LogRawFieldsWithTimestamp(logFields)
  412. if verified {
  413. // TODO: change throttling treatment
  414. }
  415. return make([]byte, 0), nil
  416. }
  417. }
  418. type requestParamSpec struct {
  419. name string
  420. validator func(*SupportServices, string) bool
  421. flags uint32
  422. }
  423. const (
  424. requestParamOptional = 1
  425. requestParamNotLogged = 2
  426. requestParamArray = 4
  427. )
  428. // baseRequestParams is the list of required and optional
  429. // request parameters; derived from COMMON_INPUTS and
  430. // OPTIONAL_COMMON_INPUTS in psi_web.
  431. // Each param is expected to be a string, unless requestParamArray
  432. // is specified, in which case an array of string is expected.
  433. var baseRequestParams = []requestParamSpec{
  434. {"server_secret", isServerSecret, requestParamNotLogged},
  435. {"client_session_id", isHexDigits, requestParamNotLogged},
  436. {"propagation_channel_id", isHexDigits, 0},
  437. {"sponsor_id", isHexDigits, 0},
  438. {"client_version", isIntString, 0},
  439. {"client_platform", isClientPlatform, 0},
  440. {"client_build_rev", isHexDigits, requestParamOptional},
  441. {"relay_protocol", isRelayProtocol, 0},
  442. {"tunnel_whole_device", isBooleanFlag, requestParamOptional},
  443. {"device_region", isRegionCode, requestParamOptional},
  444. {"ssh_client_version", isAnyString, requestParamOptional},
  445. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  446. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  447. {"meek_dial_address", isDialAddress, requestParamOptional},
  448. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  449. {"meek_sni_server_name", isDomain, requestParamOptional},
  450. {"meek_host_header", isHostHeader, requestParamOptional},
  451. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  452. {"user_agent", isAnyString, requestParamOptional},
  453. {"tls_profile", isAnyString, requestParamOptional},
  454. {"server_entry_region", isRegionCode, requestParamOptional},
  455. {"server_entry_source", isServerEntrySource, requestParamOptional},
  456. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  457. }
  458. func validateRequestParams(
  459. support *SupportServices,
  460. params requestJSONObject,
  461. expectedParams []requestParamSpec) error {
  462. for _, expectedParam := range expectedParams {
  463. value := params[expectedParam.name]
  464. if value == nil {
  465. if expectedParam.flags&requestParamOptional != 0 {
  466. continue
  467. }
  468. return common.ContextError(
  469. fmt.Errorf("missing param: %s", expectedParam.name))
  470. }
  471. var err error
  472. if expectedParam.flags&requestParamArray != 0 {
  473. err = validateStringArrayRequestParam(support, expectedParam, value)
  474. } else {
  475. err = validateStringRequestParam(support, expectedParam, value)
  476. }
  477. if err != nil {
  478. return common.ContextError(err)
  479. }
  480. }
  481. return nil
  482. }
  483. // copyBaseRequestParams makes a copy of the params which
  484. // includes only the baseRequestParams.
  485. func copyBaseRequestParams(params requestJSONObject) requestJSONObject {
  486. // Note: not a deep copy; assumes baseRequestParams values
  487. // are all scalar types (int, string, etc.)
  488. paramsCopy := make(requestJSONObject)
  489. for _, baseParam := range baseRequestParams {
  490. value := params[baseParam.name]
  491. if value == nil {
  492. continue
  493. }
  494. paramsCopy[baseParam.name] = value
  495. }
  496. return paramsCopy
  497. }
  498. func validateStringRequestParam(
  499. support *SupportServices,
  500. expectedParam requestParamSpec,
  501. value interface{}) error {
  502. strValue, ok := value.(string)
  503. if !ok {
  504. return common.ContextError(
  505. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  506. }
  507. if !expectedParam.validator(support, strValue) {
  508. return common.ContextError(
  509. fmt.Errorf("invalid param: %s", expectedParam.name))
  510. }
  511. return nil
  512. }
  513. func validateStringArrayRequestParam(
  514. support *SupportServices,
  515. expectedParam requestParamSpec,
  516. value interface{}) error {
  517. arrayValue, ok := value.([]interface{})
  518. if !ok {
  519. return common.ContextError(
  520. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  521. }
  522. for _, value := range arrayValue {
  523. err := validateStringRequestParam(support, expectedParam, value)
  524. if err != nil {
  525. return common.ContextError(err)
  526. }
  527. }
  528. return nil
  529. }
  530. // getRequestLogFields makes LogFields to log the API event following
  531. // the legacy psi_web and current ELK naming conventions.
  532. func getRequestLogFields(
  533. eventName string,
  534. geoIPData GeoIPData,
  535. authorizedAccessTypes []string,
  536. params requestJSONObject,
  537. expectedParams []requestParamSpec) LogFields {
  538. logFields := make(LogFields)
  539. if eventName != "" {
  540. logFields["event_name"] = eventName
  541. }
  542. // In psi_web, the space replacement was done to accommodate space
  543. // delimited logging, which is no longer required; we retain the
  544. // transformation so that stats aggregation isn't impacted.
  545. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  546. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  547. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  548. if len(authorizedAccessTypes) > 0 {
  549. logFields["authorized_access_types"] = authorizedAccessTypes
  550. }
  551. if params == nil {
  552. return logFields
  553. }
  554. for _, expectedParam := range expectedParams {
  555. if expectedParam.flags&requestParamNotLogged != 0 {
  556. continue
  557. }
  558. value := params[expectedParam.name]
  559. if value == nil {
  560. // Special case: older clients don't send this value,
  561. // so log a default.
  562. if expectedParam.name == "tunnel_whole_device" {
  563. value = "0"
  564. } else {
  565. // Skip omitted, optional params
  566. continue
  567. }
  568. }
  569. switch v := value.(type) {
  570. case string:
  571. strValue := v
  572. // Special cases:
  573. // - Number fields are encoded as integer types.
  574. // - For ELK performance we record these domain-or-IP
  575. // fields as one of two different values based on type;
  576. // we also omit port from host:port fields for now.
  577. switch expectedParam.name {
  578. case "client_version", "establishment_duration":
  579. intValue, _ := strconv.Atoi(strValue)
  580. logFields[expectedParam.name] = intValue
  581. case "meek_dial_address":
  582. host, _, _ := net.SplitHostPort(strValue)
  583. if isIPAddress(nil, host) {
  584. logFields["meek_dial_ip_address"] = host
  585. } else {
  586. logFields["meek_dial_domain"] = host
  587. }
  588. case "meek_host_header":
  589. host, _, _ := net.SplitHostPort(strValue)
  590. logFields[expectedParam.name] = host
  591. case "upstream_proxy_type":
  592. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  593. logFields[expectedParam.name] = strings.ToLower(strValue)
  594. default:
  595. logFields[expectedParam.name] = strValue
  596. }
  597. case []interface{}:
  598. // Note: actually validated as an array of strings
  599. logFields[expectedParam.name] = v
  600. default:
  601. // This type assertion should be checked already in
  602. // validateRequestParams, so failure is unexpected.
  603. continue
  604. }
  605. }
  606. return logFields
  607. }
  608. func getStringRequestParam(params requestJSONObject, name string) (string, error) {
  609. if params[name] == nil {
  610. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  611. }
  612. value, ok := params[name].(string)
  613. if !ok {
  614. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  615. }
  616. return value, nil
  617. }
  618. func getInt64RequestParam(params requestJSONObject, name string) (int64, error) {
  619. if params[name] == nil {
  620. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  621. }
  622. value, ok := params[name].(float64)
  623. if !ok {
  624. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  625. }
  626. return int64(value), nil
  627. }
  628. func getJSONObjectRequestParam(params requestJSONObject, name string) (requestJSONObject, error) {
  629. if params[name] == nil {
  630. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  631. }
  632. // Note: generic unmarshal of JSON produces map[string]interface{}, not requestJSONObject
  633. value, ok := params[name].(map[string]interface{})
  634. if !ok {
  635. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  636. }
  637. return requestJSONObject(value), nil
  638. }
  639. func getJSONObjectArrayRequestParam(params requestJSONObject, name string) ([]requestJSONObject, error) {
  640. if params[name] == nil {
  641. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  642. }
  643. value, ok := params[name].([]interface{})
  644. if !ok {
  645. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  646. }
  647. result := make([]requestJSONObject, len(value))
  648. for i, item := range value {
  649. // Note: generic unmarshal of JSON produces map[string]interface{}, not requestJSONObject
  650. resultItem, ok := item.(map[string]interface{})
  651. if !ok {
  652. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  653. }
  654. result[i] = requestJSONObject(resultItem)
  655. }
  656. return result, nil
  657. }
  658. func getMapStringInt64RequestParam(params requestJSONObject, name string) (map[string]int64, error) {
  659. if params[name] == nil {
  660. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  661. }
  662. // TODO: can't use requestJSONObject type?
  663. value, ok := params[name].(map[string]interface{})
  664. if !ok {
  665. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  666. }
  667. result := make(map[string]int64)
  668. for k, v := range value {
  669. numValue, ok := v.(float64)
  670. if !ok {
  671. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  672. }
  673. result[k] = int64(numValue)
  674. }
  675. return result, nil
  676. }
  677. func getStringArrayRequestParam(params requestJSONObject, name string) ([]string, error) {
  678. if params[name] == nil {
  679. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  680. }
  681. value, ok := params[name].([]interface{})
  682. if !ok {
  683. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  684. }
  685. result := make([]string, len(value))
  686. for i, v := range value {
  687. strValue, ok := v.(string)
  688. if !ok {
  689. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  690. }
  691. result[i] = strValue
  692. }
  693. return result, nil
  694. }
  695. // Normalize reported client platform. Android clients, for example, report
  696. // OS version, rooted status, and Google Play build status in the clientPlatform
  697. // string along with "Android".
  698. func normalizeClientPlatform(clientPlatform string) string {
  699. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  700. return CLIENT_PLATFORM_ANDROID
  701. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  702. return CLIENT_PLATFORM_IOS
  703. }
  704. return CLIENT_PLATFORM_WINDOWS
  705. }
  706. func isAnyString(support *SupportServices, value string) bool {
  707. return true
  708. }
  709. func isMobileClientPlatform(clientPlatform string) bool {
  710. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  711. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  712. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  713. }
  714. // Input validators follow the legacy validations rules in psi_web.
  715. func isServerSecret(support *SupportServices, value string) bool {
  716. return subtle.ConstantTimeCompare(
  717. []byte(value),
  718. []byte(support.Config.WebServerSecret)) == 1
  719. }
  720. func isHexDigits(_ *SupportServices, value string) bool {
  721. // Allows both uppercase in addition to lowercase, for legacy support.
  722. return -1 == strings.IndexFunc(value, func(c rune) bool {
  723. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  724. })
  725. }
  726. func isDigits(_ *SupportServices, value string) bool {
  727. return -1 == strings.IndexFunc(value, func(c rune) bool {
  728. return c < '0' || c > '9'
  729. })
  730. }
  731. func isIntString(_ *SupportServices, value string) bool {
  732. _, err := strconv.Atoi(value)
  733. return err == nil
  734. }
  735. func isClientPlatform(_ *SupportServices, value string) bool {
  736. return -1 == strings.IndexFunc(value, func(c rune) bool {
  737. // Note: stricter than psi_web's Python string.whitespace
  738. return unicode.Is(unicode.White_Space, c)
  739. })
  740. }
  741. func isRelayProtocol(_ *SupportServices, value string) bool {
  742. return common.Contains(protocol.SupportedTunnelProtocols, value)
  743. }
  744. func isBooleanFlag(_ *SupportServices, value string) bool {
  745. return value == "0" || value == "1"
  746. }
  747. func isUpstreamProxyType(_ *SupportServices, value string) bool {
  748. value = strings.ToLower(value)
  749. return value == "http" || value == "socks5" || value == "socks4a"
  750. }
  751. func isRegionCode(_ *SupportServices, value string) bool {
  752. if len(value) != 2 {
  753. return false
  754. }
  755. return -1 == strings.IndexFunc(value, func(c rune) bool {
  756. return c < 'A' || c > 'Z'
  757. })
  758. }
  759. func isDialAddress(_ *SupportServices, value string) bool {
  760. // "<host>:<port>", where <host> is a domain or IP address
  761. parts := strings.Split(value, ":")
  762. if len(parts) != 2 {
  763. return false
  764. }
  765. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  766. return false
  767. }
  768. if !isDigits(nil, parts[1]) {
  769. return false
  770. }
  771. port, err := strconv.Atoi(parts[1])
  772. if err != nil {
  773. return false
  774. }
  775. return port > 0 && port < 65536
  776. }
  777. func isIPAddress(_ *SupportServices, value string) bool {
  778. return net.ParseIP(value) != nil
  779. }
  780. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  781. func isDomain(_ *SupportServices, value string) bool {
  782. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  783. //
  784. // "ensures that each segment
  785. // * contains at least one character and a maximum of 63 characters
  786. // * consists only of allowed characters
  787. // * doesn't begin or end with a hyphen"
  788. //
  789. if len(value) > 255 {
  790. return false
  791. }
  792. value = strings.TrimSuffix(value, ".")
  793. for _, part := range strings.Split(value, ".") {
  794. // Note: regexp doesn't support the following Perl expression which
  795. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  796. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  797. return false
  798. }
  799. if !isDomainRegex.Match([]byte(part)) {
  800. return false
  801. }
  802. }
  803. return true
  804. }
  805. func isHostHeader(_ *SupportServices, value string) bool {
  806. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  807. if strings.Contains(value, ":") {
  808. return isDialAddress(nil, value)
  809. }
  810. return isIPAddress(nil, value) || isDomain(nil, value)
  811. }
  812. func isServerEntrySource(_ *SupportServices, value string) bool {
  813. return common.Contains(protocol.SupportedServerEntrySources, value)
  814. }
  815. var isISO8601DateRegex = regexp.MustCompile(
  816. "(?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})))")
  817. func isISO8601Date(_ *SupportServices, value string) bool {
  818. return isISO8601DateRegex.Match([]byte(value))
  819. }
  820. func isLastConnected(_ *SupportServices, value string) bool {
  821. return value == "None" || value == "Unknown" || isISO8601Date(nil, value)
  822. }