api.go 52 KB

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