api.go 31 KB

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