api.go 27 KB

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