api.go 61 KB

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