api.go 51 KB

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