api.go 33 KB

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