api.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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/base64"
  23. "encoding/json"
  24. std_errors "errors"
  25. "net"
  26. "regexp"
  27. "runtime/debug"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  37. )
  38. const (
  39. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  40. PADDING_MAX_BYTES = 16 * 1024
  41. CLIENT_PLATFORM_ANDROID = "Android"
  42. CLIENT_PLATFORM_WINDOWS = "Windows"
  43. CLIENT_PLATFORM_IOS = "iOS"
  44. )
  45. // sshAPIRequestHandler routes Psiphon API requests transported as
  46. // JSON objects via the SSH request mechanism.
  47. //
  48. // The API request handlers, handshakeAPIRequestHandler, etc., are
  49. // reused by webServer which offers the Psiphon API via web transport.
  50. //
  51. // The API request parameters and event log values follow the legacy
  52. // psi_web protocol and naming conventions. The API is compatible with
  53. // all tunnel-core clients but are not backwards compatible with all
  54. // legacy clients.
  55. //
  56. func sshAPIRequestHandler(
  57. support *SupportServices,
  58. geoIPData GeoIPData,
  59. authorizedAccessTypes []string,
  60. name string,
  61. requestPayload []byte) ([]byte, error) {
  62. // Notes:
  63. //
  64. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  65. // by max SSH request packet size.
  66. //
  67. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  68. // array of base64-encoded strings; the base64 representation should
  69. // not be decoded to []byte values. The default behavior of
  70. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  71. // type map[string]interface{} will unmarshal a base64-encoded string
  72. // to a string, not a decoded []byte, as required.
  73. var params common.APIParameters
  74. err := json.Unmarshal(requestPayload, &params)
  75. if err != nil {
  76. return nil, errors.Tracef(
  77. "invalid payload for request name: %s: %s", name, err)
  78. }
  79. return dispatchAPIRequestHandler(
  80. support,
  81. protocol.PSIPHON_SSH_API_PROTOCOL,
  82. geoIPData,
  83. authorizedAccessTypes,
  84. name,
  85. params)
  86. }
  87. // dispatchAPIRequestHandler is the common dispatch point for both
  88. // web and SSH API requests.
  89. func dispatchAPIRequestHandler(
  90. support *SupportServices,
  91. apiProtocol string,
  92. geoIPData GeoIPData,
  93. authorizedAccessTypes []string,
  94. name string,
  95. params common.APIParameters) (response []byte, reterr error) {
  96. // Recover from and log any unexpected panics caused by user input
  97. // handling bugs. User inputs should be properly validated; this
  98. // mechanism is only a last resort to prevent the process from
  99. // terminating in the case of a bug.
  100. defer func() {
  101. if e := recover(); e != nil {
  102. if intentionalPanic, ok := e.(IntentionalPanicError); ok {
  103. panic(intentionalPanic)
  104. } else {
  105. log.LogPanicRecover(e, debug.Stack())
  106. reterr = errors.TraceNew("request handler panic")
  107. }
  108. }
  109. }()
  110. // Before invoking the handlers, enforce some preconditions:
  111. //
  112. // - A handshake request must precede any other requests.
  113. // - When the handshake results in a traffic rules state where
  114. // the client is immediately exhausted, no requests
  115. // may succeed. This case ensures that blocked clients do
  116. // not log "connected", etc.
  117. //
  118. // Only one handshake request may be made. There is no check here
  119. // to enforce that handshakeAPIRequestHandler will be called at
  120. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  121. // enforces that only a single handshake is made; enforcing that there
  122. // ensures no race condition even if concurrent requests are
  123. // in flight.
  124. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  125. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  126. // applies here.
  127. sessionID, err := getStringRequestParam(params, "client_session_id")
  128. if err == nil {
  129. // Note: follows/duplicates baseParams validation
  130. if !isHexDigits(support.Config, sessionID) {
  131. err = std_errors.New("invalid param: client_session_id")
  132. }
  133. }
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. completed, exhausted, err := support.TunnelServer.GetClientHandshaked(sessionID)
  138. if err != nil {
  139. return nil, errors.Trace(err)
  140. }
  141. if !completed {
  142. return nil, errors.TraceNew("handshake not completed")
  143. }
  144. if exhausted {
  145. return nil, errors.TraceNew("exhausted after handshake")
  146. }
  147. }
  148. switch name {
  149. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  150. return handshakeAPIRequestHandler(support, apiProtocol, geoIPData, params)
  151. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  152. return connectedAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  153. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  154. return statusAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  155. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  156. return clientVerificationAPIRequestHandler(support, geoIPData, authorizedAccessTypes, params)
  157. }
  158. return nil, errors.Tracef("invalid request name: %s", name)
  159. }
  160. var handshakeRequestParams = append(
  161. append(
  162. append(
  163. []requestParamSpec{
  164. // Legacy clients may not send "session_id" in handshake
  165. {"session_id", isHexDigits, requestParamOptional},
  166. {"missing_server_entry_signature", isBase64String, requestParamOptional}},
  167. baseParams...),
  168. baseDialParams...),
  169. tacticsParams...)
  170. // handshakeAPIRequestHandler implements the "handshake" API request.
  171. // Clients make the handshake immediately after establishing a tunnel
  172. // connection; the response tells the client what homepage to open, what
  173. // stats to record, etc.
  174. func handshakeAPIRequestHandler(
  175. support *SupportServices,
  176. apiProtocol string,
  177. geoIPData GeoIPData,
  178. params common.APIParameters) ([]byte, error) {
  179. // Note: ignoring legacy "known_servers" params
  180. err := validateRequestParams(support.Config, params, handshakeRequestParams)
  181. if err != nil {
  182. return nil, errors.Trace(err)
  183. }
  184. sessionID, _ := getStringRequestParam(params, "client_session_id")
  185. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  186. clientVersion, _ := getStringRequestParam(params, "client_version")
  187. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  188. isMobile := isMobileClientPlatform(clientPlatform)
  189. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  190. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  191. // the client, a value of 0 will be used.
  192. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  193. var authorizations []string
  194. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  195. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  196. if err != nil {
  197. return nil, errors.Trace(err)
  198. }
  199. }
  200. // Note: no guarantee that PsinetDatabase won't reload between database calls
  201. db := support.PsinetDatabase
  202. httpsRequestRegexes := db.GetHttpsRequestRegexes(sponsorID)
  203. // Flag the SSH client as having completed its handshake. This
  204. // may reselect traffic rules and starts allowing port forwards.
  205. // TODO: in the case of SSH API requests, the actual sshClient could
  206. // be passed in and used here. The session ID lookup is only strictly
  207. // necessary to support web API requests.
  208. handshakeStateInfo, err := support.TunnelServer.SetClientHandshakeState(
  209. sessionID,
  210. handshakeState{
  211. completed: true,
  212. apiProtocol: apiProtocol,
  213. apiParams: copyBaseSessionAndDialParams(params),
  214. expectDomainBytes: len(httpsRequestRegexes) > 0,
  215. establishedTunnelsCount: establishedTunnelsCount,
  216. },
  217. authorizations)
  218. if err != nil {
  219. return nil, errors.Trace(err)
  220. }
  221. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  222. common.GeoIPData(geoIPData), params)
  223. if err != nil {
  224. return nil, errors.Trace(err)
  225. }
  226. var marshaledTacticsPayload []byte
  227. if tacticsPayload != nil {
  228. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  229. if err != nil {
  230. return nil, errors.Trace(err)
  231. }
  232. // Log a metric when new tactics are issued. Logging here indicates that
  233. // the handshake tactics mechanism is active; but logging for every
  234. // handshake creates unneccesary log data.
  235. if len(tacticsPayload.Tactics) > 0 {
  236. logFields := getRequestLogFields(
  237. tactics.TACTICS_METRIC_EVENT_NAME,
  238. geoIPData,
  239. handshakeStateInfo.authorizedAccessTypes,
  240. params,
  241. handshakeRequestParams)
  242. logFields[tactics.NEW_TACTICS_TAG_LOG_FIELD_NAME] = tacticsPayload.Tag
  243. logFields[tactics.IS_TACTICS_REQUEST_LOG_FIELD_NAME] = false
  244. log.LogRawFieldsWithTimestamp(logFields)
  245. }
  246. }
  247. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  248. // the state change (for example, if a second handshake is performed)
  249. //
  250. // The handshake event is no longer shipped to log consumers, so this is
  251. // simply a diagnostic log. Since the "server_tunnel" event includes all
  252. // common API parameters and "handshake_completed" flag, this handshake
  253. // log is mostly redundant and set to debug level.
  254. log.WithTraceFields(
  255. getRequestLogFields(
  256. "",
  257. geoIPData,
  258. handshakeStateInfo.authorizedAccessTypes,
  259. params,
  260. handshakeRequestParams)).Debug("handshake")
  261. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  262. encodedServerList := db.DiscoverServers(geoIPData.DiscoveryValue)
  263. // When the client indicates that it used an unsigned server entry for this
  264. // connection, return a signed copy of the server entry for the client to
  265. // upgrade to. See also: comment in psiphon.doHandshakeRequest.
  266. //
  267. // The missing_server_entry_signature parameter value is a server entry tag,
  268. // which is used to select the correct server entry for servers with multiple
  269. // entries. Identifying the server entries tags instead of server IPs prevents
  270. // an enumeration attack, where a malicious client can abuse this facilty to
  271. // check if an arbitrary IP address is a Psiphon server.
  272. serverEntryTag, ok := getOptionalStringRequestParam(
  273. params, "missing_server_entry_signature")
  274. if ok {
  275. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  276. if ok {
  277. encodedServerList = append(encodedServerList, ownServerEntry)
  278. }
  279. }
  280. handshakeResponse := protocol.HandshakeResponse{
  281. SSHSessionID: sessionID,
  282. Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, geoIPData.ASN, isMobile),
  283. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  284. PageViewRegexes: make([]map[string]string, 0),
  285. HttpsRequestRegexes: httpsRequestRegexes,
  286. EncodedServerList: encodedServerList,
  287. ClientRegion: geoIPData.Country,
  288. ServerTimestamp: common.GetCurrentTimestamp(),
  289. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  290. TacticsPayload: marshaledTacticsPayload,
  291. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  292. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  293. Padding: strings.Repeat(" ", pad_response),
  294. }
  295. responsePayload, err := json.Marshal(handshakeResponse)
  296. if err != nil {
  297. return nil, errors.Trace(err)
  298. }
  299. return responsePayload, nil
  300. }
  301. // uniqueUserParams are the connected request parameters which are logged for
  302. // unique_user events.
  303. var uniqueUserParams = append(
  304. []requestParamSpec{
  305. {"last_connected", isLastConnected, 0}},
  306. baseSessionParams...)
  307. var connectedRequestParams = append(
  308. []requestParamSpec{
  309. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  310. uniqueUserParams...)
  311. // updateOnConnectedParamNames are connected request parameters which are
  312. // copied to update data logged with server_tunnel: these fields either only
  313. // ship with or ship newer data with connected requests.
  314. var updateOnConnectedParamNames = append(
  315. []string{
  316. "last_connected",
  317. "establishment_duration",
  318. },
  319. fragmentor.GetUpstreamMetricsNames()...)
  320. // connectedAPIRequestHandler implements the "connected" API request. Clients
  321. // make the connected request once a tunnel connection has been established
  322. // and at least once per 24h for long-running tunnels. The last_connected
  323. // input value, which should be a connected_timestamp output from a previous
  324. // connected response, is used to calculate unique user stats.
  325. // connected_timestamp is truncated as a privacy measure.
  326. func connectedAPIRequestHandler(
  327. support *SupportServices,
  328. geoIPData GeoIPData,
  329. authorizedAccessTypes []string,
  330. params common.APIParameters) ([]byte, error) {
  331. err := validateRequestParams(support.Config, params, connectedRequestParams)
  332. if err != nil {
  333. return nil, errors.Trace(err)
  334. }
  335. sessionID, _ := getStringRequestParam(params, "client_session_id")
  336. lastConnected, _ := getStringRequestParam(params, "last_connected")
  337. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  338. // client may have performed more upstream fragmentation since the previous
  339. // metrics reported by the handshake request. Also, additional fields that
  340. // are reported only in the connected request are added to server_tunnel
  341. // here.
  342. // TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
  343. // applies here.
  344. err = support.TunnelServer.UpdateClientAPIParameters(
  345. sessionID, copyUpdateOnConnectedParams(params))
  346. if err != nil {
  347. return nil, errors.Trace(err)
  348. }
  349. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  350. // The finest required granularity for unique users is daily. To save space,
  351. // only record a "unique_user" log event when the client's last_connected is
  352. // in the previous day relative to the new connected_timestamp.
  353. logUniqueUser := false
  354. if lastConnected == "None" {
  355. logUniqueUser = true
  356. } else {
  357. t1, _ := time.Parse(time.RFC3339, lastConnected)
  358. year, month, day := t1.Date()
  359. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  360. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  361. year, month, day = t2.Date()
  362. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  363. if t1.Before(t2) && d1 != d2 {
  364. logUniqueUser = true
  365. }
  366. }
  367. if logUniqueUser {
  368. log.LogRawFieldsWithTimestamp(
  369. getRequestLogFields(
  370. "unique_user",
  371. geoIPData,
  372. authorizedAccessTypes,
  373. params,
  374. uniqueUserParams))
  375. }
  376. // TODO: retire the legacy "connected" log event
  377. log.LogRawFieldsWithTimestamp(
  378. getRequestLogFields(
  379. "connected",
  380. geoIPData,
  381. authorizedAccessTypes,
  382. params,
  383. connectedRequestParams))
  384. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  385. connectedResponse := protocol.ConnectedResponse{
  386. ConnectedTimestamp: connectedTimestamp,
  387. Padding: strings.Repeat(" ", pad_response),
  388. }
  389. responsePayload, err := json.Marshal(connectedResponse)
  390. if err != nil {
  391. return nil, errors.Trace(err)
  392. }
  393. return responsePayload, nil
  394. }
  395. var statusRequestParams = baseSessionParams
  396. var remoteServerListStatParams = append(
  397. []requestParamSpec{
  398. {"client_download_timestamp", isISO8601Date, 0},
  399. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  400. {"url", isAnyString, 0},
  401. {"etag", isAnyString, 0},
  402. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  403. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  404. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool}},
  405. baseSessionParams...)
  406. // Backwards compatibility case: legacy clients do not include these fields in
  407. // the remote_server_list_stats entries. Use the values from the outer status
  408. // request as an approximation (these values reflect the client at persistent
  409. // stat shipping time, which may differ from the client at persistent stat
  410. // recording time). Note that all but client_build_rev and device_region are
  411. // required fields.
  412. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  413. "session_id",
  414. "propagation_channel_id",
  415. "sponsor_id",
  416. "client_version",
  417. "client_platform",
  418. "client_build_rev",
  419. "device_region",
  420. }
  421. var failedTunnelStatParams = append(
  422. []requestParamSpec{
  423. {"server_entry_tag", isAnyString, requestParamOptional},
  424. {"session_id", isHexDigits, 0},
  425. {"last_connected", isLastConnected, 0},
  426. {"client_failed_timestamp", isISO8601Date, 0},
  427. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  428. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  429. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  430. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  431. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  432. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  433. {"tunnel_error", isAnyString, 0}},
  434. baseSessionAndDialParams...)
  435. // statusAPIRequestHandler implements the "status" API request.
  436. // Clients make periodic status requests which deliver client-side
  437. // recorded data transfer and tunnel duration stats.
  438. // Note from psi_web implementation: no input validation on domains;
  439. // any string is accepted (regex transform may result in arbitrary
  440. // string). Stats processor must handle this input with care.
  441. func statusAPIRequestHandler(
  442. support *SupportServices,
  443. geoIPData GeoIPData,
  444. authorizedAccessTypes []string,
  445. params common.APIParameters) ([]byte, error) {
  446. err := validateRequestParams(support.Config, params, statusRequestParams)
  447. if err != nil {
  448. return nil, errors.Trace(err)
  449. }
  450. sessionID, _ := getStringRequestParam(params, "client_session_id")
  451. statusData, err := getJSONObjectRequestParam(params, "statusData")
  452. if err != nil {
  453. return nil, errors.Trace(err)
  454. }
  455. // Logs are queued until the input is fully validated. Otherwise, stats
  456. // could be double counted if the client has a bug in its request
  457. // formatting: partial stats would be logged (counted), the request would
  458. // fail, and clients would then resend all the same stats again.
  459. logQueue := make([]LogFields, 0)
  460. // Domain bytes transferred stats
  461. // Older clients may not submit this data
  462. // Clients are expected to send host_bytes/domain_bytes stats only when
  463. // configured to do so in the handshake reponse. Legacy clients may still
  464. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  465. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  466. if err != nil {
  467. return nil, errors.Trace(err)
  468. }
  469. if domainBytesExpected && statusData["host_bytes"] != nil {
  470. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  471. if err != nil {
  472. return nil, errors.Trace(err)
  473. }
  474. for domain, bytes := range hostBytes {
  475. domainBytesFields := getRequestLogFields(
  476. "domain_bytes",
  477. geoIPData,
  478. authorizedAccessTypes,
  479. params,
  480. statusRequestParams)
  481. domainBytesFields["domain"] = domain
  482. domainBytesFields["bytes"] = bytes
  483. logQueue = append(logQueue, domainBytesFields)
  484. }
  485. }
  486. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  487. // not time-of-recording.
  488. // Remote server list download persistent stats.
  489. // Older clients may not submit this data.
  490. if statusData["remote_server_list_stats"] != nil {
  491. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  492. if err != nil {
  493. return nil, errors.Trace(err)
  494. }
  495. for _, remoteServerListStat := range remoteServerListStats {
  496. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  497. if _, ok := remoteServerListStat[name]; !ok {
  498. if field, ok := params[name]; ok {
  499. remoteServerListStat[name] = field
  500. }
  501. }
  502. }
  503. // For validation, copy expected fields from the outer
  504. // statusRequestParams.
  505. remoteServerListStat["server_secret"] = params["server_secret"]
  506. remoteServerListStat["client_session_id"] = params["client_session_id"]
  507. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  508. if err != nil {
  509. // Occasionally, clients may send corrupt persistent stat data. Do not
  510. // fail the status request, as this will lead to endless retries.
  511. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  512. continue
  513. }
  514. remoteServerListFields := getRequestLogFields(
  515. "remote_server_list",
  516. geoIPData,
  517. authorizedAccessTypes,
  518. remoteServerListStat,
  519. remoteServerListStatParams)
  520. logQueue = append(logQueue, remoteServerListFields)
  521. }
  522. }
  523. // Failed tunnel persistent stats.
  524. // Older clients may not submit this data.
  525. var invalidServerEntryTags map[string]bool
  526. if statusData["failed_tunnel_stats"] != nil {
  527. // Note: no guarantee that PsinetDatabase won't reload between database calls
  528. db := support.PsinetDatabase
  529. invalidServerEntryTags = make(map[string]bool)
  530. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  531. if err != nil {
  532. return nil, errors.Trace(err)
  533. }
  534. for _, failedTunnelStat := range failedTunnelStats {
  535. // failed_tunnel supplies a full set of base params, but the server secret
  536. // must use the correct value from the outer statusRequestParams.
  537. failedTunnelStat["server_secret"] = params["server_secret"]
  538. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  539. if err != nil {
  540. // Occasionally, clients may send corrupt persistent stat data. Do not
  541. // fail the status request, as this will lead to endless retries.
  542. //
  543. // TODO: trigger pruning if the data corruption indicates corrupt server
  544. // entry storage?
  545. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  546. continue
  547. }
  548. failedTunnelFields := getRequestLogFields(
  549. "failed_tunnel",
  550. geoIPData,
  551. authorizedAccessTypes,
  552. failedTunnelStat,
  553. failedTunnelStatParams)
  554. // Return a list of servers, identified by server entry tag, that are
  555. // invalid and presumed to be deleted. This information is used by clients
  556. // to prune deleted servers from their local datastores and stop attempting
  557. // connections to servers that no longer exist.
  558. //
  559. // This mechanism uses tags instead of server IPs: (a) to prevent an
  560. // enumeration attack, where a malicious client can query the entire IPv4
  561. // range and build a map of the Psiphon network; (b) to deal with recyling
  562. // cases where a server deleted and its IP is reused for a new server with
  563. // a distinct server entry.
  564. //
  565. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  566. // before returning a negative result, to mitigate accidental pruning.
  567. //
  568. // In addition, when the reported dial port number is 0, flag the server
  569. // entry as invalid to trigger client pruning. This covers a class of
  570. // invalid/semi-functional server entries, found in practice to be stored
  571. // by clients, where some protocol port number has been omitted -- due to
  572. // historical bugs in various server entry handling implementations. When
  573. // missing from a server entry loaded by a client, the port number
  574. // evaluates to 0, the zero value, which is not a valid port number even if
  575. // were not missing.
  576. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  577. if ok {
  578. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  579. if serverEntryValid {
  580. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  581. if err == nil && dialPortNumber == 0 {
  582. serverEntryValid = false
  583. }
  584. }
  585. if !serverEntryValid {
  586. invalidServerEntryTags[serverEntryTag] = true
  587. }
  588. // Add a field to the failed_tunnel log indicating if the server entry is
  589. // valid.
  590. failedTunnelFields["server_entry_valid"] = serverEntryValid
  591. }
  592. // Log failed_tunnel.
  593. logQueue = append(logQueue, failedTunnelFields)
  594. }
  595. }
  596. for _, logItem := range logQueue {
  597. log.LogRawFieldsWithTimestamp(logItem)
  598. }
  599. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  600. statusResponse := protocol.StatusResponse{
  601. Padding: strings.Repeat(" ", pad_response),
  602. }
  603. if len(invalidServerEntryTags) > 0 {
  604. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  605. i := 0
  606. for tag := range invalidServerEntryTags {
  607. statusResponse.InvalidServerEntryTags[i] = tag
  608. i++
  609. }
  610. }
  611. responsePayload, err := json.Marshal(statusResponse)
  612. if err != nil {
  613. return nil, errors.Trace(err)
  614. }
  615. return responsePayload, nil
  616. }
  617. // clientVerificationAPIRequestHandler is just a compliance stub
  618. // for older Android clients that still send verification requests
  619. func clientVerificationAPIRequestHandler(
  620. support *SupportServices,
  621. geoIPData GeoIPData,
  622. authorizedAccessTypes []string,
  623. params common.APIParameters) ([]byte, error) {
  624. return make([]byte, 0), nil
  625. }
  626. var tacticsParams = []requestParamSpec{
  627. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  628. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  629. }
  630. var tacticsRequestParams = append(
  631. append([]requestParamSpec(nil), tacticsParams...),
  632. baseSessionAndDialParams...)
  633. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  634. return func(params common.APIParameters) error {
  635. return validateRequestParams(config, params, tacticsRequestParams)
  636. }
  637. }
  638. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  639. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  640. logFields := getRequestLogFields(
  641. tactics.TACTICS_METRIC_EVENT_NAME,
  642. GeoIPData(geoIPData),
  643. nil, // authorizedAccessTypes are not known yet
  644. params,
  645. tacticsRequestParams)
  646. return common.LogFields(logFields)
  647. }
  648. }
  649. // requestParamSpec defines a request parameter. Each param is expected to be
  650. // a string, unless requestParamArray is specified, in which case an array of
  651. // strings is expected.
  652. type requestParamSpec struct {
  653. name string
  654. validator func(*Config, string) bool
  655. flags uint32
  656. }
  657. const (
  658. requestParamOptional = 1
  659. requestParamNotLogged = 1 << 1
  660. requestParamArray = 1 << 2
  661. requestParamJSON = 1 << 3
  662. requestParamLogStringAsInt = 1 << 4
  663. requestParamLogStringAsFloat = 1 << 5
  664. requestParamLogStringLengthAsInt = 1 << 6
  665. requestParamLogFlagAsBool = 1 << 7
  666. requestParamLogOnlyForFrontedMeek = 1 << 8
  667. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  668. )
  669. // baseParams are the basic request parameters that are expected for all API
  670. // requests and log events.
  671. var baseParams = []requestParamSpec{
  672. {"server_secret", isServerSecret, requestParamNotLogged},
  673. {"client_session_id", isHexDigits, requestParamNotLogged},
  674. {"propagation_channel_id", isHexDigits, 0},
  675. {"sponsor_id", isHexDigits, 0},
  676. {"client_version", isIntString, requestParamLogStringAsInt},
  677. {"client_platform", isClientPlatform, 0},
  678. {"client_build_rev", isHexDigits, requestParamOptional},
  679. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  680. {"device_region", isAnyString, requestParamOptional},
  681. }
  682. // baseSessionParams adds to baseParams the required session_id parameter. For
  683. // all requests except handshake, all existing clients are expected to send
  684. // session_id. Legacy clients may not send "session_id" in handshake.
  685. var baseSessionParams = append(
  686. []requestParamSpec{
  687. {"session_id", isHexDigits, 0}},
  688. baseParams...)
  689. // baseDialParams are the dial parameters, per-tunnel network protocol and
  690. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  691. // tactics.
  692. var baseDialParams = []requestParamSpec{
  693. {"relay_protocol", isRelayProtocol, 0},
  694. {"ssh_client_version", isAnyString, requestParamOptional},
  695. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  696. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  697. {"fronting_provider_id", isAnyString, requestParamOptional},
  698. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  699. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  700. {"meek_sni_server_name", isDomain, requestParamOptional},
  701. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  702. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  703. {"user_agent", isAnyString, requestParamOptional},
  704. {"tls_profile", isAnyString, requestParamOptional},
  705. {"tls_version", isAnyString, requestParamOptional},
  706. {"server_entry_region", isRegionCode, requestParamOptional},
  707. {"server_entry_source", isServerEntrySource, requestParamOptional},
  708. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  709. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  710. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  711. {"quic_version", isAnyString, requestParamOptional},
  712. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  713. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  714. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  715. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  716. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  717. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  718. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  719. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  720. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  721. {"egress_region", isRegionCode, requestParamOptional},
  722. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  723. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  724. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  725. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  726. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  727. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  728. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  729. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  730. {"client_bpf", isAnyString, requestParamOptional},
  731. {"network_type", isAnyString, requestParamOptional},
  732. }
  733. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  734. var baseSessionAndDialParams = append(
  735. append(
  736. []requestParamSpec{},
  737. baseSessionParams...),
  738. baseDialParams...)
  739. func validateRequestParams(
  740. config *Config,
  741. params common.APIParameters,
  742. expectedParams []requestParamSpec) error {
  743. for _, expectedParam := range expectedParams {
  744. value := params[expectedParam.name]
  745. if value == nil {
  746. if expectedParam.flags&requestParamOptional != 0 {
  747. continue
  748. }
  749. return errors.Tracef("missing param: %s", expectedParam.name)
  750. }
  751. var err error
  752. switch {
  753. case expectedParam.flags&requestParamArray != 0:
  754. err = validateStringArrayRequestParam(config, expectedParam, value)
  755. case expectedParam.flags&requestParamJSON != 0:
  756. // No validation: the JSON already unmarshalled; the parameter
  757. // user will validate that the JSON contains the expected
  758. // objects/data.
  759. // TODO: without validation, any valid JSON will be logged
  760. // by getRequestLogFields, even if the parameter user validates
  761. // and rejects the parameter.
  762. default:
  763. err = validateStringRequestParam(config, expectedParam, value)
  764. }
  765. if err != nil {
  766. return errors.Trace(err)
  767. }
  768. }
  769. return nil
  770. }
  771. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  772. // the baseSessionAndDialParams.
  773. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  774. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  775. // scalar types (int, string, etc.)
  776. paramsCopy := make(common.APIParameters)
  777. for _, baseParam := range baseSessionAndDialParams {
  778. value := params[baseParam.name]
  779. if value == nil {
  780. continue
  781. }
  782. paramsCopy[baseParam.name] = value
  783. }
  784. return paramsCopy
  785. }
  786. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  787. // Note: not a deep copy
  788. paramsCopy := make(common.APIParameters)
  789. for _, name := range updateOnConnectedParamNames {
  790. value := params[name]
  791. if value == nil {
  792. continue
  793. }
  794. paramsCopy[name] = value
  795. }
  796. return paramsCopy
  797. }
  798. func validateStringRequestParam(
  799. config *Config,
  800. expectedParam requestParamSpec,
  801. value interface{}) error {
  802. strValue, ok := value.(string)
  803. if !ok {
  804. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  805. }
  806. if !expectedParam.validator(config, strValue) {
  807. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  808. }
  809. return nil
  810. }
  811. func validateStringArrayRequestParam(
  812. config *Config,
  813. expectedParam requestParamSpec,
  814. value interface{}) error {
  815. arrayValue, ok := value.([]interface{})
  816. if !ok {
  817. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  818. }
  819. for _, value := range arrayValue {
  820. err := validateStringRequestParam(config, expectedParam, value)
  821. if err != nil {
  822. return errors.Trace(err)
  823. }
  824. }
  825. return nil
  826. }
  827. // getRequestLogFields makes LogFields to log the API event following
  828. // the legacy psi_web and current ELK naming conventions.
  829. func getRequestLogFields(
  830. eventName string,
  831. geoIPData GeoIPData,
  832. authorizedAccessTypes []string,
  833. params common.APIParameters,
  834. expectedParams []requestParamSpec) LogFields {
  835. logFields := make(LogFields)
  836. if eventName != "" {
  837. logFields["event_name"] = eventName
  838. }
  839. geoIPData.SetLogFields(logFields)
  840. if len(authorizedAccessTypes) > 0 {
  841. logFields["authorized_access_types"] = authorizedAccessTypes
  842. }
  843. if params == nil {
  844. return logFields
  845. }
  846. for _, expectedParam := range expectedParams {
  847. if expectedParam.flags&requestParamNotLogged != 0 {
  848. continue
  849. }
  850. var tunnelProtocol string
  851. if value, ok := params["relay_protocol"]; ok {
  852. tunnelProtocol, _ = value.(string)
  853. }
  854. if expectedParam.flags&requestParamLogOnlyForFrontedMeek != 0 &&
  855. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  856. continue
  857. }
  858. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  859. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  860. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  861. // Non-HTTP unfronted meek protocols never tranform the host header.
  862. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  863. continue
  864. }
  865. var transformedHostName string
  866. if value, ok := params["meek_transformed_host_name"]; ok {
  867. transformedHostName, _ = value.(string)
  868. }
  869. if transformedHostName != "1" {
  870. continue
  871. }
  872. }
  873. value := params[expectedParam.name]
  874. if value == nil {
  875. // Special case: older clients don't send this value,
  876. // so log a default.
  877. if expectedParam.name == "tunnel_whole_device" {
  878. value = "0"
  879. } else {
  880. // Skip omitted, optional params
  881. continue
  882. }
  883. }
  884. switch v := value.(type) {
  885. case string:
  886. strValue := v
  887. // Special cases:
  888. // - Number fields are encoded as integer types.
  889. // - For ELK performance we record certain domain-or-IP
  890. // fields as one of two different values based on type;
  891. // we also omit port from these host:port fields for now.
  892. // - Boolean fields that come into the api as "1"/"0"
  893. // must be logged as actual boolean values
  894. switch expectedParam.name {
  895. case "meek_dial_address":
  896. host, _, _ := net.SplitHostPort(strValue)
  897. if isIPAddress(nil, host) {
  898. logFields["meek_dial_ip_address"] = host
  899. } else {
  900. logFields["meek_dial_domain"] = host
  901. }
  902. case "upstream_proxy_type":
  903. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  904. logFields[expectedParam.name] = strings.ToLower(strValue)
  905. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  906. // Due to a client bug, clients may deliever an incorrect ""
  907. // value for speed_test_samples via the web API protocol. Omit
  908. // the field in this case.
  909. case "tunnel_error":
  910. // net/url.Error, returned from net/url.Parse, contains the original input
  911. // URL, which may contain PII. New clients strip this out by using
  912. // common.SafeParseURL. Legacy clients will still send the full error
  913. // message, so strip it out here. The target substring should be unique to
  914. // legacy clients.
  915. target := "upstreamproxy error: proxyURI url.Parse: parse "
  916. index := strings.Index(strValue, target)
  917. if index != -1 {
  918. strValue = strValue[:index+len(target)] + "<redacted>"
  919. }
  920. logFields[expectedParam.name] = strValue
  921. default:
  922. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  923. intValue, _ := strconv.Atoi(strValue)
  924. logFields[expectedParam.name] = intValue
  925. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  926. floatValue, _ := strconv.ParseFloat(strValue, 64)
  927. logFields[expectedParam.name] = floatValue
  928. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  929. logFields[expectedParam.name] = len(strValue)
  930. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  931. // Submitted value could be "0" or "1"
  932. // "0" and non "0"/"1" values should be transformed to false
  933. // "1" should be transformed to true
  934. if strValue == "1" {
  935. logFields[expectedParam.name] = true
  936. } else {
  937. logFields[expectedParam.name] = false
  938. }
  939. } else {
  940. logFields[expectedParam.name] = strValue
  941. }
  942. }
  943. case []interface{}:
  944. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  945. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  946. } else {
  947. logFields[expectedParam.name] = v
  948. }
  949. default:
  950. logFields[expectedParam.name] = v
  951. }
  952. }
  953. return logFields
  954. }
  955. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  956. // fields to more verbose names for metrics.
  957. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  958. // TODO: use reflection and add additional tags, e.g.,
  959. // `json:"s" log:"timestamp"` to remove hard-coded
  960. // tag value dependency?
  961. logSamples := make([]interface{}, len(samples))
  962. for i, sample := range samples {
  963. logSample := make(map[string]interface{})
  964. if m, ok := sample.(map[string]interface{}); ok {
  965. for k, v := range m {
  966. logK := k
  967. switch k {
  968. case "s":
  969. logK = "timestamp"
  970. case "r":
  971. logK = "server_region"
  972. case "p":
  973. logK = "relay_protocol"
  974. case "t":
  975. logK = "round_trip_time_ms"
  976. case "u":
  977. logK = "bytes_up"
  978. case "d":
  979. logK = "bytes_down"
  980. }
  981. logSample[logK] = v
  982. }
  983. }
  984. logSamples[i] = logSample
  985. }
  986. return logSamples
  987. }
  988. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  989. if params[name] == nil {
  990. return "", false
  991. }
  992. value, ok := params[name].(string)
  993. if !ok {
  994. return "", false
  995. }
  996. return value, true
  997. }
  998. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  999. if params[name] == nil {
  1000. return "", errors.Tracef("missing param: %s", name)
  1001. }
  1002. value, ok := params[name].(string)
  1003. if !ok {
  1004. return "", errors.Tracef("invalid param: %s", name)
  1005. }
  1006. return value, nil
  1007. }
  1008. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1009. if params[name] == nil {
  1010. return 0, errors.Tracef("missing param: %s", name)
  1011. }
  1012. valueStr, ok := params[name].(string)
  1013. if !ok {
  1014. return 0, errors.Tracef("invalid param: %s", name)
  1015. }
  1016. value, err := strconv.Atoi(valueStr)
  1017. if !ok {
  1018. return 0, errors.Trace(err)
  1019. }
  1020. return value, nil
  1021. }
  1022. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1023. value, err := getIntStringRequestParam(params, name)
  1024. if err != nil {
  1025. return 0, errors.Trace(err)
  1026. }
  1027. if value < 0 {
  1028. value = 0
  1029. }
  1030. if value > PADDING_MAX_BYTES {
  1031. value = PADDING_MAX_BYTES
  1032. }
  1033. return int(value), nil
  1034. }
  1035. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1036. if params[name] == nil {
  1037. return nil, errors.Tracef("missing param: %s", name)
  1038. }
  1039. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1040. value, ok := params[name].(map[string]interface{})
  1041. if !ok {
  1042. return nil, errors.Tracef("invalid param: %s", name)
  1043. }
  1044. return common.APIParameters(value), nil
  1045. }
  1046. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1047. if params[name] == nil {
  1048. return nil, errors.Tracef("missing param: %s", name)
  1049. }
  1050. value, ok := params[name].([]interface{})
  1051. if !ok {
  1052. return nil, errors.Tracef("invalid param: %s", name)
  1053. }
  1054. result := make([]common.APIParameters, len(value))
  1055. for i, item := range value {
  1056. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1057. resultItem, ok := item.(map[string]interface{})
  1058. if !ok {
  1059. return nil, errors.Tracef("invalid param: %s", name)
  1060. }
  1061. result[i] = common.APIParameters(resultItem)
  1062. }
  1063. return result, nil
  1064. }
  1065. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1066. if params[name] == nil {
  1067. return nil, errors.Tracef("missing param: %s", name)
  1068. }
  1069. // TODO: can't use common.APIParameters type?
  1070. value, ok := params[name].(map[string]interface{})
  1071. if !ok {
  1072. return nil, errors.Tracef("invalid param: %s", name)
  1073. }
  1074. result := make(map[string]int64)
  1075. for k, v := range value {
  1076. numValue, ok := v.(float64)
  1077. if !ok {
  1078. return nil, errors.Tracef("invalid param: %s", name)
  1079. }
  1080. result[k] = int64(numValue)
  1081. }
  1082. return result, nil
  1083. }
  1084. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1085. if params[name] == nil {
  1086. return nil, errors.Tracef("missing param: %s", name)
  1087. }
  1088. value, ok := params[name].([]interface{})
  1089. if !ok {
  1090. return nil, errors.Tracef("invalid param: %s", name)
  1091. }
  1092. result := make([]string, len(value))
  1093. for i, v := range value {
  1094. strValue, ok := v.(string)
  1095. if !ok {
  1096. return nil, errors.Tracef("invalid param: %s", name)
  1097. }
  1098. result[i] = strValue
  1099. }
  1100. return result, nil
  1101. }
  1102. // Normalize reported client platform. Android clients, for example, report
  1103. // OS version, rooted status, and Google Play build status in the clientPlatform
  1104. // string along with "Android".
  1105. func normalizeClientPlatform(clientPlatform string) string {
  1106. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1107. return CLIENT_PLATFORM_ANDROID
  1108. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1109. return CLIENT_PLATFORM_IOS
  1110. }
  1111. return CLIENT_PLATFORM_WINDOWS
  1112. }
  1113. func isAnyString(config *Config, value string) bool {
  1114. return true
  1115. }
  1116. func isMobileClientPlatform(clientPlatform string) bool {
  1117. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1118. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1119. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1120. }
  1121. // Input validators follow the legacy validations rules in psi_web.
  1122. func isServerSecret(config *Config, value string) bool {
  1123. return subtle.ConstantTimeCompare(
  1124. []byte(value),
  1125. []byte(config.WebServerSecret)) == 1
  1126. }
  1127. func isHexDigits(_ *Config, value string) bool {
  1128. // Allows both uppercase in addition to lowercase, for legacy support.
  1129. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1130. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1131. })
  1132. }
  1133. func isBase64String(_ *Config, value string) bool {
  1134. _, err := base64.StdEncoding.DecodeString(value)
  1135. return err == nil
  1136. }
  1137. func isDigits(_ *Config, value string) bool {
  1138. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1139. return c < '0' || c > '9'
  1140. })
  1141. }
  1142. func isIntString(_ *Config, value string) bool {
  1143. _, err := strconv.Atoi(value)
  1144. return err == nil
  1145. }
  1146. func isFloatString(_ *Config, value string) bool {
  1147. _, err := strconv.ParseFloat(value, 64)
  1148. return err == nil
  1149. }
  1150. func isClientPlatform(_ *Config, value string) bool {
  1151. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1152. // Note: stricter than psi_web's Python string.whitespace
  1153. return unicode.Is(unicode.White_Space, c)
  1154. })
  1155. }
  1156. func isRelayProtocol(_ *Config, value string) bool {
  1157. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1158. }
  1159. func isBooleanFlag(_ *Config, value string) bool {
  1160. return value == "0" || value == "1"
  1161. }
  1162. func isUpstreamProxyType(_ *Config, value string) bool {
  1163. value = strings.ToLower(value)
  1164. return value == "http" || value == "socks5" || value == "socks4a"
  1165. }
  1166. func isRegionCode(_ *Config, value string) bool {
  1167. if len(value) != 2 {
  1168. return false
  1169. }
  1170. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1171. return c < 'A' || c > 'Z'
  1172. })
  1173. }
  1174. func isDialAddress(_ *Config, value string) bool {
  1175. // "<host>:<port>", where <host> is a domain or IP address
  1176. parts := strings.Split(value, ":")
  1177. if len(parts) != 2 {
  1178. return false
  1179. }
  1180. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1181. return false
  1182. }
  1183. if !isDigits(nil, parts[1]) {
  1184. return false
  1185. }
  1186. _, err := strconv.Atoi(parts[1])
  1187. if err != nil {
  1188. return false
  1189. }
  1190. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1191. return true
  1192. }
  1193. func isIPAddress(_ *Config, value string) bool {
  1194. return net.ParseIP(value) != nil
  1195. }
  1196. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1197. func isDomain(_ *Config, value string) bool {
  1198. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1199. //
  1200. // "ensures that each segment
  1201. // * contains at least one character and a maximum of 63 characters
  1202. // * consists only of allowed characters
  1203. // * doesn't begin or end with a hyphen"
  1204. //
  1205. if len(value) > 255 {
  1206. return false
  1207. }
  1208. value = strings.TrimSuffix(value, ".")
  1209. for _, part := range strings.Split(value, ".") {
  1210. // Note: regexp doesn't support the following Perl expression which
  1211. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1212. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1213. return false
  1214. }
  1215. if !isDomainRegex.Match([]byte(part)) {
  1216. return false
  1217. }
  1218. }
  1219. return true
  1220. }
  1221. func isHostHeader(_ *Config, value string) bool {
  1222. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1223. if strings.Contains(value, ":") {
  1224. return isDialAddress(nil, value)
  1225. }
  1226. return isIPAddress(nil, value) || isDomain(nil, value)
  1227. }
  1228. func isServerEntrySource(_ *Config, value string) bool {
  1229. return common.Contains(protocol.SupportedServerEntrySources, value)
  1230. }
  1231. var isISO8601DateRegex = regexp.MustCompile(
  1232. `(?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})))`)
  1233. func isISO8601Date(_ *Config, value string) bool {
  1234. return isISO8601DateRegex.Match([]byte(value))
  1235. }
  1236. func isLastConnected(_ *Config, value string) bool {
  1237. return value == "None" || isISO8601Date(nil, value)
  1238. }