api.go 45 KB

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