api.go 30 KB

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