api.go 50 KB

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