api.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. var verified bool
  286. switch normalizeClientPlatform(clientPlatform) {
  287. case CLIENT_PLATFORM_ANDROID:
  288. verified = verifySafetyNetPayload(verificationData)
  289. }
  290. if verified {
  291. // TODO: change throttling treatment
  292. }
  293. return make([]byte, 0), nil
  294. }
  295. type requestParamSpec struct {
  296. name string
  297. validator func(*SupportServices, string) bool
  298. flags uint32
  299. }
  300. const (
  301. requestParamOptional = 1
  302. requestParamNotLogged = 2
  303. requestParamArray = 4
  304. )
  305. // baseRequestParams is the list of required and optional
  306. // request parameters; derived from COMMON_INPUTS and
  307. // OPTIONAL_COMMON_INPUTS in psi_web.
  308. // Each param is expected to be a string, unless requestParamArray
  309. // is specified, in which case an array of string is expected.
  310. var baseRequestParams = []requestParamSpec{
  311. requestParamSpec{"server_secret", isServerSecret, requestParamNotLogged},
  312. requestParamSpec{"client_session_id", isHexDigits, requestParamOptional},
  313. requestParamSpec{"propagation_channel_id", isHexDigits, 0},
  314. requestParamSpec{"sponsor_id", isHexDigits, 0},
  315. requestParamSpec{"client_version", isDigits, 0},
  316. requestParamSpec{"client_platform", isClientPlatform, 0},
  317. requestParamSpec{"relay_protocol", isRelayProtocol, 0},
  318. requestParamSpec{"tunnel_whole_device", isBooleanFlag, requestParamOptional},
  319. requestParamSpec{"device_region", isRegionCode, requestParamOptional},
  320. requestParamSpec{"upstream_proxy_type", isAnyString, requestParamOptional},
  321. requestParamSpec{"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  322. requestParamSpec{"meek_dial_address", isDialAddress, requestParamOptional},
  323. requestParamSpec{"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  324. requestParamSpec{"meek_sni_server_name", isDomain, requestParamOptional},
  325. requestParamSpec{"meek_host_header", isHostHeader, requestParamOptional},
  326. requestParamSpec{"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  327. requestParamSpec{"server_entry_region", isRegionCode, requestParamOptional},
  328. requestParamSpec{"server_entry_source", isServerEntrySource, requestParamOptional},
  329. requestParamSpec{"server_entry_timestamp", isISO8601Date, requestParamOptional},
  330. }
  331. func validateRequestParams(
  332. support *SupportServices,
  333. params requestJSONObject,
  334. expectedParams []requestParamSpec) error {
  335. for _, expectedParam := range expectedParams {
  336. value := params[expectedParam.name]
  337. if value == nil {
  338. if expectedParam.flags&requestParamOptional != 0 {
  339. continue
  340. }
  341. return psiphon.ContextError(
  342. fmt.Errorf("missing param: %s", expectedParam.name))
  343. }
  344. var err error
  345. if expectedParam.flags&requestParamArray != 0 {
  346. err = validateStringArrayRequestParam(support, expectedParam, value)
  347. } else {
  348. err = validateStringRequestParam(support, expectedParam, value)
  349. }
  350. if err != nil {
  351. return psiphon.ContextError(err)
  352. }
  353. }
  354. return nil
  355. }
  356. func validateStringRequestParam(
  357. support *SupportServices,
  358. expectedParam requestParamSpec,
  359. value interface{}) error {
  360. strValue, ok := value.(string)
  361. if !ok {
  362. return psiphon.ContextError(
  363. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  364. }
  365. if !expectedParam.validator(support, strValue) {
  366. return psiphon.ContextError(
  367. fmt.Errorf("invalid param: %s", expectedParam.name))
  368. }
  369. return nil
  370. }
  371. func validateStringArrayRequestParam(
  372. support *SupportServices,
  373. expectedParam requestParamSpec,
  374. value interface{}) error {
  375. arrayValue, ok := value.([]interface{})
  376. if !ok {
  377. return psiphon.ContextError(
  378. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  379. }
  380. for _, value := range arrayValue {
  381. err := validateStringRequestParam(support, expectedParam, value)
  382. if err != nil {
  383. return psiphon.ContextError(err)
  384. }
  385. }
  386. return nil
  387. }
  388. // getRequestLogFields makes LogFields to log the API event following
  389. // the legacy psi_web and current ELK naming conventions.
  390. func getRequestLogFields(
  391. support *SupportServices,
  392. eventName string,
  393. geoIPData GeoIPData,
  394. params requestJSONObject,
  395. expectedParams []requestParamSpec) LogFields {
  396. logFields := make(LogFields)
  397. logFields["event_name"] = eventName
  398. logFields["host_id"] = support.Config.HostID
  399. // In psi_web, the space replacement was done to accommodate space
  400. // delimited logging, which is no longer required; we retain the
  401. // transformation so that stats aggregation isn't impacted.
  402. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  403. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  404. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  405. for _, expectedParam := range expectedParams {
  406. if expectedParam.flags&requestParamNotLogged != 0 {
  407. continue
  408. }
  409. value := params[expectedParam.name]
  410. if value == nil {
  411. // Special case: older clients don't send this value,
  412. // so log a default.
  413. if expectedParam.name == "tunnel_whole_device" {
  414. value = "0"
  415. } else {
  416. // Skip omitted, optional params
  417. continue
  418. }
  419. }
  420. switch v := value.(type) {
  421. case string:
  422. strValue := v
  423. // Special cases:
  424. // - Number fields are encoded as integer types.
  425. // - For ELK performance we record these domain-or-IP
  426. // fields as one of two different values based on type;
  427. // we also omit port from host:port fields for now.
  428. switch expectedParam.name {
  429. case "client_version":
  430. intValue, _ := strconv.Atoi(strValue)
  431. logFields[expectedParam.name] = intValue
  432. case "meek_dial_address":
  433. host, _, _ := net.SplitHostPort(strValue)
  434. if isIPAddress(support, host) {
  435. logFields["meek_dial_ip_address"] = host
  436. } else {
  437. logFields["meek_dial_domain"] = host
  438. }
  439. case "meek_host_header":
  440. host, _, _ := net.SplitHostPort(strValue)
  441. logFields[expectedParam.name] = host
  442. default:
  443. logFields[expectedParam.name] = strValue
  444. }
  445. case []interface{}:
  446. // Note: actually validated as an array of strings
  447. logFields[expectedParam.name] = v
  448. default:
  449. // This type assertion should be checked already in
  450. // validateRequestParams, so failure is unexpected.
  451. continue
  452. }
  453. }
  454. return logFields
  455. }
  456. func getStringRequestParam(params requestJSONObject, name string) (string, error) {
  457. if params[name] == nil {
  458. return "", psiphon.ContextError(fmt.Errorf("missing param: %s", name))
  459. }
  460. value, ok := params[name].(string)
  461. if !ok {
  462. return "", psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  463. }
  464. return value, nil
  465. }
  466. func getInt64RequestParam(params requestJSONObject, name string) (int64, error) {
  467. if params[name] == nil {
  468. return 0, psiphon.ContextError(fmt.Errorf("missing param: %s", name))
  469. }
  470. value, ok := params[name].(float64)
  471. if !ok {
  472. return 0, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  473. }
  474. return int64(value), nil
  475. }
  476. func getJSONObjectRequestParam(params requestJSONObject, name string) (requestJSONObject, error) {
  477. if params[name] == nil {
  478. return nil, psiphon.ContextError(fmt.Errorf("missing param: %s", name))
  479. }
  480. // TODO: can't use requestJSONObject type?
  481. value, ok := params[name].(map[string]interface{})
  482. if !ok {
  483. return nil, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  484. }
  485. return requestJSONObject(value), nil
  486. }
  487. func getJSONObjectArrayRequestParam(params requestJSONObject, name string) ([]requestJSONObject, error) {
  488. if params[name] == nil {
  489. return nil, psiphon.ContextError(fmt.Errorf("missing param: %s", name))
  490. }
  491. value, ok := params[name].([]interface{})
  492. if !ok {
  493. return nil, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  494. }
  495. result := make([]requestJSONObject, len(value))
  496. for i, item := range value {
  497. // TODO: can't use requestJSONObject type?
  498. resultItem, ok := item.(map[string]interface{})
  499. if !ok {
  500. return nil, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  501. }
  502. result[i] = requestJSONObject(resultItem)
  503. }
  504. return result, nil
  505. }
  506. func getMapStringInt64RequestParam(params requestJSONObject, name string) (map[string]int64, error) {
  507. if params[name] == nil {
  508. return nil, psiphon.ContextError(fmt.Errorf("missing param: %s", name))
  509. }
  510. // TODO: can't use requestJSONObject type?
  511. value, ok := params[name].(map[string]interface{})
  512. if !ok {
  513. return nil, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  514. }
  515. result := make(map[string]int64)
  516. for k, v := range value {
  517. numValue, ok := v.(float64)
  518. if !ok {
  519. return nil, psiphon.ContextError(fmt.Errorf("invalid param: %s", name))
  520. }
  521. result[k] = int64(numValue)
  522. }
  523. return result, nil
  524. }
  525. // Normalize reported client platform. Android clients, for example, report
  526. // OS version, rooted status, and Google Play build status in the clientPlatform
  527. // string along with "Android".
  528. func normalizeClientPlatform(clientPlatform string) string {
  529. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  530. return CLIENT_PLATFORM_ANDROID
  531. }
  532. return CLIENT_PLATFORM_WINDOWS
  533. }
  534. func isMobileClientPlatform(clientPlatform string) bool {
  535. return normalizeClientPlatform(clientPlatform) == CLIENT_PLATFORM_ANDROID
  536. }
  537. // Input validators follow the legacy validations rules in psi_web.
  538. func isAnyString(support *SupportServices, value string) bool {
  539. return true
  540. }
  541. func isServerSecret(support *SupportServices, value string) bool {
  542. return subtle.ConstantTimeCompare(
  543. []byte(value),
  544. []byte(support.Config.WebServerSecret)) == 1
  545. }
  546. func isHexDigits(_ *SupportServices, value string) bool {
  547. return -1 == strings.IndexFunc(value, func(c rune) bool {
  548. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  549. })
  550. }
  551. func isDigits(_ *SupportServices, value string) bool {
  552. return -1 == strings.IndexFunc(value, func(c rune) bool {
  553. return c < '0' || c > '9'
  554. })
  555. }
  556. func isClientPlatform(_ *SupportServices, value string) bool {
  557. return -1 == strings.IndexFunc(value, func(c rune) bool {
  558. // Note: stricter than psi_web's Python string.whitespace
  559. return unicode.Is(unicode.White_Space, c)
  560. })
  561. }
  562. func isRelayProtocol(_ *SupportServices, value string) bool {
  563. return psiphon.Contains(psiphon.SupportedTunnelProtocols, value)
  564. }
  565. func isBooleanFlag(_ *SupportServices, value string) bool {
  566. return value == "0" || value == "1"
  567. }
  568. func isRegionCode(_ *SupportServices, value string) bool {
  569. if len(value) != 2 {
  570. return false
  571. }
  572. return -1 == strings.IndexFunc(value, func(c rune) bool {
  573. return c < 'A' || c > 'Z'
  574. })
  575. }
  576. func isDialAddress(support *SupportServices, value string) bool {
  577. // "<host>:<port>", where <host> is a domain or IP address
  578. parts := strings.Split(value, ":")
  579. if len(parts) != 2 {
  580. return false
  581. }
  582. if !isIPAddress(support, parts[0]) && !isDomain(support, parts[0]) {
  583. return false
  584. }
  585. if !isDigits(support, parts[1]) {
  586. return false
  587. }
  588. port, err := strconv.Atoi(parts[1])
  589. if err != nil {
  590. return false
  591. }
  592. return port > 0 && port < 65536
  593. }
  594. func isIPAddress(_ *SupportServices, value string) bool {
  595. return net.ParseIP(value) != nil
  596. }
  597. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  598. func isDomain(_ *SupportServices, value string) bool {
  599. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  600. //
  601. // "ensures that each segment
  602. // * contains at least one character and a maximum of 63 characters
  603. // * consists only of allowed characters
  604. // * doesn't begin or end with a hyphen"
  605. //
  606. if len(value) > 255 {
  607. return false
  608. }
  609. value = strings.TrimSuffix(value, ".")
  610. for _, part := range strings.Split(value, ".") {
  611. // Note: regexp doesn't support the following Perl expression which
  612. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  613. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  614. return false
  615. }
  616. if !isDomainRegex.Match([]byte(part)) {
  617. return false
  618. }
  619. }
  620. return true
  621. }
  622. func isHostHeader(support *SupportServices, value string) bool {
  623. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  624. if strings.Contains(value, ":") {
  625. return isDialAddress(support, value)
  626. }
  627. return isIPAddress(support, value) || isDomain(support, value)
  628. }
  629. func isServerEntrySource(_ *SupportServices, value string) bool {
  630. return psiphon.Contains(psiphon.SupportedServerEntrySources, value)
  631. }
  632. var isISO8601DateRegex = regexp.MustCompile(
  633. "(?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})))")
  634. func isISO8601Date(_ *SupportServices, value string) bool {
  635. return isISO8601DateRegex.Match([]byte(value))
  636. }
  637. func isLastConnected(support *SupportServices, value string) bool {
  638. return value == "None" || value == "Unknown" || isISO8601Date(support, value)
  639. }