api.go 53 KB

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