api.go 44 KB

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