api.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  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. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool}},
  403. baseSessionParams...)
  404. // Backwards compatibility case: legacy clients do not include these fields in
  405. // the remote_server_list_stats entries. Use the values from the outer status
  406. // request as an approximation (these values reflect the client at persistent
  407. // stat shipping time, which may differ from the client at persistent stat
  408. // recording time). Note that all but client_build_rev and device_region are
  409. // required fields.
  410. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  411. "session_id",
  412. "propagation_channel_id",
  413. "sponsor_id",
  414. "client_version",
  415. "client_platform",
  416. "client_build_rev",
  417. "device_region",
  418. }
  419. var failedTunnelStatParams = append(
  420. []requestParamSpec{
  421. {"server_entry_tag", isAnyString, requestParamOptional},
  422. {"session_id", isHexDigits, 0},
  423. {"last_connected", isLastConnected, 0},
  424. {"client_failed_timestamp", isISO8601Date, 0},
  425. {"liveness_test_upstream_bytes", isIntString, requestParamOptional},
  426. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional},
  427. {"liveness_test_downstream_bytes", isIntString, requestParamOptional},
  428. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional},
  429. {"bytes_up", isIntString, requestParamOptional},
  430. {"bytes_down", isIntString, requestParamOptional},
  431. {"tunnel_error", isAnyString, 0}},
  432. baseSessionAndDialParams...)
  433. // statusAPIRequestHandler implements the "status" API request.
  434. // Clients make periodic status requests which deliver client-side
  435. // recorded data transfer and tunnel duration stats.
  436. // Note from psi_web implementation: no input validation on domains;
  437. // any string is accepted (regex transform may result in arbitrary
  438. // string). Stats processor must handle this input with care.
  439. func statusAPIRequestHandler(
  440. support *SupportServices,
  441. geoIPData GeoIPData,
  442. authorizedAccessTypes []string,
  443. params common.APIParameters) ([]byte, error) {
  444. err := validateRequestParams(support.Config, params, statusRequestParams)
  445. if err != nil {
  446. return nil, errors.Trace(err)
  447. }
  448. sessionID, _ := getStringRequestParam(params, "client_session_id")
  449. statusData, err := getJSONObjectRequestParam(params, "statusData")
  450. if err != nil {
  451. return nil, errors.Trace(err)
  452. }
  453. // Logs are queued until the input is fully validated. Otherwise, stats
  454. // could be double counted if the client has a bug in its request
  455. // formatting: partial stats would be logged (counted), the request would
  456. // fail, and clients would then resend all the same stats again.
  457. logQueue := make([]LogFields, 0)
  458. // Domain bytes transferred stats
  459. // Older clients may not submit this data
  460. // Clients are expected to send host_bytes/domain_bytes stats only when
  461. // configured to do so in the handshake reponse. Legacy clients may still
  462. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  463. domainBytesExpected, err := support.TunnelServer.ExpectClientDomainBytes(sessionID)
  464. if err != nil {
  465. return nil, errors.Trace(err)
  466. }
  467. if domainBytesExpected && statusData["host_bytes"] != nil {
  468. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  469. if err != nil {
  470. return nil, errors.Trace(err)
  471. }
  472. for domain, bytes := range hostBytes {
  473. domainBytesFields := getRequestLogFields(
  474. "domain_bytes",
  475. geoIPData,
  476. authorizedAccessTypes,
  477. params,
  478. statusRequestParams)
  479. domainBytesFields["domain"] = domain
  480. domainBytesFields["bytes"] = bytes
  481. logQueue = append(logQueue, domainBytesFields)
  482. }
  483. }
  484. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  485. // not time-of-recording.
  486. // Remote server list download persistent stats.
  487. // Older clients may not submit this data.
  488. if statusData["remote_server_list_stats"] != nil {
  489. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  490. if err != nil {
  491. return nil, errors.Trace(err)
  492. }
  493. for _, remoteServerListStat := range remoteServerListStats {
  494. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  495. if _, ok := remoteServerListStat[name]; !ok {
  496. if field, ok := params[name]; ok {
  497. remoteServerListStat[name] = field
  498. }
  499. }
  500. }
  501. // For validation, copy expected fields from the outer
  502. // statusRequestParams.
  503. remoteServerListStat["server_secret"] = params["server_secret"]
  504. remoteServerListStat["client_session_id"] = params["client_session_id"]
  505. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  506. if err != nil {
  507. // Occasionally, clients may send corrupt persistent stat data. Do not
  508. // fail the status request, as this will lead to endless retries.
  509. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  510. continue
  511. }
  512. remoteServerListFields := getRequestLogFields(
  513. "remote_server_list",
  514. geoIPData,
  515. authorizedAccessTypes,
  516. remoteServerListStat,
  517. remoteServerListStatParams)
  518. logQueue = append(logQueue, remoteServerListFields)
  519. }
  520. }
  521. // Failed tunnel persistent stats.
  522. // Older clients may not submit this data.
  523. var invalidServerEntryTags map[string]bool
  524. if statusData["failed_tunnel_stats"] != nil {
  525. // Note: no guarantee that PsinetDatabase won't reload between database calls
  526. db := support.PsinetDatabase
  527. invalidServerEntryTags = make(map[string]bool)
  528. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  529. if err != nil {
  530. return nil, errors.Trace(err)
  531. }
  532. for _, failedTunnelStat := range failedTunnelStats {
  533. // failed_tunnel supplies a full set of base params, but the server secret
  534. // must use the correct value from the outer statusRequestParams.
  535. failedTunnelStat["server_secret"] = params["server_secret"]
  536. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  537. if err != nil {
  538. // Occasionally, clients may send corrupt persistent stat data. Do not
  539. // fail the status request, as this will lead to endless retries.
  540. //
  541. // TODO: trigger pruning if the data corruption indicates corrupt server
  542. // entry storage?
  543. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  544. continue
  545. }
  546. failedTunnelFields := getRequestLogFields(
  547. "failed_tunnel",
  548. geoIPData,
  549. authorizedAccessTypes,
  550. failedTunnelStat,
  551. failedTunnelStatParams)
  552. // Return a list of servers, identified by server entry tag, that are
  553. // invalid and presumed to be deleted. This information is used by clients
  554. // to prune deleted servers from their local datastores and stop attempting
  555. // connections to servers that no longer exist.
  556. //
  557. // This mechanism uses tags instead of server IPs: (a) to prevent an
  558. // enumeration attack, where a malicious client can query the entire IPv4
  559. // range and build a map of the Psiphon network; (b) to deal with recyling
  560. // cases where a server deleted and its IP is reused for a new server with
  561. // a distinct server entry.
  562. //
  563. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  564. // before returning a negative result, to mitigate accidental pruning.
  565. //
  566. // In addition, when the reported dial port number is 0, flag the server
  567. // entry as invalid to trigger client pruning. This covers a class of
  568. // invalid/semi-functional server entries, found in practice to be stored
  569. // by clients, where some protocol port number has been omitted -- due to
  570. // historical bugs in various server entry handling implementations. When
  571. // missing from a server entry loaded by a client, the port number
  572. // evaluates to 0, the zero value, which is not a valid port number even if
  573. // were not missing.
  574. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  575. if ok {
  576. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  577. if serverEntryValid {
  578. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  579. if err == nil && dialPortNumber == 0 {
  580. serverEntryValid = false
  581. }
  582. }
  583. if !serverEntryValid {
  584. invalidServerEntryTags[serverEntryTag] = true
  585. }
  586. // Add a field to the failed_tunnel log indicating if the server entry is
  587. // valid.
  588. failedTunnelFields["server_entry_valid"] = serverEntryValid
  589. }
  590. // Log failed_tunnel.
  591. logQueue = append(logQueue, failedTunnelFields)
  592. }
  593. }
  594. for _, logItem := range logQueue {
  595. log.LogRawFieldsWithTimestamp(logItem)
  596. }
  597. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  598. statusResponse := protocol.StatusResponse{
  599. Padding: strings.Repeat(" ", pad_response),
  600. }
  601. if len(invalidServerEntryTags) > 0 {
  602. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  603. i := 0
  604. for tag := range invalidServerEntryTags {
  605. statusResponse.InvalidServerEntryTags[i] = tag
  606. i++
  607. }
  608. }
  609. responsePayload, err := json.Marshal(statusResponse)
  610. if err != nil {
  611. return nil, errors.Trace(err)
  612. }
  613. return responsePayload, nil
  614. }
  615. // clientVerificationAPIRequestHandler is just a compliance stub
  616. // for older Android clients that still send verification requests
  617. func clientVerificationAPIRequestHandler(
  618. support *SupportServices,
  619. geoIPData GeoIPData,
  620. authorizedAccessTypes []string,
  621. params common.APIParameters) ([]byte, error) {
  622. return make([]byte, 0), nil
  623. }
  624. var tacticsParams = []requestParamSpec{
  625. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  626. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  627. }
  628. var tacticsRequestParams = append(
  629. append([]requestParamSpec(nil), tacticsParams...),
  630. baseSessionAndDialParams...)
  631. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  632. return func(params common.APIParameters) error {
  633. return validateRequestParams(config, params, tacticsRequestParams)
  634. }
  635. }
  636. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  637. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  638. logFields := getRequestLogFields(
  639. tactics.TACTICS_METRIC_EVENT_NAME,
  640. GeoIPData(geoIPData),
  641. nil, // authorizedAccessTypes are not known yet
  642. params,
  643. tacticsRequestParams)
  644. return common.LogFields(logFields)
  645. }
  646. }
  647. // requestParamSpec defines a request parameter. Each param is expected to be
  648. // a string, unless requestParamArray is specified, in which case an array of
  649. // strings is expected.
  650. type requestParamSpec struct {
  651. name string
  652. validator func(*Config, string) bool
  653. flags uint32
  654. }
  655. const (
  656. requestParamOptional = 1
  657. requestParamNotLogged = 1 << 1
  658. requestParamArray = 1 << 2
  659. requestParamJSON = 1 << 3
  660. requestParamLogStringAsInt = 1 << 4
  661. requestParamLogStringAsFloat = 1 << 5
  662. requestParamLogStringLengthAsInt = 1 << 6
  663. requestParamLogFlagAsBool = 1 << 7
  664. requestParamLogOnlyForFrontedMeek = 1 << 8
  665. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  666. )
  667. // baseParams are the basic request parameters that are expected for all API
  668. // requests and log events.
  669. var baseParams = []requestParamSpec{
  670. {"server_secret", isServerSecret, requestParamNotLogged},
  671. {"client_session_id", isHexDigits, requestParamNotLogged},
  672. {"propagation_channel_id", isHexDigits, 0},
  673. {"sponsor_id", isHexDigits, 0},
  674. {"client_version", isIntString, requestParamLogStringAsInt},
  675. {"client_platform", isClientPlatform, 0},
  676. {"client_build_rev", isHexDigits, requestParamOptional},
  677. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  678. {"device_region", isAnyString, requestParamOptional},
  679. }
  680. // baseSessionParams adds to baseParams the required session_id parameter. For
  681. // all requests except handshake, all existing clients are expected to send
  682. // session_id. Legacy clients may not send "session_id" in handshake.
  683. var baseSessionParams = append(
  684. []requestParamSpec{
  685. {"session_id", isHexDigits, 0}},
  686. baseParams...)
  687. // baseDialParams are the dial parameters, per-tunnel network protocol and
  688. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  689. // tactics.
  690. var baseDialParams = []requestParamSpec{
  691. {"relay_protocol", isRelayProtocol, 0},
  692. {"ssh_client_version", isAnyString, requestParamOptional},
  693. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  694. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  695. {"fronting_provider_id", isAnyString, requestParamOptional},
  696. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  697. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  698. {"meek_sni_server_name", isDomain, requestParamOptional},
  699. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  700. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  701. {"user_agent", isAnyString, requestParamOptional},
  702. {"tls_profile", isAnyString, requestParamOptional},
  703. {"tls_version", isAnyString, requestParamOptional},
  704. {"server_entry_region", isRegionCode, requestParamOptional},
  705. {"server_entry_source", isServerEntrySource, requestParamOptional},
  706. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  707. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  708. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  709. {"quic_version", isAnyString, requestParamOptional},
  710. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  711. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  712. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  713. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  714. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  715. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  716. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  717. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  718. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  719. {"egress_region", isRegionCode, requestParamOptional},
  720. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  721. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  722. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  723. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  724. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  725. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  726. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  727. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  728. {"client_bpf", isAnyString, requestParamOptional},
  729. {"network_type", isAnyString, requestParamOptional},
  730. }
  731. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  732. var baseSessionAndDialParams = append(
  733. append(
  734. []requestParamSpec{},
  735. baseSessionParams...),
  736. baseDialParams...)
  737. func validateRequestParams(
  738. config *Config,
  739. params common.APIParameters,
  740. expectedParams []requestParamSpec) error {
  741. for _, expectedParam := range expectedParams {
  742. value := params[expectedParam.name]
  743. if value == nil {
  744. if expectedParam.flags&requestParamOptional != 0 {
  745. continue
  746. }
  747. return errors.Tracef("missing param: %s", expectedParam.name)
  748. }
  749. var err error
  750. switch {
  751. case expectedParam.flags&requestParamArray != 0:
  752. err = validateStringArrayRequestParam(config, expectedParam, value)
  753. case expectedParam.flags&requestParamJSON != 0:
  754. // No validation: the JSON already unmarshalled; the parameter
  755. // user will validate that the JSON contains the expected
  756. // objects/data.
  757. // TODO: without validation, any valid JSON will be logged
  758. // by getRequestLogFields, even if the parameter user validates
  759. // and rejects the parameter.
  760. default:
  761. err = validateStringRequestParam(config, expectedParam, value)
  762. }
  763. if err != nil {
  764. return errors.Trace(err)
  765. }
  766. }
  767. return nil
  768. }
  769. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  770. // the baseSessionAndDialParams.
  771. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  772. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  773. // scalar types (int, string, etc.)
  774. paramsCopy := make(common.APIParameters)
  775. for _, baseParam := range baseSessionAndDialParams {
  776. value := params[baseParam.name]
  777. if value == nil {
  778. continue
  779. }
  780. paramsCopy[baseParam.name] = value
  781. }
  782. return paramsCopy
  783. }
  784. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  785. // Note: not a deep copy
  786. paramsCopy := make(common.APIParameters)
  787. for _, name := range updateOnConnectedParamNames {
  788. value := params[name]
  789. if value == nil {
  790. continue
  791. }
  792. paramsCopy[name] = value
  793. }
  794. return paramsCopy
  795. }
  796. func validateStringRequestParam(
  797. config *Config,
  798. expectedParam requestParamSpec,
  799. value interface{}) error {
  800. strValue, ok := value.(string)
  801. if !ok {
  802. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  803. }
  804. if !expectedParam.validator(config, strValue) {
  805. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  806. }
  807. return nil
  808. }
  809. func validateStringArrayRequestParam(
  810. config *Config,
  811. expectedParam requestParamSpec,
  812. value interface{}) error {
  813. arrayValue, ok := value.([]interface{})
  814. if !ok {
  815. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  816. }
  817. for _, value := range arrayValue {
  818. err := validateStringRequestParam(config, expectedParam, value)
  819. if err != nil {
  820. return errors.Trace(err)
  821. }
  822. }
  823. return nil
  824. }
  825. // getRequestLogFields makes LogFields to log the API event following
  826. // the legacy psi_web and current ELK naming conventions.
  827. func getRequestLogFields(
  828. eventName string,
  829. geoIPData GeoIPData,
  830. authorizedAccessTypes []string,
  831. params common.APIParameters,
  832. expectedParams []requestParamSpec) LogFields {
  833. logFields := make(LogFields)
  834. if eventName != "" {
  835. logFields["event_name"] = eventName
  836. }
  837. geoIPData.SetLogFields(logFields)
  838. if len(authorizedAccessTypes) > 0 {
  839. logFields["authorized_access_types"] = authorizedAccessTypes
  840. }
  841. if params == nil {
  842. return logFields
  843. }
  844. for _, expectedParam := range expectedParams {
  845. if expectedParam.flags&requestParamNotLogged != 0 {
  846. continue
  847. }
  848. var tunnelProtocol string
  849. if value, ok := params["relay_protocol"]; ok {
  850. tunnelProtocol, _ = value.(string)
  851. }
  852. if expectedParam.flags&requestParamLogOnlyForFrontedMeek != 0 &&
  853. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  854. continue
  855. }
  856. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  857. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  858. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  859. // Non-HTTP unfronted meek protocols never tranform the host header.
  860. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  861. continue
  862. }
  863. var transformedHostName string
  864. if value, ok := params["meek_transformed_host_name"]; ok {
  865. transformedHostName, _ = value.(string)
  866. }
  867. if transformedHostName != "1" {
  868. continue
  869. }
  870. }
  871. value := params[expectedParam.name]
  872. if value == nil {
  873. // Special case: older clients don't send this value,
  874. // so log a default.
  875. if expectedParam.name == "tunnel_whole_device" {
  876. value = "0"
  877. } else {
  878. // Skip omitted, optional params
  879. continue
  880. }
  881. }
  882. switch v := value.(type) {
  883. case string:
  884. strValue := v
  885. // Special cases:
  886. // - Number fields are encoded as integer types.
  887. // - For ELK performance we record certain domain-or-IP
  888. // fields as one of two different values based on type;
  889. // we also omit port from these host:port fields for now.
  890. // - Boolean fields that come into the api as "1"/"0"
  891. // must be logged as actual boolean values
  892. switch expectedParam.name {
  893. case "meek_dial_address":
  894. host, _, _ := net.SplitHostPort(strValue)
  895. if isIPAddress(nil, host) {
  896. logFields["meek_dial_ip_address"] = host
  897. } else {
  898. logFields["meek_dial_domain"] = host
  899. }
  900. case "upstream_proxy_type":
  901. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  902. logFields[expectedParam.name] = strings.ToLower(strValue)
  903. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  904. // Due to a client bug, clients may deliever an incorrect ""
  905. // value for speed_test_samples via the web API protocol. Omit
  906. // the field in this case.
  907. default:
  908. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  909. intValue, _ := strconv.Atoi(strValue)
  910. logFields[expectedParam.name] = intValue
  911. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  912. floatValue, _ := strconv.ParseFloat(strValue, 64)
  913. logFields[expectedParam.name] = floatValue
  914. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  915. logFields[expectedParam.name] = len(strValue)
  916. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  917. // Submitted value could be "0" or "1"
  918. // "0" and non "0"/"1" values should be transformed to false
  919. // "1" should be transformed to true
  920. if strValue == "1" {
  921. logFields[expectedParam.name] = true
  922. } else {
  923. logFields[expectedParam.name] = false
  924. }
  925. } else {
  926. logFields[expectedParam.name] = strValue
  927. }
  928. }
  929. case []interface{}:
  930. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  931. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  932. } else {
  933. logFields[expectedParam.name] = v
  934. }
  935. default:
  936. logFields[expectedParam.name] = v
  937. }
  938. }
  939. return logFields
  940. }
  941. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  942. // fields to more verbose names for metrics.
  943. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  944. // TODO: use reflection and add additional tags, e.g.,
  945. // `json:"s" log:"timestamp"` to remove hard-coded
  946. // tag value dependency?
  947. logSamples := make([]interface{}, len(samples))
  948. for i, sample := range samples {
  949. logSample := make(map[string]interface{})
  950. if m, ok := sample.(map[string]interface{}); ok {
  951. for k, v := range m {
  952. logK := k
  953. switch k {
  954. case "s":
  955. logK = "timestamp"
  956. case "r":
  957. logK = "server_region"
  958. case "p":
  959. logK = "relay_protocol"
  960. case "t":
  961. logK = "round_trip_time_ms"
  962. case "u":
  963. logK = "bytes_up"
  964. case "d":
  965. logK = "bytes_down"
  966. }
  967. logSample[logK] = v
  968. }
  969. }
  970. logSamples[i] = logSample
  971. }
  972. return logSamples
  973. }
  974. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  975. if params[name] == nil {
  976. return "", false
  977. }
  978. value, ok := params[name].(string)
  979. if !ok {
  980. return "", false
  981. }
  982. return value, true
  983. }
  984. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  985. if params[name] == nil {
  986. return "", errors.Tracef("missing param: %s", name)
  987. }
  988. value, ok := params[name].(string)
  989. if !ok {
  990. return "", errors.Tracef("invalid param: %s", name)
  991. }
  992. return value, nil
  993. }
  994. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  995. if params[name] == nil {
  996. return 0, errors.Tracef("missing param: %s", name)
  997. }
  998. valueStr, ok := params[name].(string)
  999. if !ok {
  1000. return 0, errors.Tracef("invalid param: %s", name)
  1001. }
  1002. value, err := strconv.Atoi(valueStr)
  1003. if !ok {
  1004. return 0, errors.Trace(err)
  1005. }
  1006. return value, nil
  1007. }
  1008. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1009. value, err := getIntStringRequestParam(params, name)
  1010. if err != nil {
  1011. return 0, errors.Trace(err)
  1012. }
  1013. if value < 0 {
  1014. value = 0
  1015. }
  1016. if value > PADDING_MAX_BYTES {
  1017. value = PADDING_MAX_BYTES
  1018. }
  1019. return int(value), nil
  1020. }
  1021. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1022. if params[name] == nil {
  1023. return nil, errors.Tracef("missing param: %s", name)
  1024. }
  1025. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1026. value, ok := params[name].(map[string]interface{})
  1027. if !ok {
  1028. return nil, errors.Tracef("invalid param: %s", name)
  1029. }
  1030. return common.APIParameters(value), nil
  1031. }
  1032. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1033. if params[name] == nil {
  1034. return nil, errors.Tracef("missing param: %s", name)
  1035. }
  1036. value, ok := params[name].([]interface{})
  1037. if !ok {
  1038. return nil, errors.Tracef("invalid param: %s", name)
  1039. }
  1040. result := make([]common.APIParameters, len(value))
  1041. for i, item := range value {
  1042. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1043. resultItem, ok := item.(map[string]interface{})
  1044. if !ok {
  1045. return nil, errors.Tracef("invalid param: %s", name)
  1046. }
  1047. result[i] = common.APIParameters(resultItem)
  1048. }
  1049. return result, nil
  1050. }
  1051. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1052. if params[name] == nil {
  1053. return nil, errors.Tracef("missing param: %s", name)
  1054. }
  1055. // TODO: can't use common.APIParameters type?
  1056. value, ok := params[name].(map[string]interface{})
  1057. if !ok {
  1058. return nil, errors.Tracef("invalid param: %s", name)
  1059. }
  1060. result := make(map[string]int64)
  1061. for k, v := range value {
  1062. numValue, ok := v.(float64)
  1063. if !ok {
  1064. return nil, errors.Tracef("invalid param: %s", name)
  1065. }
  1066. result[k] = int64(numValue)
  1067. }
  1068. return result, nil
  1069. }
  1070. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1071. if params[name] == nil {
  1072. return nil, errors.Tracef("missing param: %s", name)
  1073. }
  1074. value, ok := params[name].([]interface{})
  1075. if !ok {
  1076. return nil, errors.Tracef("invalid param: %s", name)
  1077. }
  1078. result := make([]string, len(value))
  1079. for i, v := range value {
  1080. strValue, ok := v.(string)
  1081. if !ok {
  1082. return nil, errors.Tracef("invalid param: %s", name)
  1083. }
  1084. result[i] = strValue
  1085. }
  1086. return result, nil
  1087. }
  1088. // Normalize reported client platform. Android clients, for example, report
  1089. // OS version, rooted status, and Google Play build status in the clientPlatform
  1090. // string along with "Android".
  1091. func normalizeClientPlatform(clientPlatform string) string {
  1092. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1093. return CLIENT_PLATFORM_ANDROID
  1094. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1095. return CLIENT_PLATFORM_IOS
  1096. }
  1097. return CLIENT_PLATFORM_WINDOWS
  1098. }
  1099. func isAnyString(config *Config, value string) bool {
  1100. return true
  1101. }
  1102. func isMobileClientPlatform(clientPlatform string) bool {
  1103. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1104. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1105. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1106. }
  1107. // Input validators follow the legacy validations rules in psi_web.
  1108. func isServerSecret(config *Config, value string) bool {
  1109. return subtle.ConstantTimeCompare(
  1110. []byte(value),
  1111. []byte(config.WebServerSecret)) == 1
  1112. }
  1113. func isHexDigits(_ *Config, value string) bool {
  1114. // Allows both uppercase in addition to lowercase, for legacy support.
  1115. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1116. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1117. })
  1118. }
  1119. func isBase64String(_ *Config, value string) bool {
  1120. _, err := base64.StdEncoding.DecodeString(value)
  1121. return err == nil
  1122. }
  1123. func isDigits(_ *Config, value string) bool {
  1124. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1125. return c < '0' || c > '9'
  1126. })
  1127. }
  1128. func isIntString(_ *Config, value string) bool {
  1129. _, err := strconv.Atoi(value)
  1130. return err == nil
  1131. }
  1132. func isFloatString(_ *Config, value string) bool {
  1133. _, err := strconv.ParseFloat(value, 64)
  1134. return err == nil
  1135. }
  1136. func isClientPlatform(_ *Config, value string) bool {
  1137. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1138. // Note: stricter than psi_web's Python string.whitespace
  1139. return unicode.Is(unicode.White_Space, c)
  1140. })
  1141. }
  1142. func isRelayProtocol(_ *Config, value string) bool {
  1143. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1144. }
  1145. func isBooleanFlag(_ *Config, value string) bool {
  1146. return value == "0" || value == "1"
  1147. }
  1148. func isUpstreamProxyType(_ *Config, value string) bool {
  1149. value = strings.ToLower(value)
  1150. return value == "http" || value == "socks5" || value == "socks4a"
  1151. }
  1152. func isRegionCode(_ *Config, value string) bool {
  1153. if len(value) != 2 {
  1154. return false
  1155. }
  1156. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1157. return c < 'A' || c > 'Z'
  1158. })
  1159. }
  1160. func isDialAddress(_ *Config, value string) bool {
  1161. // "<host>:<port>", where <host> is a domain or IP address
  1162. parts := strings.Split(value, ":")
  1163. if len(parts) != 2 {
  1164. return false
  1165. }
  1166. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1167. return false
  1168. }
  1169. if !isDigits(nil, parts[1]) {
  1170. return false
  1171. }
  1172. _, err := strconv.Atoi(parts[1])
  1173. if err != nil {
  1174. return false
  1175. }
  1176. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1177. return true
  1178. }
  1179. func isIPAddress(_ *Config, value string) bool {
  1180. return net.ParseIP(value) != nil
  1181. }
  1182. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1183. func isDomain(_ *Config, value string) bool {
  1184. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1185. //
  1186. // "ensures that each segment
  1187. // * contains at least one character and a maximum of 63 characters
  1188. // * consists only of allowed characters
  1189. // * doesn't begin or end with a hyphen"
  1190. //
  1191. if len(value) > 255 {
  1192. return false
  1193. }
  1194. value = strings.TrimSuffix(value, ".")
  1195. for _, part := range strings.Split(value, ".") {
  1196. // Note: regexp doesn't support the following Perl expression which
  1197. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1198. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1199. return false
  1200. }
  1201. if !isDomainRegex.Match([]byte(part)) {
  1202. return false
  1203. }
  1204. }
  1205. return true
  1206. }
  1207. func isHostHeader(_ *Config, value string) bool {
  1208. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1209. if strings.Contains(value, ":") {
  1210. return isDialAddress(nil, value)
  1211. }
  1212. return isIPAddress(nil, value) || isDomain(nil, value)
  1213. }
  1214. func isServerEntrySource(_ *Config, value string) bool {
  1215. return common.Contains(protocol.SupportedServerEntrySources, value)
  1216. }
  1217. var isISO8601DateRegex = regexp.MustCompile(
  1218. `(?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})))`)
  1219. func isISO8601Date(_ *Config, value string) bool {
  1220. return isISO8601DateRegex.Match([]byte(value))
  1221. }
  1222. func isLastConnected(_ *Config, value string) bool {
  1223. return value == "None" || isISO8601Date(nil, value)
  1224. }