api.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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. "encoding/base64"
  22. "encoding/json"
  23. "net"
  24. "regexp"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "unicode"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  35. "github.com/fxamacker/cbor/v2"
  36. )
  37. const (
  38. MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  39. PADDING_MAX_BYTES = 16 * 1024
  40. CLIENT_PLATFORM_ANDROID = "Android"
  41. CLIENT_PLATFORM_WINDOWS = "Windows"
  42. CLIENT_PLATFORM_IOS = "iOS"
  43. )
  44. // sshAPIRequestHandler routes Psiphon API requests transported as
  45. // JSON objects via the SSH request mechanism.
  46. //
  47. // The API request parameters and event log values follow the legacy
  48. // psi_web protocol and naming conventions. The API is compatible with
  49. // all tunnel-core clients but are not backwards compatible with all
  50. // legacy clients.
  51. func sshAPIRequestHandler(
  52. support *SupportServices,
  53. sshClient *sshClient,
  54. name string,
  55. requestPayload []byte) ([]byte, error) {
  56. // Notes:
  57. //
  58. // - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  59. // by max SSH request packet size.
  60. //
  61. // - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
  62. // array of base64-encoded strings; the base64 representation should
  63. // not be decoded to []byte values. The default behavior of
  64. // https://golang.org/pkg/encoding/json/#Unmarshal for a target of
  65. // type map[string]interface{} will unmarshal a base64-encoded string
  66. // to a string, not a decoded []byte, as required.
  67. var params common.APIParameters
  68. // The request payload is either packed CBOR or legacy JSON.
  69. params, isPacked, err := protocol.GetPackedAPIParametersRequestPayload(requestPayload)
  70. if err != nil {
  71. return nil, errors.Tracef(
  72. "invalid packed payload for request name: %s: %s", name, err)
  73. }
  74. if !isPacked {
  75. err := json.Unmarshal(requestPayload, &params)
  76. if err != nil {
  77. return nil, errors.Tracef(
  78. "invalid payload for request name: %s: %s", name, err)
  79. }
  80. }
  81. // Before invoking the handlers, enforce some preconditions:
  82. //
  83. // - A handshake request must precede any other requests.
  84. // - When the handshake results in a traffic rules state where
  85. // the client is immediately exhausted, no requests
  86. // may succeed. This case ensures that blocked clients do
  87. // not log "connected", etc.
  88. //
  89. // Only one handshake request may be made. There is no check here
  90. // to enforce that handshakeAPIRequestHandler will be called at
  91. // most once. The SetHandshakeState call in handshakeAPIRequestHandler
  92. // enforces that only a single handshake is made; enforcing that there
  93. // ensures no race condition even if concurrent requests are
  94. // in flight.
  95. if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
  96. completed, exhausted := sshClient.getHandshaked()
  97. if !completed {
  98. return nil, errors.TraceNew("handshake not completed")
  99. }
  100. if exhausted {
  101. return nil, errors.TraceNew("exhausted after handshake")
  102. }
  103. }
  104. switch name {
  105. case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
  106. return handshakeAPIRequestHandler(
  107. support, protocol.PSIPHON_API_PROTOCOL_SSH, sshClient, params)
  108. case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
  109. return connectedAPIRequestHandler(
  110. support, sshClient, params)
  111. case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
  112. return statusAPIRequestHandler(
  113. support, sshClient, params)
  114. case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
  115. return clientVerificationAPIRequestHandler(
  116. support, sshClient, params)
  117. }
  118. return nil, errors.Tracef("invalid request name: %s", name)
  119. }
  120. var handshakeRequestParams = append(
  121. append(
  122. []requestParamSpec{
  123. {"missing_server_entry_signature", isBase64String, requestParamOptional},
  124. {"missing_server_entry_provider_id", isBase64String, requestParamOptional},
  125. },
  126. baseAndDialParams...),
  127. tacticsParams...)
  128. // handshakeAPIRequestHandler implements the "handshake" API request.
  129. // Clients make the handshake immediately after establishing a tunnel
  130. // connection; the response tells the client what homepage to open, what
  131. // stats to record, etc.
  132. func handshakeAPIRequestHandler(
  133. support *SupportServices,
  134. apiProtocol string,
  135. sshClient *sshClient,
  136. params common.APIParameters) ([]byte, error) {
  137. var clientGeoIPData GeoIPData
  138. var inproxyClientIP string
  139. var inproxyClientGeoIPData GeoIPData
  140. var inproxyRelayLogFields common.LogFields
  141. if sshClient.isInproxyTunnelProtocol {
  142. inproxyConnectionID, err := getStringRequestParam(params, "inproxy_connection_id")
  143. if err != nil {
  144. return nil, errors.Trace(err)
  145. }
  146. // Complete the in-proxy broker/server relay before the rest of
  147. // handshake in order to obtain the original client IP and other
  148. // inputs sent from the broker.
  149. //
  150. // In the best and typical case, the broker has already established a
  151. // secure session with this server and the inproxy_relay_packet is
  152. // the broker report application-level payload. Otherwise, if there
  153. // is no session or the session has expired, session handshake
  154. // messages will be relayed to the broker via the client, using SSH
  155. // requests to the client. These requests/responses happen while the
  156. // handshake response remains outstanding, as this handler needs the
  157. // original client IP and its geolocation data in order to determine
  158. // the correct landing pages, traffic rules, tactics, etc.
  159. //
  160. // The client should extends its handshake timeout to accommodate
  161. // potential relay round trips.
  162. inproxyRelayPacketStr, err := getStringRequestParam(params, "inproxy_relay_packet")
  163. if err != nil {
  164. return nil, errors.Trace(err)
  165. }
  166. inproxyRelayPacket, err := base64.RawStdEncoding.DecodeString(inproxyRelayPacketStr)
  167. if err != nil {
  168. return nil, errors.Trace(err)
  169. }
  170. inproxyClientIP, inproxyRelayLogFields, err = doHandshakeInproxyBrokerRelay(
  171. sshClient,
  172. inproxyConnectionID,
  173. inproxyRelayPacket)
  174. if err != nil {
  175. return nil, errors.Trace(err)
  176. }
  177. inproxyClientGeoIPData = support.GeoIPService.Lookup(inproxyClientIP)
  178. clientGeoIPData = inproxyClientGeoIPData
  179. } else {
  180. clientGeoIPData = sshClient.getClientGeoIPData()
  181. }
  182. // Check input parameters
  183. // Note: ignoring legacy "known_servers" params
  184. err := validateRequestParams(support.Config, params, handshakeRequestParams)
  185. if err != nil {
  186. return nil, errors.Trace(err)
  187. }
  188. sponsorID, _ := getStringRequestParam(params, "sponsor_id")
  189. clientVersion, _ := getStringRequestParam(params, "client_version")
  190. clientPlatform, _ := getStringRequestParam(params, "client_platform")
  191. isMobile := isMobileClientPlatform(clientPlatform)
  192. normalizedPlatform := normalizeClientPlatform(clientPlatform)
  193. // establishedTunnelsCount is used in traffic rule selection. When omitted by
  194. // the client, a value of 0 will be used.
  195. establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
  196. var authorizations []string
  197. if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
  198. authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
  199. if err != nil {
  200. return nil, errors.Trace(err)
  201. }
  202. }
  203. deviceRegion, ok := getOptionalStringRequestParam(params, "device_region")
  204. if !ok {
  205. deviceRegion = GEOIP_UNKNOWN_VALUE
  206. }
  207. // splitTunnelOwnRegion indicates if the client is requesting split tunnel
  208. // mode to be applied to the client's own country. When omitted by the
  209. // client, the value will be false.
  210. //
  211. // When split_tunnel_regions is non-empty, split tunnel mode will be
  212. // applied for the specified country codes. When omitted by the client,
  213. // the value will be an empty slice.
  214. splitTunnelOwnRegion, _ := getBoolStringRequestParam(params, "split_tunnel")
  215. splitTunnelOtherRegions, _ := getStringArrayRequestParam(params, "split_tunnel_regions")
  216. ownRegion := ""
  217. if splitTunnelOwnRegion {
  218. ownRegion = clientGeoIPData.Country
  219. }
  220. var splitTunnelLookup *splitTunnelLookup
  221. if ownRegion != "" || len(splitTunnelOtherRegions) > 0 {
  222. splitTunnelLookup, err = newSplitTunnelLookup(ownRegion, splitTunnelOtherRegions)
  223. if err != nil {
  224. return nil, errors.Trace(err)
  225. }
  226. }
  227. // Note: no guarantee that PsinetDatabase won't reload between database calls
  228. db := support.PsinetDatabase
  229. httpsRequestRegexes, domainBytesChecksum := db.GetHttpsRequestRegexes(sponsorID)
  230. tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
  231. common.GeoIPData(clientGeoIPData), params)
  232. if err != nil {
  233. return nil, errors.Trace(err)
  234. }
  235. var newTacticsTag string
  236. if tacticsPayload != nil && len(tacticsPayload.Tactics) > 0 {
  237. newTacticsTag = tacticsPayload.Tag
  238. }
  239. // Flag the SSH client as having completed its handshake. This
  240. // may reselect traffic rules and starts allowing port forwards.
  241. apiParams := copyBaseAndDialParams(params)
  242. handshakeStateInfo, err := sshClient.setHandshakeState(
  243. handshakeState{
  244. completed: true,
  245. apiProtocol: apiProtocol,
  246. apiParams: apiParams,
  247. domainBytesChecksum: domainBytesChecksum,
  248. establishedTunnelsCount: establishedTunnelsCount,
  249. splitTunnelLookup: splitTunnelLookup,
  250. deviceRegion: deviceRegion,
  251. newTacticsTag: newTacticsTag,
  252. inproxyClientIP: inproxyClientIP,
  253. inproxyClientGeoIPData: inproxyClientGeoIPData,
  254. inproxyRelayLogFields: inproxyRelayLogFields,
  255. },
  256. authorizations)
  257. if err != nil {
  258. return nil, errors.Trace(err)
  259. }
  260. // The log comes _after_ SetClientHandshakeState, in case that call rejects
  261. // the state change (for example, if a second handshake is performed)
  262. //
  263. // The handshake event is no longer shipped to log consumers, so this is
  264. // simply a diagnostic log. Since the "server_tunnel" event includes all
  265. // common API parameters and "handshake_completed" flag, this handshake
  266. // log is mostly redundant and set to debug level.
  267. if IsLogLevelDebug() {
  268. logFields := getRequestLogFields(
  269. "",
  270. sshClient.sessionID,
  271. clientGeoIPData,
  272. handshakeStateInfo.authorizedAccessTypes,
  273. params,
  274. handshakeRequestParams)
  275. log.WithTraceFields(logFields).Debug("handshake")
  276. }
  277. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  278. // Discover new servers
  279. var encodedServerList []string
  280. if !sshClient.getDisableDiscovery() {
  281. clientIP := ""
  282. if sshClient.isInproxyTunnelProtocol {
  283. clientIP = inproxyClientIP
  284. } else if sshClient.peerAddr != nil {
  285. clientIP, _, _ = net.SplitHostPort(sshClient.peerAddr.String())
  286. }
  287. IP := net.ParseIP(clientIP)
  288. if IP == nil {
  289. return nil, errors.TraceNew("invalid client IP")
  290. }
  291. encodedServerList = support.discovery.DiscoverServers(IP)
  292. }
  293. // When the client indicates that it used an out-of-date server entry for
  294. // this connection, return a signed copy of the server entry for the client
  295. // to upgrade to. Out-of-date server entries are either unsigned or missing
  296. // a provider ID. See also: comment in psiphon.doHandshakeRequest.
  297. //
  298. // The missing_server_entry_signature parameter value is a server entry tag,
  299. // which is used to select the correct server entry for servers with multiple
  300. // entries. Identifying the server entries tags instead of server IPs prevents
  301. // an enumeration attack, where a malicious client can abuse this facilty to
  302. // check if an arbitrary IP address is a Psiphon server.
  303. //
  304. // The missing_server_entry_provider_id parameter value is a server entry
  305. // tag.
  306. serverEntryTag, ok := getOptionalStringRequestParam(
  307. params, "missing_server_entry_signature")
  308. if !ok {
  309. // Do not need to check this case if we'll already return the server
  310. // entry due to a missing signature.
  311. serverEntryTag, ok = getOptionalStringRequestParam(
  312. params, "missing_server_entry_provider_id")
  313. }
  314. if ok {
  315. ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
  316. if ok {
  317. encodedServerList = append(encodedServerList, ownServerEntry)
  318. }
  319. }
  320. // PageViewRegexes is obsolete and not used by any tunnel-core clients. In
  321. // the JSON response, return an empty array instead of null for legacy
  322. // clients.
  323. homepages := db.GetRandomizedHomepages(
  324. sponsorID,
  325. clientGeoIPData.Country,
  326. clientGeoIPData.ASN,
  327. deviceRegion,
  328. isMobile)
  329. clientAddress := ""
  330. if sshClient.isInproxyTunnelProtocol {
  331. // ClientAddress not supported for in-proxy tunnel protocols:
  332. //
  333. // - We don't want to return the address of the direct peer, the
  334. // in-proxy proxy;
  335. // - The known port number will correspond to the in-proxy proxy
  336. // source address, not the client;
  337. // - While we assume that the the original client IP from the broker
  338. // is representative for geolocation, an actual direct connection
  339. // to the Psiphon server from the client may route differently and
  340. // use a different IP address.
  341. clientAddress = ""
  342. } else if sshClient.peerAddr != nil {
  343. clientAddress = sshClient.peerAddr.String()
  344. }
  345. var marshaledTacticsPayload []byte
  346. if tacticsPayload != nil {
  347. marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
  348. if err != nil {
  349. return nil, errors.Trace(err)
  350. }
  351. }
  352. handshakeResponse := protocol.HandshakeResponse{
  353. Homepages: homepages,
  354. UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
  355. PageViewRegexes: make([]map[string]string, 0),
  356. HttpsRequestRegexes: httpsRequestRegexes,
  357. EncodedServerList: encodedServerList,
  358. ClientRegion: clientGeoIPData.Country,
  359. ClientAddress: clientAddress,
  360. ServerTimestamp: common.GetCurrentTimestamp(),
  361. ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
  362. TacticsPayload: marshaledTacticsPayload,
  363. UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
  364. DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
  365. SteeringIP: handshakeStateInfo.steeringIP,
  366. Padding: strings.Repeat(" ", pad_response),
  367. }
  368. // TODO: as a future enhancement, pack and CBOR encode this and other API
  369. // responses
  370. responsePayload, err := json.Marshal(handshakeResponse)
  371. if err != nil {
  372. return nil, errors.Trace(err)
  373. }
  374. return responsePayload, nil
  375. }
  376. func doHandshakeInproxyBrokerRelay(
  377. sshClient *sshClient,
  378. clientConnectionID string,
  379. initialRelayPacket []byte) (string, common.LogFields, error) {
  380. connectionID, err := inproxy.IDFromString(clientConnectionID)
  381. if err != nil {
  382. return "", nil, errors.Trace(err)
  383. }
  384. clientIP := ""
  385. var logFields common.LogFields
  386. // This first packet from broker arrives via the client handshake. If
  387. // there is an established, non-expired session, this packet will contain
  388. // the application-level broker report and the relay will complete
  389. // immediately.
  390. relayPacket := initialRelayPacket
  391. for i := 0; i < inproxy.MaxRelayRoundTrips; i++ {
  392. // broker -> server
  393. relayPacket, err = sshClient.sshServer.inproxyBrokerSessions.HandlePacket(
  394. CommonLogger(log),
  395. relayPacket,
  396. connectionID,
  397. func(
  398. brokerVerifiedOriginalClientIP string,
  399. fields common.LogFields) {
  400. // Once the broker report is received, this callback is invoked.
  401. clientIP = brokerVerifiedOriginalClientIP
  402. logFields = fields
  403. })
  404. if err != nil {
  405. if relayPacket == nil {
  406. // If there is an error and no relay packet, the packet is
  407. // invalid. Drop the packet and return an error. Do _not_
  408. // reset the session, otherwise a malicious client could
  409. // interrupt a valid broker/server session with a malformed packet.
  410. return "", nil, errors.Trace(err)
  411. }
  412. // In the case of expired sessions, a reset session token is sent
  413. // to the broker, so this is not a failure condition; the error
  414. // is for logging only. Continue to ship relayPacket.
  415. log.WithTraceFields(LogFields{"error": err}).Warning(
  416. "HandlePacket returned packet and error")
  417. }
  418. if relayPacket == nil {
  419. // The relay is complete; the handler recording the clientIP and
  420. // logFields was invoked.
  421. return clientIP, logFields, nil
  422. }
  423. // server -> broker
  424. // Send an SSH request back to client with next packet for broker;
  425. // then the client relays that to the broker and returns the broker's
  426. // next response in the SSH response.
  427. request := protocol.InproxyRelayRequest{
  428. Packet: relayPacket,
  429. }
  430. requestPayload, err := protocol.CBOREncoding.Marshal(request)
  431. if err != nil {
  432. return "", nil, errors.Trace(err)
  433. }
  434. ok, responsePayload, err := sshClient.sshConn.SendRequest(
  435. protocol.PSIPHON_API_INPROXY_RELAY_REQUEST_NAME,
  436. true,
  437. requestPayload)
  438. if err != nil {
  439. return "", nil, errors.Trace(err)
  440. }
  441. if !ok {
  442. return "", nil, errors.TraceNew("client rejected request")
  443. }
  444. var response protocol.InproxyRelayResponse
  445. err = cbor.Unmarshal(responsePayload, &response)
  446. if err != nil {
  447. return "", nil, errors.Trace(err)
  448. }
  449. relayPacket = response.Packet
  450. }
  451. return "", nil, errors.Tracef("exceeded %d relay round trips", inproxy.MaxRelayRoundTrips)
  452. }
  453. // uniqueUserParams are the connected request parameters which are logged for
  454. // unique_user events.
  455. var uniqueUserParams = append(
  456. []requestParamSpec{
  457. {"last_connected", isLastConnected, 0}},
  458. baseParams...)
  459. var connectedRequestParams = append(
  460. []requestParamSpec{
  461. {"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
  462. uniqueUserParams...)
  463. // updateOnConnectedParamNames are connected request parameters which are
  464. // copied to update data logged with server_tunnel: these fields either only
  465. // ship with or ship newer data with connected requests.
  466. var updateOnConnectedParamNames = append(
  467. []string{
  468. "last_connected",
  469. "establishment_duration",
  470. },
  471. fragmentor.GetUpstreamMetricsNames()...)
  472. // connectedAPIRequestHandler implements the "connected" API request. Clients
  473. // make the connected request once a tunnel connection has been established
  474. // and at least once per 24h for long-running tunnels. The last_connected
  475. // input value, which should be a connected_timestamp output from a previous
  476. // connected response, is used to calculate unique user stats.
  477. // connected_timestamp is truncated as a privacy measure.
  478. func connectedAPIRequestHandler(
  479. support *SupportServices,
  480. sshClient *sshClient,
  481. params common.APIParameters) ([]byte, error) {
  482. err := validateRequestParams(support.Config, params, connectedRequestParams)
  483. if err != nil {
  484. return nil, errors.Trace(err)
  485. }
  486. // Note: unlock before use is only safe as long as referenced sshClient data,
  487. // such as slices in handshakeState, is read-only after initially set.
  488. sshClient.Lock()
  489. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  490. sshClient.Unlock()
  491. lastConnected, _ := getStringRequestParam(params, "last_connected")
  492. // Update, for server_tunnel logging, upstream fragmentor metrics, as the
  493. // client may have performed more upstream fragmentation since the previous
  494. // metrics reported by the handshake request. Also, additional fields that
  495. // are reported only in the connected request are added to server_tunnel
  496. // here.
  497. sshClient.updateAPIParameters(copyUpdateOnConnectedParams(params))
  498. connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  499. // The finest required granularity for unique users is daily. To save space,
  500. // only record a "unique_user" log event when the client's last_connected is
  501. // in the previous day relative to the new connected_timestamp.
  502. logUniqueUser := false
  503. if lastConnected == "None" {
  504. logUniqueUser = true
  505. } else {
  506. t1, _ := time.Parse(time.RFC3339, lastConnected)
  507. year, month, day := t1.Date()
  508. d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  509. t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
  510. year, month, day = t2.Date()
  511. d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
  512. if t1.Before(t2) && d1 != d2 {
  513. logUniqueUser = true
  514. }
  515. }
  516. if logUniqueUser {
  517. log.LogRawFieldsWithTimestamp(
  518. getRequestLogFields(
  519. "unique_user",
  520. sshClient.sessionID,
  521. sshClient.getClientGeoIPData(),
  522. authorizedAccessTypes,
  523. params,
  524. uniqueUserParams))
  525. }
  526. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  527. connectedResponse := protocol.ConnectedResponse{
  528. ConnectedTimestamp: connectedTimestamp,
  529. Padding: strings.Repeat(" ", pad_response),
  530. }
  531. responsePayload, err := json.Marshal(connectedResponse)
  532. if err != nil {
  533. return nil, errors.Trace(err)
  534. }
  535. return responsePayload, nil
  536. }
  537. var statusRequestParams = baseParams
  538. var remoteServerListStatParams = append(
  539. []requestParamSpec{
  540. // Legacy clients don't record the session_id with remote_server_list_stats entries.
  541. {"session_id", isHexDigits, requestParamOptional},
  542. {"client_download_timestamp", isISO8601Date, 0},
  543. {"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  544. {"url", isAnyString, 0},
  545. {"etag", isAnyString, 0},
  546. {"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  547. {"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  548. {"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  549. {"fronting_provider_id", isAnyString, requestParamOptional},
  550. {"meek_dial_address", isDialAddress, requestParamOptional},
  551. {"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  552. {"meek_sni_server_name", isDomain, requestParamOptional},
  553. {"meek_host_header", isHostHeader, requestParamOptional},
  554. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  555. {"user_agent", isAnyString, requestParamOptional},
  556. {"tls_profile", isAnyString, requestParamOptional},
  557. {"tls_version", isAnyString, requestParamOptional},
  558. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  559. },
  560. baseParams...)
  561. // Backwards compatibility case: legacy clients do not include these fields in
  562. // the remote_server_list_stats entries. Use the values from the outer status
  563. // request as an approximation (these values reflect the client at persistent
  564. // stat shipping time, which may differ from the client at persistent stat
  565. // recording time). Note that all but client_build_rev, device_region, and
  566. // device_location are required fields.
  567. var remoteServerListStatBackwardsCompatibilityParamNames = []string{
  568. "propagation_channel_id",
  569. "sponsor_id",
  570. "client_version",
  571. "client_platform",
  572. "client_build_rev",
  573. "device_region",
  574. "device_location",
  575. }
  576. var failedTunnelStatParams = append(
  577. []requestParamSpec{
  578. {"server_entry_tag", isAnyString, requestParamOptional},
  579. {"session_id", isHexDigits, 0},
  580. {"last_connected", isLastConnected, 0},
  581. {"client_failed_timestamp", isISO8601Date, 0},
  582. {"record_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  583. {"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  584. {"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  585. {"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  586. {"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
  587. {"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
  588. {"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
  589. {"tunnel_error", isAnyString, 0}},
  590. baseAndDialParams...)
  591. // statusAPIRequestHandler implements the "status" API request.
  592. // Clients make periodic status requests which deliver client-side
  593. // recorded data transfer and tunnel duration stats.
  594. // Note from psi_web implementation: no input validation on domains;
  595. // any string is accepted (regex transform may result in arbitrary
  596. // string). Stats processor must handle this input with care.
  597. func statusAPIRequestHandler(
  598. support *SupportServices,
  599. sshClient *sshClient,
  600. params common.APIParameters) ([]byte, error) {
  601. err := validateRequestParams(support.Config, params, statusRequestParams)
  602. if err != nil {
  603. return nil, errors.Trace(err)
  604. }
  605. sshClient.Lock()
  606. authorizedAccessTypes := sshClient.handshakeState.authorizedAccessTypes
  607. sshClient.Unlock()
  608. statusData, err := getJSONObjectRequestParam(params, "statusData")
  609. if err != nil {
  610. return nil, errors.Trace(err)
  611. }
  612. // Logs are queued until the input is fully validated. Otherwise, stats
  613. // could be double counted if the client has a bug in its request
  614. // formatting: partial stats would be logged (counted), the request would
  615. // fail, and clients would then resend all the same stats again.
  616. logQueue := make([]LogFields, 0)
  617. // Domain bytes transferred stats
  618. // Older clients may not submit this data
  619. // Clients are expected to send host_bytes/domain_bytes stats only when
  620. // configured to do so in the handshake reponse. Legacy clients may still
  621. // report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
  622. if sshClient.acceptDomainBytes() && statusData["host_bytes"] != nil {
  623. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  624. if err != nil {
  625. return nil, errors.Trace(err)
  626. }
  627. for domain, bytes := range hostBytes {
  628. domainBytesFields := getRequestLogFields(
  629. "domain_bytes",
  630. sshClient.sessionID,
  631. sshClient.getClientGeoIPData(),
  632. authorizedAccessTypes,
  633. params,
  634. statusRequestParams)
  635. domainBytesFields["domain"] = domain
  636. domainBytesFields["bytes"] = bytes
  637. logQueue = append(logQueue, domainBytesFields)
  638. }
  639. }
  640. // Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
  641. // not time-of-recording.
  642. // Remote server list download persistent stats.
  643. // Older clients may not submit this data.
  644. if statusData["remote_server_list_stats"] != nil {
  645. remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
  646. if err != nil {
  647. return nil, errors.Trace(err)
  648. }
  649. for _, remoteServerListStat := range remoteServerListStats {
  650. for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
  651. if _, ok := remoteServerListStat[name]; !ok {
  652. if field, ok := params[name]; ok {
  653. remoteServerListStat[name] = field
  654. }
  655. }
  656. }
  657. err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
  658. if err != nil {
  659. // Occasionally, clients may send corrupt persistent stat data. Do not
  660. // fail the status request, as this will lead to endless retries.
  661. log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
  662. continue
  663. }
  664. remoteServerListFields := getRequestLogFields(
  665. "remote_server_list",
  666. "", // Use the session_id the client recorded with the event
  667. sshClient.getClientGeoIPData(),
  668. authorizedAccessTypes,
  669. remoteServerListStat,
  670. remoteServerListStatParams)
  671. logQueue = append(logQueue, remoteServerListFields)
  672. }
  673. }
  674. // Failed tunnel persistent stats.
  675. // Older clients may not submit this data.
  676. var invalidServerEntryTags map[string]bool
  677. if statusData["failed_tunnel_stats"] != nil {
  678. // Note: no guarantee that PsinetDatabase won't reload between database calls
  679. db := support.PsinetDatabase
  680. invalidServerEntryTags = make(map[string]bool)
  681. failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
  682. if err != nil {
  683. return nil, errors.Trace(err)
  684. }
  685. for _, failedTunnelStat := range failedTunnelStats {
  686. err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
  687. if err != nil {
  688. // Occasionally, clients may send corrupt persistent stat data. Do not
  689. // fail the status request, as this will lead to endless retries.
  690. //
  691. // TODO: trigger pruning if the data corruption indicates corrupt server
  692. // entry storage?
  693. log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
  694. continue
  695. }
  696. failedTunnelFields := getRequestLogFields(
  697. "failed_tunnel",
  698. "", // Use the session_id the client recorded with the event
  699. sshClient.getClientGeoIPData(),
  700. authorizedAccessTypes,
  701. failedTunnelStat,
  702. failedTunnelStatParams)
  703. // Return a list of servers, identified by server entry tag, that are
  704. // invalid and presumed to be deleted. This information is used by clients
  705. // to prune deleted servers from their local datastores and stop attempting
  706. // connections to servers that no longer exist.
  707. //
  708. // This mechanism uses tags instead of server IPs: (a) to prevent an
  709. // enumeration attack, where a malicious client can query the entire IPv4
  710. // range and build a map of the Psiphon network; (b) to deal with recyling
  711. // cases where a server deleted and its IP is reused for a new server with
  712. // a distinct server entry.
  713. //
  714. // IsValidServerEntryTag ensures that the local copy of psinet is not stale
  715. // before returning a negative result, to mitigate accidental pruning.
  716. //
  717. // In addition, when the reported dial port number is 0, flag the server
  718. // entry as invalid to trigger client pruning. This covers a class of
  719. // invalid/semi-functional server entries, found in practice to be stored
  720. // by clients, where some protocol port number has been omitted -- due to
  721. // historical bugs in various server entry handling implementations. When
  722. // missing from a server entry loaded by a client, the port number
  723. // evaluates to 0, the zero value, which is not a valid port number even if
  724. // were not missing.
  725. serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
  726. if ok {
  727. serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
  728. if serverEntryValid {
  729. dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
  730. if err == nil && dialPortNumber == 0 {
  731. serverEntryValid = false
  732. }
  733. }
  734. if !serverEntryValid {
  735. invalidServerEntryTags[serverEntryTag] = true
  736. }
  737. // Add a field to the failed_tunnel log indicating if the server entry is
  738. // valid.
  739. failedTunnelFields["server_entry_valid"] = serverEntryValid
  740. }
  741. // Log failed_tunnel.
  742. logQueue = append(logQueue, failedTunnelFields)
  743. }
  744. }
  745. for _, logItem := range logQueue {
  746. log.LogRawFieldsWithTimestamp(logItem)
  747. }
  748. pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
  749. statusResponse := protocol.StatusResponse{
  750. Padding: strings.Repeat(" ", pad_response),
  751. }
  752. if len(invalidServerEntryTags) > 0 {
  753. statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
  754. i := 0
  755. for tag := range invalidServerEntryTags {
  756. statusResponse.InvalidServerEntryTags[i] = tag
  757. i++
  758. }
  759. }
  760. responsePayload, err := json.Marshal(statusResponse)
  761. if err != nil {
  762. return nil, errors.Trace(err)
  763. }
  764. return responsePayload, nil
  765. }
  766. // clientVerificationAPIRequestHandler is just a compliance stub
  767. // for older Android clients that still send verification requests
  768. func clientVerificationAPIRequestHandler(
  769. _ *SupportServices,
  770. _ *sshClient,
  771. _ common.APIParameters) ([]byte, error) {
  772. return make([]byte, 0), nil
  773. }
  774. var tacticsParams = []requestParamSpec{
  775. {tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  776. {tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
  777. }
  778. var tacticsRequestParams = append(
  779. append(
  780. []requestParamSpec{
  781. {"session_id", isHexDigits, 0}},
  782. tacticsParams...),
  783. baseAndDialParams...)
  784. func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
  785. return func(params common.APIParameters) error {
  786. return validateRequestParams(config, params, tacticsRequestParams)
  787. }
  788. }
  789. func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  790. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  791. logFields := getRequestLogFields(
  792. tactics.TACTICS_METRIC_EVENT_NAME,
  793. "", // Use the session_id the client reported
  794. GeoIPData(geoIPData),
  795. nil, // authorizedAccessTypes are not known yet
  796. params,
  797. tacticsRequestParams)
  798. return common.LogFields(logFields)
  799. }
  800. }
  801. var inproxyBrokerRequestParams = append(
  802. append(
  803. []requestParamSpec{
  804. {"session_id", isHexDigits, 0}},
  805. tacticsParams...),
  806. baseParams...)
  807. func getInproxyBrokerAPIParameterValidator(config *Config) common.APIParameterValidator {
  808. return func(params common.APIParameters) error {
  809. return validateRequestParams(config, params, inproxyBrokerRequestParams)
  810. }
  811. }
  812. func getInproxyBrokerAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
  813. return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
  814. logFields := getRequestLogFields(
  815. "inproxy_broker",
  816. "", // Use the session_id the client reported
  817. GeoIPData(geoIPData),
  818. nil,
  819. params,
  820. inproxyBrokerRequestParams)
  821. return common.LogFields(logFields)
  822. }
  823. }
  824. // requestParamSpec defines a request parameter. Each param is expected to be
  825. // a string, unless requestParamArray is specified, in which case an array of
  826. // strings is expected.
  827. type requestParamSpec struct {
  828. name string
  829. validator func(*Config, string) bool
  830. flags uint32
  831. }
  832. const (
  833. requestParamOptional = 1
  834. requestParamNotLogged = 1 << 1
  835. requestParamArray = 1 << 2
  836. requestParamJSON = 1 << 3
  837. requestParamLogStringAsInt = 1 << 4
  838. requestParamLogStringAsFloat = 1 << 5
  839. requestParamLogStringLengthAsInt = 1 << 6
  840. requestParamLogFlagAsBool = 1 << 7
  841. requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
  842. requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
  843. )
  844. // baseParams are the basic request parameters that are expected for all API
  845. // requests and log events.
  846. var baseParams = []requestParamSpec{
  847. {"propagation_channel_id", isHexDigits, 0},
  848. {"sponsor_id", isHexDigits, 0},
  849. {"client_version", isIntString, requestParamLogStringAsInt},
  850. {"client_platform", isClientPlatform, 0},
  851. {"client_features", isAnyString, requestParamOptional | requestParamArray},
  852. {"client_build_rev", isHexDigits, requestParamOptional},
  853. {"device_region", isAnyString, requestParamOptional},
  854. {"device_location", isGeoHashString, requestParamOptional},
  855. {"network_type", isAnyString, requestParamOptional},
  856. {tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
  857. }
  858. // baseDialParams are the dial parameters, per-tunnel network protocol and
  859. // obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
  860. // tactics.
  861. var baseDialParams = []requestParamSpec{
  862. {"relay_protocol", isRelayProtocol, 0},
  863. {"ssh_client_version", isAnyString, requestParamOptional},
  864. {"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
  865. {"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
  866. {"fronting_provider_id", isAnyString, requestParamOptional},
  867. {"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  868. {"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  869. {"meek_sni_server_name", isDomain, requestParamOptional},
  870. {"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
  871. {"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  872. {"user_agent", isAnyString, requestParamOptional},
  873. {"tls_profile", isAnyString, requestParamOptional},
  874. {"tls_version", isAnyString, requestParamOptional},
  875. {"server_entry_region", isRegionCode, requestParamOptional},
  876. {"server_entry_source", isServerEntrySource, requestParamOptional},
  877. {"server_entry_timestamp", isISO8601Date, requestParamOptional},
  878. {"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  879. {"quic_version", isAnyString, requestParamOptional},
  880. {"quic_dial_sni_address", isAnyString, requestParamOptional},
  881. {"quic_disable_client_path_mtu_discovery", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  882. {"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  883. {"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  884. {"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
  885. {"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  886. {"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
  887. {"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
  888. {"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
  889. {"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  890. {"egress_region", isRegionCode, requestParamOptional},
  891. {"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
  892. {"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
  893. {"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
  894. {"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  895. {"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
  896. {"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
  897. {"meek_redial_probability", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  898. {"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  899. {"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
  900. {"client_bpf", isAnyString, requestParamOptional},
  901. {"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  902. {"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
  903. {"conjure_transport", isAnyString, requestParamOptional},
  904. {"conjure_prefix", isAnyString, requestParamOptional},
  905. {"conjure_stun", isAnyString, requestParamOptional},
  906. {"conjure_empty_packet", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  907. {"conjure_network", isAnyString, requestParamOptional},
  908. {"conjure_port_number", isAnyString, requestParamOptional},
  909. {"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  910. {"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
  911. {"dns_preresolved", isAnyString, requestParamOptional},
  912. {"dns_preferred", isAnyString, requestParamOptional},
  913. {"dns_transform", isAnyString, requestParamOptional},
  914. {"dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  915. {"http_transform", isAnyString, requestParamOptional},
  916. {"seed_transform", isAnyString, requestParamOptional},
  917. {"ossh_prefix", isAnyString, requestParamOptional},
  918. {"tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  919. {"tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
  920. {"tls_ossh_sni_server_name", isDomain, requestParamOptional},
  921. {"tls_ossh_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  922. {"steering_ip", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
  923. }
  924. var inproxyDialParams = []requestParamSpec{
  925. // Both the client and broker send inproxy_connection_id, and the values
  926. // must be the same. The broker's value is logged, so the client's value
  927. // is configured here as requestParamNotLogged.
  928. {"inproxy_connection_id", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  929. {"inproxy_relay_packet", isUnpaddedBase64String, requestParamOptional | requestParamNotLogged},
  930. {"inproxy_broker_is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  931. {"inproxy_broker_transport", isAnyString, requestParamOptional},
  932. {"inproxy_broker_fronting_provider_id", isAnyString, requestParamOptional},
  933. {"inproxy_broker_dial_address", isAnyString, requestParamOptional},
  934. {"inproxy_broker_resolved_ip_address", isAnyString, requestParamOptional},
  935. {"inproxy_broker_sni_server_name", isAnyString, requestParamOptional},
  936. {"inproxy_broker_host_header", isAnyString, requestParamOptional},
  937. {"inproxy_broker_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  938. {"inproxy_broker_user_agent", isAnyString, requestParamOptional},
  939. {"inproxy_broker_tls_profile", isAnyString, requestParamOptional},
  940. {"inproxy_broker_tls_version", isAnyString, requestParamOptional},
  941. {"inproxy_broker_tls_fragmented", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  942. {"inproxy_broker_client_bpf", isAnyString, requestParamOptional},
  943. {"inproxy_broker_upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
  944. {"inproxy_broker_http_transform", isAnyString, requestParamOptional},
  945. {"inproxy_broker_dns_preresolved", isAnyString, requestParamOptional},
  946. {"inproxy_broker_dns_preferred", isAnyString, requestParamOptional},
  947. {"inproxy_broker_dns_transform", isAnyString, requestParamOptional},
  948. {"inproxy_broker_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  949. {"inproxy_webrtc_dns_preresolved", isAnyString, requestParamOptional},
  950. {"inproxy_webrtc_dns_preferred", isAnyString, requestParamOptional},
  951. {"inproxy_webrtc_dns_transform", isAnyString, requestParamOptional},
  952. {"inproxy_webrtc_dns_attempt", isIntString, requestParamOptional | requestParamLogStringAsInt},
  953. {"inproxy_webrtc_stun_server", isAnyString, requestParamOptional},
  954. {"inproxy_webrtc_stun_server_resolved_ip_address", isAnyString, requestParamOptional},
  955. {"inproxy_webrtc_stun_server_RFC5780", isAnyString, requestParamOptional},
  956. {"inproxy_webrtc_stun_server_RFC5780_resolved_ip_address", isAnyString, requestParamOptional},
  957. {"inproxy_webrtc_randomize_dtls", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  958. {"inproxy_webrtc_padded_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  959. {"inproxy_webrtc_padded_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  960. {"inproxy_webrtc_decoy_messages_sent", isIntString, requestParamOptional | requestParamLogStringAsInt},
  961. {"inproxy_webrtc_decoy_messages_received", isIntString, requestParamOptional | requestParamLogStringAsInt},
  962. {"inproxy_webrtc_local_ice_candidate_type", isAnyString, requestParamOptional},
  963. {"inproxy_webrtc_local_ice_candidate_is_initiator", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  964. {"inproxy_webrtc_local_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  965. {"inproxy_webrtc_local_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  966. {"inproxy_webrtc_remote_ice_candidate_type", isAnyString, requestParamOptional},
  967. {"inproxy_webrtc_remote_ice_candidate_is_IPv6", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
  968. {"inproxy_webrtc_remote_ice_candidate_port", isIntString, requestParamOptional | requestParamLogStringAsInt},
  969. }
  970. // baseAndDialParams adds baseDialParams and inproxyDialParams to baseParams.
  971. var baseAndDialParams = append(
  972. append(
  973. append(
  974. []requestParamSpec{},
  975. baseParams...),
  976. baseDialParams...),
  977. inproxyDialParams...)
  978. func validateRequestParams(
  979. config *Config,
  980. params common.APIParameters,
  981. expectedParams []requestParamSpec) error {
  982. for _, expectedParam := range expectedParams {
  983. value := params[expectedParam.name]
  984. if value == nil {
  985. if expectedParam.flags&requestParamOptional != 0 {
  986. continue
  987. }
  988. return errors.Tracef("missing param: %s", expectedParam.name)
  989. }
  990. var err error
  991. switch {
  992. case expectedParam.flags&requestParamArray != 0:
  993. err = validateStringArrayRequestParam(config, expectedParam, value)
  994. case expectedParam.flags&requestParamJSON != 0:
  995. // No validation: the JSON already unmarshalled; the parameter
  996. // user will validate that the JSON contains the expected
  997. // objects/data.
  998. // TODO: without validation, any valid JSON will be logged
  999. // by getRequestLogFields, even if the parameter user validates
  1000. // and rejects the parameter.
  1001. default:
  1002. err = validateStringRequestParam(config, expectedParam, value)
  1003. }
  1004. if err != nil {
  1005. return errors.Trace(err)
  1006. }
  1007. }
  1008. return nil
  1009. }
  1010. // copyBaseAndDialParams makes a copy of the params which includes only
  1011. // the baseAndDialParams.
  1012. func copyBaseAndDialParams(params common.APIParameters) common.APIParameters {
  1013. // Note: not a deep copy; assumes baseSessionAndDialParams values are all
  1014. // scalar types (int, string, etc.)
  1015. paramsCopy := make(common.APIParameters)
  1016. for _, baseParam := range baseAndDialParams {
  1017. value := params[baseParam.name]
  1018. if value == nil {
  1019. continue
  1020. }
  1021. paramsCopy[baseParam.name] = value
  1022. }
  1023. return paramsCopy
  1024. }
  1025. func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
  1026. // Note: not a deep copy
  1027. paramsCopy := make(common.APIParameters)
  1028. for _, name := range updateOnConnectedParamNames {
  1029. value := params[name]
  1030. if value == nil {
  1031. continue
  1032. }
  1033. paramsCopy[name] = value
  1034. }
  1035. return paramsCopy
  1036. }
  1037. func validateStringRequestParam(
  1038. config *Config,
  1039. expectedParam requestParamSpec,
  1040. value interface{}) error {
  1041. strValue, ok := value.(string)
  1042. if !ok {
  1043. return errors.Tracef("unexpected string param type: %s", expectedParam.name)
  1044. }
  1045. if !expectedParam.validator(config, strValue) {
  1046. return errors.Tracef("invalid param: %s: %s", expectedParam.name, strValue)
  1047. }
  1048. return nil
  1049. }
  1050. func validateStringArrayRequestParam(
  1051. config *Config,
  1052. expectedParam requestParamSpec,
  1053. value interface{}) error {
  1054. arrayValue, ok := value.([]interface{})
  1055. if !ok {
  1056. return errors.Tracef("unexpected array param type: %s", expectedParam.name)
  1057. }
  1058. for _, value := range arrayValue {
  1059. err := validateStringRequestParam(config, expectedParam, value)
  1060. if err != nil {
  1061. return errors.Trace(err)
  1062. }
  1063. }
  1064. return nil
  1065. }
  1066. // getRequestLogFields makes LogFields to log the API event following
  1067. // the legacy psi_web and current ELK naming conventions.
  1068. func getRequestLogFields(
  1069. eventName string,
  1070. sessionID string,
  1071. geoIPData GeoIPData,
  1072. authorizedAccessTypes []string,
  1073. params common.APIParameters,
  1074. expectedParams []requestParamSpec) LogFields {
  1075. logFields := make(LogFields)
  1076. // A sessionID is specified for SSH API requests, where the Psiphon server
  1077. // has already received a session ID in the SSH auth payload. In this
  1078. // case, use that session ID.
  1079. //
  1080. // sessionID is "" for other, non-SSH server cases including tactics,
  1081. // in-proxy broker, and client-side store and forward events including
  1082. // remote server list and failed tunnel.
  1083. if sessionID != "" {
  1084. logFields["session_id"] = sessionID
  1085. }
  1086. if eventName != "" {
  1087. logFields["event_name"] = eventName
  1088. }
  1089. geoIPData.SetClientLogFields(logFields)
  1090. if len(authorizedAccessTypes) > 0 {
  1091. logFields["authorized_access_types"] = authorizedAccessTypes
  1092. }
  1093. if params == nil {
  1094. return logFields
  1095. }
  1096. for _, expectedParam := range expectedParams {
  1097. if expectedParam.flags&requestParamNotLogged != 0 {
  1098. continue
  1099. }
  1100. var tunnelProtocol string
  1101. if value, ok := params["relay_protocol"]; ok {
  1102. tunnelProtocol, _ = value.(string)
  1103. }
  1104. if expectedParam.flags&requestParamLogOnlyForFrontedMeekOrConjure != 0 &&
  1105. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) &&
  1106. !protocol.TunnelProtocolUsesConjure(tunnelProtocol) {
  1107. continue
  1108. }
  1109. if expectedParam.flags&requestParamNotLoggedForUnfrontedMeekNonTransformedHeader != 0 &&
  1110. protocol.TunnelProtocolUsesMeek(tunnelProtocol) &&
  1111. !protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  1112. // Non-HTTP unfronted meek protocols never tranform the host header.
  1113. if protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  1114. continue
  1115. }
  1116. var transformedHostName string
  1117. if value, ok := params["meek_transformed_host_name"]; ok {
  1118. transformedHostName, _ = value.(string)
  1119. }
  1120. if transformedHostName != "1" {
  1121. continue
  1122. }
  1123. }
  1124. value := params[expectedParam.name]
  1125. if value == nil {
  1126. // Special case: older clients don't send this value,
  1127. // so log a default.
  1128. if expectedParam.name == "tunnel_whole_device" {
  1129. value = "0"
  1130. } else {
  1131. // Skip omitted, optional params
  1132. continue
  1133. }
  1134. }
  1135. switch v := value.(type) {
  1136. case string:
  1137. strValue := v
  1138. // Special cases:
  1139. // - Number fields are encoded as integer types.
  1140. // - For ELK performance we record certain domain-or-IP
  1141. // fields as one of two different values based on type;
  1142. // we also omit port from these host:port fields for now.
  1143. // - Boolean fields that come into the api as "1"/"0"
  1144. // must be logged as actual boolean values
  1145. switch expectedParam.name {
  1146. case "meek_dial_address":
  1147. host, _, _ := net.SplitHostPort(strValue)
  1148. if isIPAddress(nil, host) {
  1149. logFields["meek_dial_ip_address"] = host
  1150. } else {
  1151. logFields["meek_dial_domain"] = host
  1152. }
  1153. case "upstream_proxy_type":
  1154. // Submitted value could be e.g., "SOCKS5" or "socks5"; log lowercase
  1155. logFields[expectedParam.name] = strings.ToLower(strValue)
  1156. case tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME:
  1157. // Due to a client bug, clients may deliever an incorrect ""
  1158. // value for speed_test_samples via the web API protocol. Omit
  1159. // the field in this case.
  1160. case "tunnel_error":
  1161. // net/url.Error, returned from net/url.Parse, contains the original input
  1162. // URL, which may contain PII. New clients strip this out by using
  1163. // common.SafeParseURL. Legacy clients will still send the full error
  1164. // message, so strip it out here. The target substring should be unique to
  1165. // legacy clients.
  1166. target := "upstreamproxy error: proxyURI url.Parse: parse "
  1167. index := strings.Index(strValue, target)
  1168. if index != -1 {
  1169. strValue = strValue[:index+len(target)] + "<redacted>"
  1170. }
  1171. logFields[expectedParam.name] = strValue
  1172. default:
  1173. if expectedParam.flags&requestParamLogStringAsInt != 0 {
  1174. intValue, _ := strconv.Atoi(strValue)
  1175. logFields[expectedParam.name] = intValue
  1176. } else if expectedParam.flags&requestParamLogStringAsFloat != 0 {
  1177. floatValue, _ := strconv.ParseFloat(strValue, 64)
  1178. logFields[expectedParam.name] = floatValue
  1179. } else if expectedParam.flags&requestParamLogStringLengthAsInt != 0 {
  1180. logFields[expectedParam.name] = len(strValue)
  1181. } else if expectedParam.flags&requestParamLogFlagAsBool != 0 {
  1182. // Submitted value could be "0" or "1"
  1183. // "0" and non "0"/"1" values should be transformed to false
  1184. // "1" should be transformed to true
  1185. if strValue == "1" {
  1186. logFields[expectedParam.name] = true
  1187. } else {
  1188. logFields[expectedParam.name] = false
  1189. }
  1190. } else {
  1191. logFields[expectedParam.name] = strValue
  1192. }
  1193. }
  1194. case []interface{}:
  1195. if expectedParam.name == tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME {
  1196. logFields[expectedParam.name] = makeSpeedTestSamplesLogField(v)
  1197. } else {
  1198. logFields[expectedParam.name] = v
  1199. }
  1200. default:
  1201. logFields[expectedParam.name] = v
  1202. }
  1203. }
  1204. return logFields
  1205. }
  1206. // makeSpeedTestSamplesLogField renames the tactics.SpeedTestSample json tag
  1207. // fields to more verbose names for metrics.
  1208. func makeSpeedTestSamplesLogField(samples []interface{}) []interface{} {
  1209. // TODO: use reflection and add additional tags, e.g.,
  1210. // `json:"s" log:"timestamp"` to remove hard-coded
  1211. // tag value dependency?
  1212. logSamples := make([]interface{}, len(samples))
  1213. for i, sample := range samples {
  1214. logSample := make(map[string]interface{})
  1215. if m, ok := sample.(map[string]interface{}); ok {
  1216. for k, v := range m {
  1217. logK := k
  1218. switch k {
  1219. case "s":
  1220. logK = "timestamp"
  1221. case "r":
  1222. logK = "server_region"
  1223. case "p":
  1224. logK = "relay_protocol"
  1225. case "t":
  1226. logK = "round_trip_time_ms"
  1227. case "u":
  1228. logK = "bytes_up"
  1229. case "d":
  1230. logK = "bytes_down"
  1231. }
  1232. logSample[logK] = v
  1233. }
  1234. }
  1235. logSamples[i] = logSample
  1236. }
  1237. return logSamples
  1238. }
  1239. func getOptionalStringRequestParam(params common.APIParameters, name string) (string, bool) {
  1240. if params[name] == nil {
  1241. return "", false
  1242. }
  1243. value, ok := params[name].(string)
  1244. if !ok {
  1245. return "", false
  1246. }
  1247. return value, true
  1248. }
  1249. func getStringRequestParam(params common.APIParameters, name string) (string, error) {
  1250. if params[name] == nil {
  1251. return "", errors.Tracef("missing param: %s", name)
  1252. }
  1253. value, ok := params[name].(string)
  1254. if !ok {
  1255. return "", errors.Tracef("invalid param: %s", name)
  1256. }
  1257. return value, nil
  1258. }
  1259. func getIntStringRequestParam(params common.APIParameters, name string) (int, error) {
  1260. if params[name] == nil {
  1261. return 0, errors.Tracef("missing param: %s", name)
  1262. }
  1263. valueStr, ok := params[name].(string)
  1264. if !ok {
  1265. return 0, errors.Tracef("invalid param: %s", name)
  1266. }
  1267. value, err := strconv.Atoi(valueStr)
  1268. if !ok {
  1269. return 0, errors.Trace(err)
  1270. }
  1271. return value, nil
  1272. }
  1273. func getBoolStringRequestParam(params common.APIParameters, name string) (bool, error) {
  1274. if params[name] == nil {
  1275. return false, errors.Tracef("missing param: %s", name)
  1276. }
  1277. valueStr, ok := params[name].(string)
  1278. if !ok {
  1279. return false, errors.Tracef("invalid param: %s", name)
  1280. }
  1281. if valueStr == "1" {
  1282. return true, nil
  1283. }
  1284. return false, nil
  1285. }
  1286. func getPaddingSizeRequestParam(params common.APIParameters, name string) (int, error) {
  1287. value, err := getIntStringRequestParam(params, name)
  1288. if err != nil {
  1289. return 0, errors.Trace(err)
  1290. }
  1291. if value < 0 {
  1292. value = 0
  1293. }
  1294. if value > PADDING_MAX_BYTES {
  1295. value = PADDING_MAX_BYTES
  1296. }
  1297. return int(value), nil
  1298. }
  1299. func getJSONObjectRequestParam(params common.APIParameters, name string) (common.APIParameters, error) {
  1300. if params[name] == nil {
  1301. return nil, errors.Tracef("missing param: %s", name)
  1302. }
  1303. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1304. value, ok := params[name].(map[string]interface{})
  1305. if !ok {
  1306. return nil, errors.Tracef("invalid param: %s", name)
  1307. }
  1308. return common.APIParameters(value), nil
  1309. }
  1310. func getJSONObjectArrayRequestParam(params common.APIParameters, name string) ([]common.APIParameters, error) {
  1311. if params[name] == nil {
  1312. return nil, errors.Tracef("missing param: %s", name)
  1313. }
  1314. value, ok := params[name].([]interface{})
  1315. if !ok {
  1316. return nil, errors.Tracef("invalid param: %s", name)
  1317. }
  1318. result := make([]common.APIParameters, len(value))
  1319. for i, item := range value {
  1320. // Note: generic unmarshal of JSON produces map[string]interface{}, not common.APIParameters
  1321. resultItem, ok := item.(map[string]interface{})
  1322. if !ok {
  1323. return nil, errors.Tracef("invalid param: %s", name)
  1324. }
  1325. result[i] = common.APIParameters(resultItem)
  1326. }
  1327. return result, nil
  1328. }
  1329. func getMapStringInt64RequestParam(params common.APIParameters, name string) (map[string]int64, error) {
  1330. if params[name] == nil {
  1331. return nil, errors.Tracef("missing param: %s", name)
  1332. }
  1333. // TODO: can't use common.APIParameters type?
  1334. value, ok := params[name].(map[string]interface{})
  1335. if !ok {
  1336. return nil, errors.Tracef("invalid param: %s", name)
  1337. }
  1338. result := make(map[string]int64)
  1339. for k, v := range value {
  1340. numValue, ok := v.(float64)
  1341. if !ok {
  1342. return nil, errors.Tracef("invalid param: %s", name)
  1343. }
  1344. result[k] = int64(numValue)
  1345. }
  1346. return result, nil
  1347. }
  1348. func getStringArrayRequestParam(params common.APIParameters, name string) ([]string, error) {
  1349. if params[name] == nil {
  1350. return nil, errors.Tracef("missing param: %s", name)
  1351. }
  1352. switch value := params[name].(type) {
  1353. case []string:
  1354. return value, nil
  1355. case []interface{}:
  1356. // JSON unmarshaling may decode the parameter as []interface{}.
  1357. result := make([]string, len(value))
  1358. for i, v := range value {
  1359. strValue, ok := v.(string)
  1360. if !ok {
  1361. return nil, errors.Tracef("invalid param: %s", name)
  1362. }
  1363. result[i] = strValue
  1364. }
  1365. return result, nil
  1366. default:
  1367. return nil, errors.Tracef("invalid param: %s", name)
  1368. }
  1369. }
  1370. // Normalize reported client platform. Android clients, for example, report
  1371. // OS version, rooted status, and Google Play build status in the clientPlatform
  1372. // string along with "Android".
  1373. func normalizeClientPlatform(clientPlatform string) string {
  1374. if strings.Contains(strings.ToLower(clientPlatform), strings.ToLower(CLIENT_PLATFORM_ANDROID)) {
  1375. return CLIENT_PLATFORM_ANDROID
  1376. } else if strings.HasPrefix(clientPlatform, CLIENT_PLATFORM_IOS) {
  1377. return CLIENT_PLATFORM_IOS
  1378. }
  1379. return CLIENT_PLATFORM_WINDOWS
  1380. }
  1381. func isAnyString(config *Config, value string) bool {
  1382. return true
  1383. }
  1384. func isMobileClientPlatform(clientPlatform string) bool {
  1385. normalizedClientPlatform := normalizeClientPlatform(clientPlatform)
  1386. return normalizedClientPlatform == CLIENT_PLATFORM_ANDROID ||
  1387. normalizedClientPlatform == CLIENT_PLATFORM_IOS
  1388. }
  1389. // Input validators follow the legacy validations rules in psi_web.
  1390. func isHexDigits(_ *Config, value string) bool {
  1391. // Allows both uppercase in addition to lowercase, for legacy support.
  1392. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1393. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  1394. })
  1395. }
  1396. func isBase64String(_ *Config, value string) bool {
  1397. _, err := base64.StdEncoding.DecodeString(value)
  1398. return err == nil
  1399. }
  1400. func isUnpaddedBase64String(_ *Config, value string) bool {
  1401. _, err := base64.RawStdEncoding.DecodeString(value)
  1402. return err == nil
  1403. }
  1404. func isDigits(_ *Config, value string) bool {
  1405. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1406. return c < '0' || c > '9'
  1407. })
  1408. }
  1409. func isIntString(_ *Config, value string) bool {
  1410. _, err := strconv.Atoi(value)
  1411. return err == nil
  1412. }
  1413. func isFloatString(_ *Config, value string) bool {
  1414. _, err := strconv.ParseFloat(value, 64)
  1415. return err == nil
  1416. }
  1417. func isClientPlatform(_ *Config, value string) bool {
  1418. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1419. // Note: stricter than psi_web's Python string.whitespace
  1420. return unicode.Is(unicode.White_Space, c)
  1421. })
  1422. }
  1423. func isRelayProtocol(_ *Config, value string) bool {
  1424. return common.Contains(protocol.SupportedTunnelProtocols, value)
  1425. }
  1426. func isBooleanFlag(_ *Config, value string) bool {
  1427. return value == "0" || value == "1"
  1428. }
  1429. func isUpstreamProxyType(_ *Config, value string) bool {
  1430. value = strings.ToLower(value)
  1431. return value == "http" || value == "socks5" || value == "socks4a"
  1432. }
  1433. func isRegionCode(_ *Config, value string) bool {
  1434. if len(value) != 2 {
  1435. return false
  1436. }
  1437. return -1 == strings.IndexFunc(value, func(c rune) bool {
  1438. return c < 'A' || c > 'Z'
  1439. })
  1440. }
  1441. func isDialAddress(_ *Config, value string) bool {
  1442. // "<host>:<port>", where <host> is a domain or IP address
  1443. parts := strings.Split(value, ":")
  1444. if len(parts) != 2 {
  1445. return false
  1446. }
  1447. if !isIPAddress(nil, parts[0]) && !isDomain(nil, parts[0]) {
  1448. return false
  1449. }
  1450. if !isDigits(nil, parts[1]) {
  1451. return false
  1452. }
  1453. _, err := strconv.Atoi(parts[1])
  1454. if err != nil {
  1455. return false
  1456. }
  1457. // Allow port numbers outside [0,65535] to accommodate failed_tunnel cases.
  1458. return true
  1459. }
  1460. func isIPAddress(_ *Config, value string) bool {
  1461. return net.ParseIP(value) != nil
  1462. }
  1463. var isDomainRegex = regexp.MustCompile(`[a-zA-Z\d-]{1,63}$`)
  1464. func isDomain(_ *Config, value string) bool {
  1465. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  1466. //
  1467. // "ensures that each segment
  1468. // * contains at least one character and a maximum of 63 characters
  1469. // * consists only of allowed characters
  1470. // * doesn't begin or end with a hyphen"
  1471. //
  1472. if len(value) > 255 {
  1473. return false
  1474. }
  1475. value = strings.TrimSuffix(value, ".")
  1476. for _, part := range strings.Split(value, ".") {
  1477. // Note: regexp doesn't support the following Perl expression which
  1478. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  1479. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  1480. return false
  1481. }
  1482. if !isDomainRegex.Match([]byte(part)) {
  1483. return false
  1484. }
  1485. }
  1486. return true
  1487. }
  1488. func isHostHeader(_ *Config, value string) bool {
  1489. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  1490. if strings.Contains(value, ":") {
  1491. return isDialAddress(nil, value)
  1492. }
  1493. return isIPAddress(nil, value) || isDomain(nil, value)
  1494. }
  1495. func isServerEntrySource(_ *Config, value string) bool {
  1496. return common.Contains(protocol.SupportedServerEntrySources, value)
  1497. }
  1498. var isISO8601DateRegex = regexp.MustCompile(
  1499. `(?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})))`)
  1500. func isISO8601Date(_ *Config, value string) bool {
  1501. return isISO8601DateRegex.Match([]byte(value))
  1502. }
  1503. func isLastConnected(_ *Config, value string) bool {
  1504. return value == "None" || isISO8601Date(nil, value)
  1505. }
  1506. const geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
  1507. func isGeoHashString(_ *Config, value string) bool {
  1508. // Verify that the string is between 1 and 12 characters long
  1509. // and contains only characters from the geohash alphabet.
  1510. if len(value) < 1 || len(value) > 12 {
  1511. return false
  1512. }
  1513. for _, c := range value {
  1514. if strings.Index(geohashAlphabet, string(c)) == -1 {
  1515. return false
  1516. }
  1517. }
  1518. return true
  1519. }