api.go 49 KB

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