api.go 25 KB

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