api.go 61 KB

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