api.go 24 KB

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