api.go 25 KB

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