api.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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", isAnyString, 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. // TODO: without validation, any valid JSON will be logged
  488. // by getRequestLogFields, even if the parameter user validates
  489. // and rejects the parameter.
  490. default:
  491. err = validateStringRequestParam(config, expectedParam, value)
  492. }
  493. if err != nil {
  494. return common.ContextError(err)
  495. }
  496. }
  497. return nil
  498. }
  499. // copyBaseRequestParams makes a copy of the params which
  500. // includes only the baseRequestParams.
  501. func copyBaseRequestParams(params common.APIParameters) common.APIParameters {
  502. // Note: not a deep copy; assumes baseRequestParams values
  503. // are all scalar types (int, string, etc.)
  504. paramsCopy := make(common.APIParameters)
  505. for _, baseParam := range baseRequestParams {
  506. value := params[baseParam.name]
  507. if value == nil {
  508. continue
  509. }
  510. paramsCopy[baseParam.name] = value
  511. }
  512. return paramsCopy
  513. }
  514. func validateStringRequestParam(
  515. config *Config,
  516. expectedParam requestParamSpec,
  517. value interface{}) error {
  518. strValue, ok := value.(string)
  519. if !ok {
  520. return common.ContextError(
  521. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  522. }
  523. if !expectedParam.validator(config, strValue) {
  524. return common.ContextError(
  525. fmt.Errorf("invalid param: %s: %s", expectedParam.name, strValue))
  526. }
  527. return nil
  528. }
  529. func validateStringArrayRequestParam(
  530. config *Config,
  531. expectedParam requestParamSpec,
  532. value interface{}) error {
  533. arrayValue, ok := value.([]interface{})
  534. if !ok {
  535. return common.ContextError(
  536. fmt.Errorf("unexpected string param type: %s", expectedParam.name))
  537. }
  538. for _, value := range arrayValue {
  539. err := validateStringRequestParam(config, expectedParam, value)
  540. if err != nil {
  541. return common.ContextError(err)
  542. }
  543. }
  544. return nil
  545. }
  546. // getRequestLogFields makes LogFields to log the API event following
  547. // the legacy psi_web and current ELK naming conventions.
  548. func getRequestLogFields(
  549. eventName string,
  550. geoIPData GeoIPData,
  551. authorizedAccessTypes []string,
  552. params common.APIParameters,
  553. expectedParams []requestParamSpec) LogFields {
  554. logFields := make(LogFields)
  555. if eventName != "" {
  556. logFields["event_name"] = eventName
  557. }
  558. // In psi_web, the space replacement was done to accommodate space
  559. // delimited logging, which is no longer required; we retain the
  560. // transformation so that stats aggregation isn't impacted.
  561. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  562. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  563. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  564. if len(authorizedAccessTypes) > 0 {
  565. logFields["authorized_access_types"] = authorizedAccessTypes
  566. }
  567. if params == nil {
  568. return logFields
  569. }
  570. for _, expectedParam := range expectedParams {
  571. if expectedParam.flags&requestParamNotLogged != 0 {
  572. continue
  573. }
  574. value := params[expectedParam.name]
  575. if value == nil {
  576. // Special case: older clients don't send this value,
  577. // so log a default.
  578. if expectedParam.name == "tunnel_whole_device" {
  579. value = "0"
  580. } else {
  581. // Skip omitted, optional params
  582. continue
  583. }
  584. }
  585. switch v := value.(type) {
  586. case string:
  587. strValue := v
  588. // Special cases:
  589. // - Number fields are encoded as integer types.
  590. // - For ELK performance we record certain domain-or-IP
  591. // fields as one of two different values based on type;
  592. // we also omit port from these host:port fields for now.
  593. // - Boolean fields that come into the api as "1"/"0"
  594. // must be logged as actual boolean values
  595. switch expectedParam.name {
  596. case "client_version", "establishment_duration":
  597. intValue, _ := strconv.Atoi(strValue)
  598. logFields[expectedParam.name] = intValue
  599. case "meek_dial_address":
  600. host, _, _ := net.SplitHostPort(strValue)
  601. if isIPAddress(nil, host) {
  602. logFields["meek_dial_ip_address"] = host
  603. } else {
  604. logFields["meek_dial_domain"] = host
  605. }
  606. case "upstream_proxy_type":
  607. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  608. logFields[expectedParam.name] = strings.ToLower(strValue)
  609. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  610. // Due to a client bug, clients may deliever an incorrect ""
  611. // value for speed_test_samples via the web API protocol. Omit
  612. // the field in this case.
  613. case "tunnel_whole_device", "meek_transformed_host_name", "connected":
  614. // Submitted value could be "0" or "1"
  615. // "0" and non "0"/"1" values should be transformed to false
  616. // "1" should be transformed to true
  617. if strValue == "1" {
  618. logFields[expectedParam.name] = true
  619. } else {
  620. logFields[expectedParam.name] = false
  621. }
  622. default:
  623. logFields[expectedParam.name] = strValue
  624. }
  625. case []interface{}:
  626. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  627. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  628. } else {
  629. logFields[expectedParam.name] = v
  630. }
  631. default:
  632. logFields[expectedParam.name] = v
  633. }
  634. }
  635. return logFields
  636. }
  637. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  638. // fields to more verbose names for metrics.
  639. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  640. // TODO: use reflection and add additional tags, e.g.,
  641. // `json:"s" log:"timestamp"` to remove hard-coded
  642. // tag value dependency?
  643. logSamples := make([]interface{}, len(samples))
  644. for i, sample := range samples {
  645. logSample := make(map[string]interface{})
  646. if m, ok := sample.(map[string]interface{}); ok {
  647. for k, v := range m {
  648. logK := k
  649. switch k {
  650. case "s":
  651. logK = "timestamp"
  652. case "r":
  653. logK = "server_region"
  654. case "p":
  655. logK = "relay_protocol"
  656. case "t":
  657. logK = "round_trip_time_ms"
  658. case "u":
  659. logK = "bytes_up"
  660. case "d":
  661. logK = "bytes_down"
  662. }
  663. logSample[logK] = v
  664. }
  665. }
  666. logSamples[i] = logSample
  667. }
  668. return logSamples
  669. }
  670. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  671. if params[name] == nil {
  672. return "", common.ContextError(fmt.Errorf("missing param: %s", name))
  673. }
  674. value, ok := params[name].(string)
  675. if !ok {
  676. return "", common.ContextError(fmt.Errorf("invalid param: %s", name))
  677. }
  678. return value, nil
  679. }
  680. func getInt64RequestParam(params common.APIParameters, name string) (int64, error) {
  681. if params[name] == nil {
  682. return 0, common.ContextError(fmt.Errorf("missing param: %s", name))
  683. }
  684. value, ok := params[name].(float64)
  685. if !ok {
  686. return 0, common.ContextError(fmt.Errorf("invalid param: %s", name))
  687. }
  688. return int64(value), nil
  689. }
  690. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  691. if params[name] == nil {
  692. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  693. }
  694. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  695. value, ok := params[name].(map[string]interface{})
  696. if !ok {
  697. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  698. }
  699. return common.APIParameters(value), nil
  700. }
  701. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  702. if params[name] == nil {
  703. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  704. }
  705. value, ok := params[name].([]interface{})
  706. if !ok {
  707. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  708. }
  709. result := make([]common.APIParameters, len(value))
  710. for i, item := range value {
  711. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  712. resultItem, ok := item.(map[string]interface{})
  713. if !ok {
  714. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  715. }
  716. result[i] = common.APIParameters(resultItem)
  717. }
  718. return result, nil
  719. }
  720. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  721. if params[name] == nil {
  722. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  723. }
  724. // TODO: can't use common.APIParameters type?
  725. value, ok := params[name].(map[string]interface{})
  726. if !ok {
  727. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  728. }
  729. result := make(map[string]int64)
  730. for k, v := range value {
  731. numValue, ok := v.(float64)
  732. if !ok {
  733. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  734. }
  735. result[k] = int64(numValue)
  736. }
  737. return result, nil
  738. }
  739. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  740. if params[name] == nil {
  741. return nil, common.ContextError(fmt.Errorf("missing param: %s", name))
  742. }
  743. value, ok := params[name].([]interface{})
  744. if !ok {
  745. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  746. }
  747. result := make([]string, len(value))
  748. for i, v := range value {
  749. strValue, ok := v.(string)
  750. if !ok {
  751. return nil, common.ContextError(fmt.Errorf("invalid param: %s", name))
  752. }
  753. result[i] = strValue
  754. }
  755. return result, nil
  756. }
  757. // Normalize reported client platform. Android clients, for example, report
  758. // OS version, rooted status, and Google Play build status in the clientPlatform
  759. // string along with "Android".
  760. func normalizeClientPlatform(clientPlatform string) string {
  761. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  762. return CLIENT_PLATFORM_ANDROID
  763. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  764. return CLIENT_PLATFORM_IOS
  765. }
  766. return CLIENT_PLATFORM_WINDOWS
  767. }
  768. func isAnyString(config *Config, value string) bool {
  769. return true
  770. }
  771. func isMobileClientPlatform(clientPlatform string) bool {
  772. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  773. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  774. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  775. }
  776. // Input validators follow the legacy validations rules in psi_web.
  777. func isServerSecret(config *Config, value string) bool {
  778. return subtle.ConstantTimeCompare(
  779. []byte(value),
  780. []byte(config.WebServerSecret)) == 1
  781. }
  782. func isHexDigits(_ *Config, value string) bool {
  783. // Allows both uppercase in addition to lowercase, for legacy support.
  784. return -1 == strings.IndexFunc(value, func(c rune) bool {
  785. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  786. })
  787. }
  788. func isDigits(_ *Config, value string) bool {
  789. return -1 == strings.IndexFunc(value, func(c rune) bool {
  790. return c < '0' || c > '9'
  791. })
  792. }
  793. func isIntString(_ *Config, value string) bool {
  794. _, err := strconv.Atoi(value)
  795. return err == nil
  796. }
  797. func isClientPlatform(_ *Config, value string) bool {
  798. return -1 == strings.IndexFunc(value, func(c rune) bool {
  799. // Note: stricter than psi_web's Python string.whitespace
  800. return unicode.Is(unicode.White_Space, c)
  801. })
  802. }
  803. func isRelayProtocol(_ *Config, value string) bool {
  804. return common.Contains(protocol.SupportedTunnelProtocols, value)
  805. }
  806. func isBooleanFlag(_ *Config, value string) bool {
  807. return value == "0" || value == "1"
  808. }
  809. func isUpstreamProxyType(_ *Config, value string) bool {
  810. value = strings.ToLower(value)
  811. return value == "http" || value == "socks5" || value == "socks4a"
  812. }
  813. func isRegionCode(_ *Config, value string) bool {
  814. if len(value) != 2 {
  815. return false
  816. }
  817. return -1 == strings.IndexFunc(value, func(c rune) bool {
  818. return c < 'A' || c > 'Z'
  819. })
  820. }
  821. func isDialAddress(_ *Config, value string) bool {
  822. // "<host>:<port>", where <host> is a domain or IP address
  823. parts := strings.Split(value, ":")
  824. if len(parts) != 2 {
  825. return false
  826. }
  827. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  828. return false
  829. }
  830. if !isDigits(nil, parts[1]) {
  831. return false
  832. }
  833. port, err := strconv.Atoi(parts[1])
  834. if err != nil {
  835. return false
  836. }
  837. return port > 0 && port < 65536
  838. }
  839. func isIPAddress(_ *Config, value string) bool {
  840. return net.ParseIP(value) != nil
  841. }
  842. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  843. func isDomain(_ *Config, value string) bool {
  844. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  845. //
  846. // "ensures that each segment
  847. // * contains at least one character and a maximum of 63 characters
  848. // * consists only of allowed characters
  849. // * doesn't begin or end with a hyphen"
  850. //
  851. if len(value) > 255 {
  852. return false
  853. }
  854. value = strings.TrimSuffix(value, ".")
  855. for _, part := range strings.Split(value, ".") {
  856. // Note: regexp doesn't support the following Perl expression which
  857. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  858. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  859. return false
  860. }
  861. if !isDomainRegex.Match([]byte(part)) {
  862. return false
  863. }
  864. }
  865. return true
  866. }
  867. func isHostHeader(_ *Config, value string) bool {
  868. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  869. if strings.Contains(value, ":") {
  870. return isDialAddress(nil, value)
  871. }
  872. return isIPAddress(nil, value) || isDomain(nil, value)
  873. }
  874. func isServerEntrySource(_ *Config, value string) bool {
  875. return common.Contains(protocol.SupportedServerEntrySources, value)
  876. }
  877. var isISO8601DateRegex = regexp.MustCompile(
  878. "(?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})))")
  879. func isISO8601Date(_ *Config, value string) bool {
  880. return isISO8601DateRegex.Match([]byte(value))
  881. }
  882. func isLastConnected(_ *Config, value string) bool {
  883. return value == "None" || value == "Unknown" || isISO8601Date(nil, value)
  884. }