api.go 28 KB

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