api.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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, string(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{"relay_protocol", isRelayProtocol, 0},
  427. requestParamSpec{"tunnel_whole_device", isBooleanFlag, requestParamOptional},
  428. requestParamSpec{"device_region", isRegionCode, requestParamOptional},
  429. requestParamSpec{"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  430. requestParamSpec{"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  431. requestParamSpec{"meek_dial_address", isDialAddress, requestParamOptional},
  432. requestParamSpec{"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  433. requestParamSpec{"meek_sni_server_name", isDomain, requestParamOptional},
  434. requestParamSpec{"meek_host_header", isHostHeader, requestParamOptional},
  435. requestParamSpec{"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  436. requestParamSpec{"server_entry_region", isRegionCode, requestParamOptional},
  437. requestParamSpec{"server_entry_source", isServerEntrySource, requestParamOptional},
  438. requestParamSpec{"server_entry_timestamp", isISO8601Date, requestParamOptional},
  439. }
  440. func validateRequestParams(
  441. support *SupportServices,
  442. params requestJSONObject,
  443. expectedParams []requestParamSpec) error {
  444. for _, expectedParam := range expectedParams {
  445. value := params[expectedParam.name]
  446. if value == nil {
  447. if expectedParam.flags&requestParamOptional != 0 {
  448. continue
  449. }
  450. return common.ContextError(
  451. fmt.Errorf("missing param: %s", expectedParam.name))
  452. }
  453. var err error
  454. if expectedParam.flags&requestParamArray != 0 {
  455. err = validateStringArrayRequestParam(support, expectedParam, value)
  456. } else {
  457. err = validateStringRequestParam(support, expectedParam, value)
  458. }
  459. if err != nil {
  460. return common.ContextError(err)
  461. }
  462. }
  463. return nil
  464. }
  465. // copyBaseRequestParams makes a copy of the params which
  466. // includes only the baseRequestParams.
  467. func copyBaseRequestParams(params requestJSONObject) requestJSONObject {
  468. // Note: not a deep copy; assumes baseRequestParams values
  469. // are all scalar types (int, string, etc.)
  470. paramsCopy := make(requestJSONObject)
  471. for _, baseParam := range baseRequestParams {
  472. value := params[baseParam.name]
  473. if value == nil {
  474. continue
  475. }
  476. paramsCopy[baseParam.name] = value
  477. }
  478. return paramsCopy
  479. }
  480. func validateStringRequestParam(
  481. support *SupportServices,
  482. expectedParam requestParamSpec,
  483. value interface{}) error {
  484. strValue, ok := value.(string)
  485. if !ok {
  486. return common.ContextError(
  487. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  488. }
  489. if !expectedParam.validator(support, strValue) {
  490. return common.ContextError(
  491. fmt.Errorf("invalid param: %s", expectedParam.name))
  492. }
  493. return nil
  494. }
  495. func validateStringArrayRequestParam(
  496. support *SupportServices,
  497. expectedParam requestParamSpec,
  498. value interface{}) error {
  499. arrayValue, ok := value.([]interface{})
  500. if !ok {
  501. return common.ContextError(
  502. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  503. }
  504. for _, value := range arrayValue {
  505. err := validateStringRequestParam(support, expectedParam, value)
  506. if err != nil {
  507. return common.ContextError(err)
  508. }
  509. }
  510. return nil
  511. }
  512. // getRequestLogFields makes LogFields to log the API event following
  513. // the legacy psi_web and current ELK naming conventions.
  514. func getRequestLogFields(
  515. support *SupportServices,
  516. eventName string,
  517. geoIPData GeoIPData,
  518. params requestJSONObject,
  519. expectedParams []requestParamSpec) LogFields {
  520. logFields := make(LogFields)
  521. logFields["event_name"] = eventName
  522. // In psi_web, the space replacement was done to accommodate space
  523. // delimited logging, which is no longer required; we retain the
  524. // transformation so that stats aggregation isn't impacted.
  525. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  526. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  527. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  528. if params == nil {
  529. return logFields
  530. }
  531. for _, expectedParam := range expectedParams {
  532. if expectedParam.flags&requestParamNotLogged != 0 {
  533. continue
  534. }
  535. value := params[expectedParam.name]
  536. if value == nil {
  537. // Special case: older clients don't send this value,
  538. // so log a default.
  539. if expectedParam.name == "tunnel_whole_device" {
  540. value = "0"
  541. } else {
  542. // Skip omitted, optional params
  543. continue
  544. }
  545. }
  546. switch v := value.(type) {
  547. case string:
  548. strValue := v
  549. // Special cases:
  550. // - Number fields are encoded as integer types.
  551. // - For ELK performance we record these domain-or-IP
  552. // fields as one of two different values based on type;
  553. // we also omit port from host:port fields for now.
  554. switch expectedParam.name {
  555. case "client_version":
  556. intValue, _ := strconv.Atoi(strValue)
  557. logFields[expectedParam.name] = intValue
  558. case "meek_dial_address":
  559. host, _, _ := net.SplitHostPort(strValue)
  560. if isIPAddress(support, host) {
  561. logFields["meek_dial_ip_address"] = host
  562. } else {
  563. logFields["meek_dial_domain"] = host
  564. }
  565. case "meek_host_header":
  566. host, _, _ := net.SplitHostPort(strValue)
  567. logFields[expectedParam.name] = host
  568. case "upstream_proxy_type":
  569. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  570. logFields[expectedParam.name] = strings.ToLower(strValue)
  571. default:
  572. logFields[expectedParam.name] = strValue
  573. }
  574. case []interface{}:
  575. // Note: actually validated as an array of strings
  576. logFields[expectedParam.name] = v
  577. default:
  578. // This type assertion should be checked already in
  579. // validateRequestParams, so failure is unexpected.
  580. continue
  581. }
  582. }
  583. return logFields
  584. }
  585. func getStringRequestParam(params requestJSONObject, name string) (string, error) {
  586. if params[name] == nil {
  587. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  588. }
  589. value, ok := params[name].(string)
  590. if !ok {
  591. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  592. }
  593. return value, nil
  594. }
  595. func getInt64RequestParam(params requestJSONObject, name string) (int64, error) {
  596. if params[name] == nil {
  597. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  598. }
  599. value, ok := params[name].(float64)
  600. if !ok {
  601. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  602. }
  603. return int64(value), nil
  604. }
  605. func getJSONObjectRequestParam(params requestJSONObject, name string) (requestJSONObject, error) {
  606. if params[name] == nil {
  607. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  608. }
  609. // Note: generic unmarshal of JSON produces map[string]interface{}, not requestJSONObject
  610. value, ok := params[name].(map[string]interface{})
  611. if !ok {
  612. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  613. }
  614. return requestJSONObject(value), nil
  615. }
  616. func getJSONObjectArrayRequestParam(params requestJSONObject, name string) ([]requestJSONObject, error) {
  617. if params[name] == nil {
  618. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  619. }
  620. value, ok := params[name].([]interface{})
  621. if !ok {
  622. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  623. }
  624. result := make([]requestJSONObject, len(value))
  625. for i, item := range value {
  626. // Note: generic unmarshal of JSON produces map[string]interface{}, not requestJSONObject
  627. resultItem, ok := item.(map[string]interface{})
  628. if !ok {
  629. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  630. }
  631. result[i] = requestJSONObject(resultItem)
  632. }
  633. return result, nil
  634. }
  635. func getMapStringInt64RequestParam(params requestJSONObject, name string) (map[string]int64, error) {
  636. if params[name] == nil {
  637. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  638. }
  639. // TODO: can't use requestJSONObject type?
  640. value, ok := params[name].(map[string]interface{})
  641. if !ok {
  642. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  643. }
  644. result := make(map[string]int64)
  645. for k, v := range value {
  646. numValue, ok := v.(float64)
  647. if !ok {
  648. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  649. }
  650. result[k] = int64(numValue)
  651. }
  652. return result, nil
  653. }
  654. // Normalize reported client platform. Android clients, for example, report
  655. // OS version, rooted status, and Google Play build status in the clientPlatform
  656. // string along with "Android".
  657. func normalizeClientPlatform(clientPlatform string) string {
  658. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  659. return CLIENT_PLATFORM_ANDROID
  660. }
  661. return CLIENT_PLATFORM_WINDOWS
  662. }
  663. func isAnyString(support *SupportServices, value string) bool {
  664. return true
  665. }
  666. func isMobileClientPlatform(clientPlatform string) bool {
  667. return normalizeClientPlatform(clientPlatform) == CLIENT_PLATFORM_ANDROID
  668. }
  669. // Input validators follow the legacy validations rules in psi_web.
  670. func isServerSecret(support *SupportServices, value string) bool {
  671. return subtle.ConstantTimeCompare(
  672. []byte(value),
  673. []byte(support.Config.WebServerSecret)) == 1
  674. }
  675. func isHexDigits(_ *SupportServices, value string) bool {
  676. return -1 == strings.IndexFunc(value, func(c rune) bool {
  677. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  678. })
  679. }
  680. func isDigits(_ *SupportServices, value string) bool {
  681. return -1 == strings.IndexFunc(value, func(c rune) bool {
  682. return c < '0' || c > '9'
  683. })
  684. }
  685. func isIntString(_ *SupportServices, value string) bool {
  686. _, err := strconv.Atoi(value)
  687. return err == nil
  688. }
  689. func isClientPlatform(_ *SupportServices, value string) bool {
  690. return -1 == strings.IndexFunc(value, func(c rune) bool {
  691. // Note: stricter than psi_web's Python string.whitespace
  692. return unicode.Is(unicode.White_Space, c)
  693. })
  694. }
  695. func isRelayProtocol(_ *SupportServices, value string) bool {
  696. return common.Contains(protocol.SupportedTunnelProtocols, value)
  697. }
  698. func isBooleanFlag(_ *SupportServices, value string) bool {
  699. return value == "0" || value == "1"
  700. }
  701. func isUpstreamProxyType(_ *SupportServices, value string) bool {
  702. value = strings.ToLower(value)
  703. return value == "http" || value == "socks5" || value == "socks4a"
  704. }
  705. func isRegionCode(_ *SupportServices, value string) bool {
  706. if len(value) != 2 {
  707. return false
  708. }
  709. return -1 == strings.IndexFunc(value, func(c rune) bool {
  710. return c < 'A' || c > 'Z'
  711. })
  712. }
  713. func isDialAddress(support *SupportServices, value string) bool {
  714. // "<host>:<port>", where <host> is a domain or IP address
  715. parts := strings.Split(value, ":")
  716. if len(parts) != 2 {
  717. return false
  718. }
  719. if !isIPAddress(support, parts[0]) && !isDomain(support, parts[0]) {
  720. return false
  721. }
  722. if !isDigits(support, parts[1]) {
  723. return false
  724. }
  725. port, err := strconv.Atoi(parts[1])
  726. if err != nil {
  727. return false
  728. }
  729. return port > 0 && port < 65536
  730. }
  731. func isIPAddress(_ *SupportServices, value string) bool {
  732. return net.ParseIP(value) != nil
  733. }
  734. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  735. func isDomain(_ *SupportServices, value string) bool {
  736. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  737. //
  738. // "ensures that each segment
  739. // * contains at least one character and a maximum of 63 characters
  740. // * consists only of allowed characters
  741. // * doesn't begin or end with a hyphen"
  742. //
  743. if len(value) > 255 {
  744. return false
  745. }
  746. value = strings.TrimSuffix(value, ".")
  747. for _, part := range strings.Split(value, ".") {
  748. // Note: regexp doesn't support the following Perl expression which
  749. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  750. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  751. return false
  752. }
  753. if !isDomainRegex.Match([]byte(part)) {
  754. return false
  755. }
  756. }
  757. return true
  758. }
  759. func isHostHeader(support *SupportServices, value string) bool {
  760. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  761. if strings.Contains(value, ":") {
  762. return isDialAddress(support, value)
  763. }
  764. return isIPAddress(support, value) || isDomain(support, value)
  765. }
  766. func isServerEntrySource(_ *SupportServices, value string) bool {
  767. return common.Contains(protocol.SupportedServerEntrySources, value)
  768. }
  769. var isISO8601DateRegex = regexp.MustCompile(
  770. "(?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})))")
  771. func isISO8601Date(_ *SupportServices, value string) bool {
  772. return isISO8601DateRegex.Match([]byte(value))
  773. }
  774. func isLastConnected(support *SupportServices, value string) bool {
  775. return value == "None" || value == "Unknown" || isISO8601Date(support, value)
  776. }