api.go 26 KB

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