api.go 42 KB

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