api.go 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  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. var serverEntryTagStr string
  566. serverEntryTag, ok := failedTunnelStat["server_entry_tag"]
  567. if ok {
  568. serverEntryTagStr, ok = serverEntryTag.(string)
  569. }
  570. if ok {
  571. serverEntryValid := db.IsValidServerEntryTag(serverEntryTagStr)
  572. if !serverEntryValid {
  573. invalidServerEntryTags[serverEntryTagStr] = true
  574. }
  575. // Add a field to the failed_tunnel log indicating if the server entry is
  576. // valid.
  577. failedTunnelFields["server_entry_valid"] = serverEntryValid
  578. }
  579. // Log failed_tunnel.
  580. logQueue = append(logQueue, failedTunnelFields)
  581. }
  582. }
  583. for _, logItem := range logQueue {
  584. log.LogRawFieldsWithTimestamp(logItem)
  585. }
  586. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  587. statusResponse := protocol.StatusResponse{
  588. Padding: strings.Repeat(" ", pad_response),
  589. }
  590. if len(invalidServerEntryTags) > 0 {
  591. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  592. i := 0
  593. for tag := range invalidServerEntryTags {
  594. statusResponse.InvalidServerEntryTags[i] = tag
  595. i++
  596. }
  597. }
  598. responsePayload, err := json.Marshal(statusResponse)
  599. if err != nil {
  600. return nil, errors.Trace(err)
  601. }
  602. return responsePayload, nil
  603. }
  604. // clientVerificationAPIRequestHandler is just a compliance stub
  605. // for older Android clients that still send verification requests
  606. func clientVerificationAPIRequestHandler(
  607. support *SupportServices,
  608. geoIPData GeoIPData,
  609. authorizedAccessTypes []string,
  610. params common.APIParameters) ([]byte, error) {
  611. return make([]byte, 0), nil
  612. }
  613. var tacticsParams = []requestParamSpec{
  614. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  615. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  616. }
  617. var tacticsRequestParams = append(
  618. append([]requestParamSpec(nil), tacticsParams...),
  619. baseSessionAndDialParams...)
  620. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  621. return func(params common.APIParameters) error {
  622. return validateRequestParams(config, params, tacticsRequestParams)
  623. }
  624. }
  625. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  626. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  627. logFields := getRequestLogFields(
  628. tactics.TACTICS_METRIC_EVENT_NAME,
  629. GeoIPData(geoIPData),
  630. nil, // authorizedAccessTypes are not known yet
  631. params,
  632. tacticsRequestParams)
  633. return common.LogFields(logFields)
  634. }
  635. }
  636. // requestParamSpec defines a request parameter. Each param is expected to be
  637. // a string, unless requestParamArray is specified, in which case an array of
  638. // strings is expected.
  639. type requestParamSpec struct {
  640. name string
  641. validator func(*Config, string) bool
  642. flags uint32
  643. }
  644. const (
  645. requestParamOptional = 1
  646. requestParamNotLogged = 1 << 1
  647. requestParamArray = 1 << 2
  648. requestParamJSON = 1 << 3
  649. requestParamLogStringAsInt = 1 << 4
  650. requestParamLogStringAsFloat = 1 << 5
  651. requestParamLogStringLengthAsInt = 1 << 6
  652. requestParamLogFlagAsBool = 1 << 7
  653. requestParamLogOnlyForFrontedMeek = 1 << 8
  654. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  655. )
  656. // baseParams are the basic request parameters that are expected for all API
  657. // requests and log events.
  658. var baseParams = []requestParamSpec{
  659. {"server_secret", isServerSecret, requestParamNotLogged},
  660. {"client_session_id", isHexDigits, requestParamNotLogged},
  661. {"propagation_channel_id", isHexDigits, 0},
  662. {"sponsor_id", isHexDigits, 0},
  663. {"client_version", isIntString, requestParamLogStringAsInt},
  664. {"client_platform", isClientPlatform, 0},
  665. {"client_build_rev", isHexDigits, requestParamOptional},
  666. {"tunnel_whole_device", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  667. {"device_region", isAnyString, requestParamOptional},
  668. }
  669. // baseSessionParams adds to baseParams the required session_id parameter. For
  670. // all requests except handshake, all existing clients are expected to send
  671. // session_id. Legacy clients may not send "session_id" in handshake.
  672. var baseSessionParams = append(
  673. []requestParamSpec{
  674. {"session_id", isHexDigits, 0}},
  675. baseParams...)
  676. // baseDialParams are the dial parameters, per-tunnel network protocol and
  677. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  678. // tactics.
  679. var baseDialParams = []requestParamSpec{
  680. {"relay_protocol", isRelayProtocol, 0},
  681. {"ssh_client_version", isAnyString, requestParamOptional},
  682. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  683. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  684. {"fronting_provider_id", isAnyString, requestParamOptional},
  685. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  686. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeek},
  687. {"meek_sni_server_name", isDomain, requestParamOptional},
  688. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  689. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  690. {"user_agent", isAnyString, requestParamOptional},
  691. {"tls_profile", isAnyString, requestParamOptional},
  692. {"tls_version", isAnyString, requestParamOptional},
  693. {"server_entry_region", isRegionCode, requestParamOptional},
  694. {"server_entry_source", isServerEntrySource, requestParamOptional},
  695. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  696. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  697. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  698. {"quic_version", isAnyString, requestParamOptional},
  699. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  700. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  701. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  702. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  703. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  704. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  705. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  706. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  707. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  708. {"egress_region", isRegionCode, requestParamOptional},
  709. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  710. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  711. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  712. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  713. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  714. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  715. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  716. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  717. {"client_bpf", isAnyString, requestParamOptional},
  718. {"network_type", isAnyString, requestParamOptional},
  719. }
  720. // baseSessionAndDialParams adds baseDialParams to baseSessionParams.
  721. var baseSessionAndDialParams = append(
  722. append(
  723. []requestParamSpec{},
  724. baseSessionParams...),
  725. baseDialParams...)
  726. func validateRequestParams(
  727. config *Config,
  728. params common.APIParameters,
  729. expectedParams []requestParamSpec) error {
  730. for _, expectedParam := range expectedParams {
  731. value := params[expectedParam.name]
  732. if value == nil {
  733. if expectedParam.flags&requestParamOptional != 0 {
  734. continue
  735. }
  736. return errors.Tracef("missing param: %s", expectedParam.name)
  737. }
  738. var err error
  739. switch {
  740. case expectedParam.flags&requestParamArray != 0:
  741. err = validateStringArrayRequestParam(config, expectedParam, value)
  742. case expectedParam.flags&requestParamJSON != 0:
  743. // No validation: the JSON already unmarshalled; the parameter
  744. // user will validate that the JSON contains the expected
  745. // objects/data.
  746. // TODO: without validation, any valid JSON will be logged
  747. // by getRequestLogFields, even if the parameter user validates
  748. // and rejects the parameter.
  749. default:
  750. err = validateStringRequestParam(config, expectedParam, value)
  751. }
  752. if err != nil {
  753. return errors.Trace(err)
  754. }
  755. }
  756. return nil
  757. }
  758. // copyBaseSessionAndDialParams makes a copy of the params which includes only
  759. // the baseSessionAndDialParams.
  760. func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
  761. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  762. // scalar types (int, string, etc.)
  763. paramsCopy := make(common.APIParameters)
  764. for _, baseParam := range baseSessionAndDialParams {
  765. value := params[baseParam.name]
  766. if value == nil {
  767. continue
  768. }
  769. paramsCopy[baseParam.name] = value
  770. }
  771. return paramsCopy
  772. }
  773. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  774. // Note: not a deep copy
  775. paramsCopy := make(common.APIParameters)
  776. for _, name := range updateOnConnectedParamNames {
  777. value := params[name]
  778. if value == nil {
  779. continue
  780. }
  781. paramsCopy[name] = value
  782. }
  783. return paramsCopy
  784. }
  785. func validateStringRequestParam(
  786. config *Config,
  787. expectedParam requestParamSpec,
  788. value interface{}) error {
  789. strValue, ok := value.(string)
  790. if !ok {
  791. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  792. }
  793. if !expectedParam.validator(config, strValue) {
  794. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  795. }
  796. return nil
  797. }
  798. func validateStringArrayRequestParam(
  799. config *Config,
  800. expectedParam requestParamSpec,
  801. value interface{}) error {
  802. arrayValue, ok := value.([]interface{})
  803. if !ok {
  804. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  805. }
  806. for _, value := range arrayValue {
  807. err := validateStringRequestParam(config, expectedParam, value)
  808. if err != nil {
  809. return errors.Trace(err)
  810. }
  811. }
  812. return nil
  813. }
  814. // getRequestLogFields makes LogFields to log the API event following
  815. // the legacy psi_web and current ELK naming conventions.
  816. func getRequestLogFields(
  817. eventName string,
  818. geoIPData GeoIPData,
  819. authorizedAccessTypes []string,
  820. params common.APIParameters,
  821. expectedParams []requestParamSpec) LogFields {
  822. logFields := make(LogFields)
  823. if eventName != "" {
  824. logFields["event_name"] = eventName
  825. }
  826. geoIPData.SetLogFields(logFields)
  827. if len(authorizedAccessTypes) > 0 {
  828. logFields["authorized_access_types"] = authorizedAccessTypes
  829. }
  830. if params == nil {
  831. return logFields
  832. }
  833. for _, expectedParam := range expectedParams {
  834. if expectedParam.flags&requestParamNotLogged != 0 {
  835. continue
  836. }
  837. var tunnelProtocol string
  838. if value, ok := params["relay_protocol"]; ok {
  839. tunnelProtocol, _ = value.(string)
  840. }
  841. if expectedParam.flags&requestParamLogOnlyForFrontedMeek != 0 &&
  842. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  843. continue
  844. }
  845. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  846. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  847. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  848. // Non-HTTP unfronted meek protocols never tranform the host header.
  849. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  850. continue
  851. }
  852. var transformedHostName string
  853. if value, ok := params["meek_transformed_host_name"]; ok {
  854. transformedHostName, _ = value.(string)
  855. }
  856. if transformedHostName != "1" {
  857. continue
  858. }
  859. }
  860. value := params[expectedParam.name]
  861. if value == nil {
  862. // Special case: older clients don't send this value,
  863. // so log a default.
  864. if expectedParam.name == "tunnel_whole_device" {
  865. value = "0"
  866. } else {
  867. // Skip omitted, optional params
  868. continue
  869. }
  870. }
  871. switch v := value.(type) {
  872. case string:
  873. strValue := v
  874. // Special cases:
  875. // - Number fields are encoded as integer types.
  876. // - For ELK performance we record certain domain-or-IP
  877. // fields as one of two different values based on type;
  878. // we also omit port from these host:port fields for now.
  879. // - Boolean fields that come into the api as "1"/"0"
  880. // must be logged as actual boolean values
  881. switch expectedParam.name {
  882. case "meek_dial_address":
  883. host, _, _ := net.SplitHostPort(strValue)
  884. if isIPAddress(nil, host) {
  885. logFields["meek_dial_ip_address"] = host
  886. } else {
  887. logFields["meek_dial_domain"] = host
  888. }
  889. case "upstream_proxy_type":
  890. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  891. logFields[expectedParam.name] = strings.ToLower(strValue)
  892. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  893. // Due to a client bug, clients may deliever an incorrect ""
  894. // value for speed_test_samples via the web API protocol. Omit
  895. // the field in this case.
  896. default:
  897. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  898. intValue, _ := strconv.Atoi(strValue)
  899. logFields[expectedParam.name] = intValue
  900. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  901. floatValue, _ := strconv.ParseFloat(strValue, 64)
  902. logFields[expectedParam.name] = floatValue
  903. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  904. logFields[expectedParam.name] = len(strValue)
  905. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  906. // Submitted value could be "0" or "1"
  907. // "0" and non "0"/"1" values should be transformed to false
  908. // "1" should be transformed to true
  909. if strValue == "1" {
  910. logFields[expectedParam.name] = true
  911. } else {
  912. logFields[expectedParam.name] = false
  913. }
  914. } else {
  915. logFields[expectedParam.name] = strValue
  916. }
  917. }
  918. case []interface{}:
  919. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  920. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  921. } else {
  922. logFields[expectedParam.name] = v
  923. }
  924. default:
  925. logFields[expectedParam.name] = v
  926. }
  927. }
  928. return logFields
  929. }
  930. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  931. // fields to more verbose names for metrics.
  932. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  933. // TODO: use reflection and add additional tags, e.g.,
  934. // `json:"s" log:"timestamp"` to remove hard-coded
  935. // tag value dependency?
  936. logSamples := make([]interface{}, len(samples))
  937. for i, sample := range samples {
  938. logSample := make(map[string]interface{})
  939. if m, ok := sample.(map[string]interface{}); ok {
  940. for k, v := range m {
  941. logK := k
  942. switch k {
  943. case "s":
  944. logK = "timestamp"
  945. case "r":
  946. logK = "server_region"
  947. case "p":
  948. logK = "relay_protocol"
  949. case "t":
  950. logK = "round_trip_time_ms"
  951. case "u":
  952. logK = "bytes_up"
  953. case "d":
  954. logK = "bytes_down"
  955. }
  956. logSample[logK] = v
  957. }
  958. }
  959. logSamples[i] = logSample
  960. }
  961. return logSamples
  962. }
  963. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  964. if params[name] == nil {
  965. return "", false
  966. }
  967. value, ok := params[name].(string)
  968. if !ok {
  969. return "", false
  970. }
  971. return value, true
  972. }
  973. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  974. if params[name] == nil {
  975. return "", errors.Tracef("missing param: %s", name)
  976. }
  977. value, ok := params[name].(string)
  978. if !ok {
  979. return "", errors.Tracef("invalid param: %s", name)
  980. }
  981. return value, nil
  982. }
  983. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  984. if params[name] == nil {
  985. return 0, errors.Tracef("missing param: %s", name)
  986. }
  987. valueStr, ok := params[name].(string)
  988. if !ok {
  989. return 0, errors.Tracef("invalid param: %s", name)
  990. }
  991. value, err := strconv.Atoi(valueStr)
  992. if !ok {
  993. return 0, errors.Trace(err)
  994. }
  995. return value, nil
  996. }
  997. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  998. value, err := getIntStringRequestParam(params, name)
  999. if err != nil {
  1000. return 0, errors.Trace(err)
  1001. }
  1002. if value < 0 {
  1003. value = 0
  1004. }
  1005. if value > PADDING_MAX_BYTES {
  1006. value = PADDING_MAX_BYTES
  1007. }
  1008. return int(value), nil
  1009. }
  1010. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1011. if params[name] == nil {
  1012. return nil, errors.Tracef("missing param: %s", name)
  1013. }
  1014. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1015. value, ok := params[name].(map[string]interface{})
  1016. if !ok {
  1017. return nil, errors.Tracef("invalid param: %s", name)
  1018. }
  1019. return common.APIParameters(value), nil
  1020. }
  1021. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1022. if params[name] == nil {
  1023. return nil, errors.Tracef("missing param: %s", name)
  1024. }
  1025. value, ok := params[name].([]interface{})
  1026. if !ok {
  1027. return nil, errors.Tracef("invalid param: %s", name)
  1028. }
  1029. result := make([]common.APIParameters, len(value))
  1030. for i, item := range value {
  1031. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1032. resultItem, ok := item.(map[string]interface{})
  1033. if !ok {
  1034. return nil, errors.Tracef("invalid param: %s", name)
  1035. }
  1036. result[i] = common.APIParameters(resultItem)
  1037. }
  1038. return result, nil
  1039. }
  1040. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1041. if params[name] == nil {
  1042. return nil, errors.Tracef("missing param: %s", name)
  1043. }
  1044. // TODO: can't use common.APIParameters type?
  1045. value, ok := params[name].(map[string]interface{})
  1046. if !ok {
  1047. return nil, errors.Tracef("invalid param: %s", name)
  1048. }
  1049. result := make(map[string]int64)
  1050. for k, v := range value {
  1051. numValue, ok := v.(float64)
  1052. if !ok {
  1053. return nil, errors.Tracef("invalid param: %s", name)
  1054. }
  1055. result[k] = int64(numValue)
  1056. }
  1057. return result, nil
  1058. }
  1059. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1060. if params[name] == nil {
  1061. return nil, errors.Tracef("missing param: %s", name)
  1062. }
  1063. value, ok := params[name].([]interface{})
  1064. if !ok {
  1065. return nil, errors.Tracef("invalid param: %s", name)
  1066. }
  1067. result := make([]string, len(value))
  1068. for i, v := range value {
  1069. strValue, ok := v.(string)
  1070. if !ok {
  1071. return nil, errors.Tracef("invalid param: %s", name)
  1072. }
  1073. result[i] = strValue
  1074. }
  1075. return result, nil
  1076. }
  1077. // Normalize reported client platform. Android clients, for example, report
  1078. // OS version, rooted status, and Google Play build status in the clientPlatform
  1079. // string along with "Android".
  1080. func normalizeClientPlatform(clientPlatform string) string {
  1081. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1082. return CLIENT_PLATFORM_ANDROID
  1083. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1084. return CLIENT_PLATFORM_IOS
  1085. }
  1086. return CLIENT_PLATFORM_WINDOWS
  1087. }
  1088. func isAnyString(config *Config, value string) bool {
  1089. return true
  1090. }
  1091. func isMobileClientPlatform(clientPlatform string) bool {
  1092. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1093. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1094. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1095. }
  1096. // Input validators follow the legacy validations rules in psi_web.
  1097. func isServerSecret(config *Config, value string) bool {
  1098. return subtle.ConstantTimeCompare(
  1099. []byte(value),
  1100. []byte(config.WebServerSecret)) == 1
  1101. }
  1102. func isHexDigits(_ *Config, value string) bool {
  1103. // Allows both uppercase in addition to lowercase, for legacy support.
  1104. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1105. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1106. })
  1107. }
  1108. func isBase64String(_ *Config, value string) bool {
  1109. _, err := base64.StdEncoding.DecodeString(value)
  1110. return err == nil
  1111. }
  1112. func isDigits(_ *Config, value string) bool {
  1113. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1114. return c < '0' || c > '9'
  1115. })
  1116. }
  1117. func isIntString(_ *Config, value string) bool {
  1118. _, err := strconv.Atoi(value)
  1119. return err == nil
  1120. }
  1121. func isFloatString(_ *Config, value string) bool {
  1122. _, err := strconv.ParseFloat(value, 64)
  1123. return err == nil
  1124. }
  1125. func isClientPlatform(_ *Config, value string) bool {
  1126. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1127. // Note: stricter than psi_web's Python string.whitespace
  1128. return unicode.Is(unicode.White_Space, c)
  1129. })
  1130. }
  1131. func isRelayProtocol(_ *Config, value string) bool {
  1132. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1133. }
  1134. func isBooleanFlag(_ *Config, value string) bool {
  1135. return value == "0" || value == "1"
  1136. }
  1137. func isUpstreamProxyType(_ *Config, value string) bool {
  1138. value = strings.ToLower(value)
  1139. return value == "http" || value == "socks5" || value == "socks4a"
  1140. }
  1141. func isRegionCode(_ *Config, value string) bool {
  1142. if len(value) != 2 {
  1143. return false
  1144. }
  1145. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1146. return c < 'A' || c > 'Z'
  1147. })
  1148. }
  1149. func isDialAddress(_ *Config, value string) bool {
  1150. // "<host>:<port>", where <host> is a domain or IP address
  1151. parts := strings.Split(value, ":")
  1152. if len(parts) != 2 {
  1153. return false
  1154. }
  1155. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1156. return false
  1157. }
  1158. if !isDigits(nil, parts[1]) {
  1159. return false
  1160. }
  1161. _, err := strconv.Atoi(parts[1])
  1162. if err != nil {
  1163. return false
  1164. }
  1165. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1166. return true
  1167. }
  1168. func isIPAddress(_ *Config, value string) bool {
  1169. return net.ParseIP(value) != nil
  1170. }
  1171. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1172. func isDomain(_ *Config, value string) bool {
  1173. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1174. //
  1175. // "ensures that each segment
  1176. // * contains at least one character and a maximum of 63 characters
  1177. // * consists only of allowed characters
  1178. // * doesn't begin or end with a hyphen"
  1179. //
  1180. if len(value) > 255 {
  1181. return false
  1182. }
  1183. value = strings.TrimSuffix(value, ".")
  1184. for _, part := range strings.Split(value, ".") {
  1185. // Note: regexp doesn't support the following Perl expression which
  1186. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1187. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1188. return false
  1189. }
  1190. if !isDomainRegex.Match([]byte(part)) {
  1191. return false
  1192. }
  1193. }
  1194. return true
  1195. }
  1196. func isHostHeader(_ *Config, value string) bool {
  1197. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1198. if strings.Contains(value, ":") {
  1199. return isDialAddress(nil, value)
  1200. }
  1201. return isIPAddress(nil, value) || isDomain(nil, value)
  1202. }
  1203. func isServerEntrySource(_ *Config, value string) bool {
  1204. return common.Contains(protocol.SupportedServerEntrySources, value)
  1205. }
  1206. var isISO8601DateRegex = regexp.MustCompile(
  1207. `(?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})))`)
  1208. func isISO8601Date(_ *Config, value string) bool {
  1209. return isISO8601DateRegex.Match([]byte(value))
  1210. }
  1211. func isLastConnected(_ *Config, value string) bool {
  1212. return value == "None" || isISO8601Date(nil, value)
  1213. }