api.go 29 KB

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