api.go 23 KB

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