api.go 27 KB

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