api.go 22 KB

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