api.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. "errors"
  24. "fmt"
  25. "net"
  26. "regexp"
  27. "strconv"
  28. "strings"
  29. "unicode"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. )
  32. const MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
  33. type requestJSONObject map[string]interface{}
  34. // sshAPIRequestHandler routes Psiphon API requests transported as
  35. // JSON objects via the SSH request mechanism.
  36. //
  37. // The API request handlers, handshakeAPIRequestHandler, etc., are
  38. // reused by webServer which offers the Psiphon API via web transport.
  39. //
  40. // The API request parameters and event log values follow the legacy
  41. // psi_web protocol and naming conventions. The API is compatible all
  42. // tunnel-core clients but are not backwards compatible with older
  43. // clients.
  44. //
  45. func sshAPIRequestHandler(
  46. config *Config, geoIPData GeoIPData, name string, requestPayload []byte) ([]byte, error) {
  47. // Note: for SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
  48. // by max SSH reqest packet size.
  49. var params requestJSONObject
  50. err := json.Unmarshal(requestPayload, &params)
  51. if err != nil {
  52. return nil, psiphon.ContextError(err)
  53. }
  54. switch name {
  55. case psiphon.SERVER_API_HANDSHAKE_REQUEST_NAME:
  56. return handshakeAPIRequestHandler(config, geoIPData, params)
  57. case psiphon.SERVER_API_CONNECTED_REQUEST_NAME:
  58. return connectedAPIRequestHandler(config, geoIPData, params)
  59. case psiphon.SERVER_API_STATUS_REQUEST_NAME:
  60. return statusAPIRequestHandler(config, geoIPData, params)
  61. case psiphon.SERVER_API_CLIENT_VERIFICATION_REQUEST_NAME:
  62. return clientVerificationAPIRequestHandler(config, geoIPData, params)
  63. }
  64. return nil, psiphon.ContextError(fmt.Errorf("invalid request name: %s", name))
  65. }
  66. // handshakeAPIRequestHandler implements the "handshake" API request.
  67. // Clients make the handshake immediately after establishing a tunnel
  68. // connection; the response tells the client what homepage to open, what
  69. // stats to record, etc.
  70. func handshakeAPIRequestHandler(
  71. config *Config, geoIPData GeoIPData, params requestJSONObject) ([]byte, error) {
  72. // Note: ignoring "known_servers" params
  73. err := validateRequestParams(config, params, baseRequestParams)
  74. if err != nil {
  75. // TODO: fail2ban?
  76. return nil, psiphon.ContextError(errors.New("invalid params"))
  77. }
  78. log.WithContextFields(
  79. getRequestLogFields(
  80. config,
  81. "handshake",
  82. geoIPData,
  83. params,
  84. baseRequestParams)).Info("API event")
  85. // TODO: share struct definition with psiphon/serverApi.go?
  86. // TODO: populate response data using psinet database
  87. var handshakeResponse struct {
  88. Homepages []string `json:"homepages"`
  89. UpgradeClientVersion string `json:"upgrade_client_version"`
  90. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  91. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  92. EncodedServerList []string `json:"encoded_server_list"`
  93. ClientRegion string `json:"client_region"`
  94. ServerTimestamp string `json:"server_timestamp"`
  95. }
  96. handshakeResponse.ServerTimestamp = psiphon.GetCurrentTimestamp()
  97. responsePayload, err := json.Marshal(handshakeResponse)
  98. if err != nil {
  99. return nil, psiphon.ContextError(err)
  100. }
  101. return responsePayload, nil
  102. }
  103. var connectedRequestParams = append(
  104. []requestParamSpec{requestParamSpec{"last_connected", isLastConnected, 0}},
  105. baseRequestParams...)
  106. // connectedAPIRequestHandler implements the "connected" API request.
  107. // Clients make the connected request once a tunnel connection has been
  108. // established and at least once per day. The last_connected input value,
  109. // which should be a connected_timestamp output from a previous connected
  110. // response, is used to calculate unique user stats.
  111. func connectedAPIRequestHandler(
  112. config *Config, geoIPData GeoIPData, params requestJSONObject) ([]byte, error) {
  113. err := validateRequestParams(config, params, connectedRequestParams)
  114. if err != nil {
  115. // TODO: fail2ban?
  116. return nil, psiphon.ContextError(errors.New("invalid params"))
  117. }
  118. log.WithContextFields(
  119. getRequestLogFields(
  120. config,
  121. "connected",
  122. geoIPData,
  123. params,
  124. connectedRequestParams)).Info("API event")
  125. var connectedResponse struct {
  126. ConnectedTimestamp string `json:"connected_timestamp"`
  127. }
  128. connectedResponse.ConnectedTimestamp =
  129. psiphon.TruncateTimestampToHour(psiphon.GetCurrentTimestamp())
  130. responsePayload, err := json.Marshal(connectedResponse)
  131. if err != nil {
  132. return nil, psiphon.ContextError(err)
  133. }
  134. return responsePayload, nil
  135. }
  136. var statusRequestParams = append(
  137. []requestParamSpec{requestParamSpec{"connected", isBooleanFlag, 0}},
  138. baseRequestParams...)
  139. // statusAPIRequestHandler implements the "status" API request.
  140. // Clients make periodic status requests which deliver client-side
  141. // recorded data transfer and tunnel duration stats.
  142. func statusAPIRequestHandler(
  143. config *Config, geoIPData GeoIPData, params requestJSONObject) ([]byte, error) {
  144. err := validateRequestParams(config, params, statusRequestParams)
  145. if err != nil {
  146. // TODO: fail2ban?
  147. return nil, psiphon.ContextError(errors.New("invalid params"))
  148. }
  149. statusData, err := getJSONObjectRequestParam(params, "statusData")
  150. if err != nil {
  151. return nil, psiphon.ContextError(err)
  152. }
  153. // Overall bytes transferred stats
  154. bytesTransferred, err := getInt64RequestParam(statusData, "bytes_transferred")
  155. if err != nil {
  156. return nil, psiphon.ContextError(err)
  157. }
  158. bytesTransferredFields := getRequestLogFields(
  159. config, "bytes_transferred", geoIPData, params, statusRequestParams)
  160. bytesTransferredFields["bytes"] = bytesTransferred
  161. log.WithContextFields(bytesTransferredFields).Info("API event")
  162. // Domain bytes transferred stats
  163. hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
  164. if err != nil {
  165. return nil, psiphon.ContextError(err)
  166. }
  167. domainBytesFields := getRequestLogFields(
  168. config, "domain_bytes", geoIPData, params, statusRequestParams)
  169. for domain, bytes := range hostBytes {
  170. domainBytesFields["domain"] = domain
  171. domainBytesFields["bytes"] = bytes
  172. log.WithContextFields(domainBytesFields).Info("API event")
  173. }
  174. // Tunnel duration and bytes transferred stats
  175. tunnelStats, err := getJSONObjectArrayRequestParam(statusData, "tunnel_stats")
  176. if err != nil {
  177. return nil, psiphon.ContextError(err)
  178. }
  179. sessionFields := getRequestLogFields(
  180. config, "session", geoIPData, params, statusRequestParams)
  181. for _, tunnelStat := range tunnelStats {
  182. sessionID, err := getStringRequestParam(tunnelStat, "session_id")
  183. if err != nil {
  184. return nil, psiphon.ContextError(err)
  185. }
  186. sessionFields["session_id"] = sessionID
  187. tunnelNumber, err := getInt64RequestParam(tunnelStat, "tunnel_number")
  188. if err != nil {
  189. return nil, psiphon.ContextError(err)
  190. }
  191. sessionFields["tunnel_number"] = tunnelNumber
  192. tunnelServerIPAddress, err := getStringRequestParam(tunnelStat, "tunnel_server_ip_address")
  193. if err != nil {
  194. return nil, psiphon.ContextError(err)
  195. }
  196. sessionFields["tunnel_server_ip_address"] = tunnelServerIPAddress
  197. serverHandshakeTimestamp, err := getStringRequestParam(tunnelStat, "server_handshake_timestamp")
  198. if err != nil {
  199. return nil, psiphon.ContextError(err)
  200. }
  201. sessionFields["server_handshake_timestamp"] = serverHandshakeTimestamp
  202. duration, err := getInt64RequestParam(tunnelStat, "duration")
  203. if err != nil {
  204. return nil, psiphon.ContextError(err)
  205. }
  206. // Client reports durations in nanoseconds; divide to get to milliseconds
  207. sessionFields["duration"] = duration / 1000000
  208. totalBytesSent, err := getInt64RequestParam(tunnelStat, "total_bytes_sent")
  209. if err != nil {
  210. return nil, psiphon.ContextError(err)
  211. }
  212. sessionFields["total_bytes_sent"] = totalBytesSent
  213. totalBytesReceived, err := getInt64RequestParam(tunnelStat, "total_bytes_received")
  214. if err != nil {
  215. return nil, psiphon.ContextError(err)
  216. }
  217. sessionFields["total_bytes_received"] = totalBytesReceived
  218. log.WithContextFields(sessionFields).Info("API event")
  219. }
  220. return make([]byte, 0), nil
  221. }
  222. // clientVerificationAPIRequestHandler implements the
  223. // "client verification" API request. Clients make the client
  224. // verification request once per tunnel connection. The payload
  225. // attests that client is a legitimate Psiphon client.
  226. func clientVerificationAPIRequestHandler(
  227. config *Config, geoIPData GeoIPData, params requestJSONObject) ([]byte, error) {
  228. err := validateRequestParams(config, params, baseRequestParams)
  229. if err != nil {
  230. // TODO: fail2ban?
  231. return nil, psiphon.ContextError(errors.New("invalid params"))
  232. }
  233. // TODO: implement
  234. return make([]byte, 0), nil
  235. }
  236. type requestParamSpec struct {
  237. name string
  238. validator func(*Config, string) bool
  239. flags int32
  240. }
  241. const (
  242. requestParamOptional = 1
  243. requestParamNotLogged = 2
  244. )
  245. // baseRequestParams is the list of required and optional
  246. // request parameters; derived from COMMON_INPUTS and
  247. // OPTIONAL_COMMON_INPUTS in psi_web.
  248. var baseRequestParams = []requestParamSpec{
  249. requestParamSpec{"server_secret", isServerSecret, requestParamNotLogged},
  250. requestParamSpec{"client_session_id", isHexDigits, 0},
  251. requestParamSpec{"propagation_channel_id", isHexDigits, 0},
  252. requestParamSpec{"sponsor_id", isHexDigits, 0},
  253. requestParamSpec{"client_version", isDigits, 0},
  254. requestParamSpec{"client_platform", isClientPlatform, 0},
  255. requestParamSpec{"relay_protocol", isRelayProtocol, 0},
  256. requestParamSpec{"tunnel_whole_device", isBooleanFlag, 0},
  257. requestParamSpec{"device_region", isRegionCode, requestParamOptional},
  258. requestParamSpec{"meek_dial_address", isDialAddress, requestParamOptional},
  259. requestParamSpec{"meek_resolved_ip_address", isIPAddress, requestParamOptional},
  260. requestParamSpec{"meek_sni_server_name", isDomain, requestParamOptional},
  261. requestParamSpec{"meek_host_header", isHostHeader, requestParamOptional},
  262. requestParamSpec{"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
  263. requestParamSpec{"server_entry_region", isRegionCode, requestParamOptional},
  264. requestParamSpec{"server_entry_source", isServerEntrySource, requestParamOptional},
  265. requestParamSpec{"server_entry_timestamp", isISO8601Date, requestParamOptional},
  266. }
  267. func validateRequestParams(
  268. config *Config,
  269. params requestJSONObject,
  270. expectedParams []requestParamSpec) error {
  271. for _, expectedParam := range expectedParams {
  272. value := params[expectedParam.name]
  273. if value == nil {
  274. if expectedParam.flags&requestParamOptional != 0 {
  275. continue
  276. }
  277. return psiphon.ContextError(
  278. fmt.Errorf("missing required param: %s", expectedParam.name))
  279. }
  280. strValue, ok := value.(string)
  281. if !ok {
  282. return psiphon.ContextError(
  283. fmt.Errorf("unexpected param type: %s", expectedParam.name))
  284. }
  285. if !expectedParam.validator(config, strValue) {
  286. return psiphon.ContextError(
  287. fmt.Errorf("invalid param: %s", expectedParam.name))
  288. }
  289. }
  290. return nil
  291. }
  292. // getRequestLogFields makes LogFields to log the API event following
  293. // the legacy psi_web and current ELK naming conventions.
  294. func getRequestLogFields(
  295. config *Config,
  296. eventName string,
  297. geoIPData GeoIPData,
  298. params requestJSONObject,
  299. expectedParams []requestParamSpec) LogFields {
  300. logFields := make(LogFields)
  301. logFields["event_name"] = eventName
  302. logFields["host_id"] = config.HostID
  303. // In psi_web, the space replacement was done to accommodate space
  304. // delimited logging, which is no longer required; we retain the
  305. // transformation so that stats aggregation isn't impacted.
  306. logFields["client_region"] = strings.Replace(geoIPData.Country, " ", "_", -1)
  307. logFields["client_city"] = strings.Replace(geoIPData.City, " ", "_", -1)
  308. logFields["client_isp"] = strings.Replace(geoIPData.ISP, " ", "_", -1)
  309. for _, expectedParam := range expectedParams {
  310. value := params[expectedParam.name]
  311. if value == nil {
  312. // Skip optional params
  313. continue
  314. }
  315. strValue, ok := value.(string)
  316. if !ok {
  317. // This type assertion should be checked already in
  318. // validateRequestParams, so failure is unexpected.
  319. continue
  320. }
  321. // Special cases:
  322. // - Number fields are encoded as integer types.
  323. // - For ELK performance we record these domain-or-IP
  324. // fields as one of two different values based on type;
  325. // we also omit port from host:port fields for now.
  326. switch expectedParam.name {
  327. case "client_version":
  328. intValue, _ := strconv.Atoi(strValue)
  329. logFields[expectedParam.name] = intValue
  330. case "meek_dial_address":
  331. host, _, _ := net.SplitHostPort(strValue)
  332. if isIPAddress(config, host) {
  333. logFields["meek_dial_ip_address"] = host
  334. } else {
  335. logFields["meek_dial_domain"] = host
  336. }
  337. case "meek_host_header":
  338. host, _, _ := net.SplitHostPort(strValue)
  339. logFields[expectedParam.name] = host
  340. default:
  341. logFields[expectedParam.name] = strValue
  342. }
  343. }
  344. return logFields
  345. }
  346. func getStringRequestParam(params requestJSONObject, name string) (string, error) {
  347. if params[name] == nil {
  348. return "", psiphon.ContextError(errors.New("missing param"))
  349. }
  350. value, ok := params[name].(string)
  351. if !ok {
  352. return "", psiphon.ContextError(errors.New("invalid param"))
  353. }
  354. return value, nil
  355. }
  356. func getInt64RequestParam(params requestJSONObject, name string) (int64, error) {
  357. if params[name] == nil {
  358. return 0, psiphon.ContextError(errors.New("missing param"))
  359. }
  360. value, ok := params[name].(int64)
  361. if !ok {
  362. return 0, psiphon.ContextError(errors.New("invalid param"))
  363. }
  364. return value, nil
  365. }
  366. func getJSONObjectRequestParam(params requestJSONObject, name string) (requestJSONObject, error) {
  367. if params[name] == nil {
  368. return nil, psiphon.ContextError(errors.New("missing param"))
  369. }
  370. value, ok := params[name].(requestJSONObject)
  371. if !ok {
  372. return nil, psiphon.ContextError(errors.New("invalid param"))
  373. }
  374. return value, nil
  375. }
  376. func getJSONObjectArrayRequestParam(params requestJSONObject, name string) ([]requestJSONObject, error) {
  377. if params[name] == nil {
  378. return nil, psiphon.ContextError(errors.New("missing param"))
  379. }
  380. value, ok := params[name].([]requestJSONObject)
  381. if !ok {
  382. return nil, psiphon.ContextError(errors.New("invalid param"))
  383. }
  384. return value, nil
  385. }
  386. func getMapStringInt64RequestParam(params requestJSONObject, name string) (map[string]int64, error) {
  387. if params[name] == nil {
  388. return nil, psiphon.ContextError(errors.New("missing param"))
  389. }
  390. value, ok := params[name].(map[string]int64)
  391. if !ok {
  392. return nil, psiphon.ContextError(errors.New("invalid param"))
  393. }
  394. return value, nil
  395. }
  396. // Input validators follow the legacy validations rules in psi_web.
  397. func isServerSecret(config *Config, value string) bool {
  398. return subtle.ConstantTimeCompare(
  399. []byte(value),
  400. []byte(config.WebServerSecret)) == 1
  401. }
  402. func isHexDigits(_ *Config, value string) bool {
  403. return -1 == strings.IndexFunc(value, func(c rune) bool {
  404. return !unicode.Is(unicode.ASCII_Hex_Digit, c)
  405. })
  406. }
  407. func isDigits(_ *Config, value string) bool {
  408. return -1 == strings.IndexFunc(value, func(c rune) bool {
  409. return c < '0' || c > '9'
  410. })
  411. }
  412. func isClientPlatform(_ *Config, value string) bool {
  413. return -1 == strings.IndexFunc(value, func(c rune) bool {
  414. // Note: stricter than psi_web's Python string.whitespace
  415. return unicode.Is(unicode.White_Space, c)
  416. })
  417. }
  418. func isRelayProtocol(_ *Config, value string) bool {
  419. return psiphon.Contains(psiphon.SupportedTunnelProtocols, value)
  420. }
  421. func isBooleanFlag(_ *Config, value string) bool {
  422. return value == "0" || value == "1"
  423. }
  424. func isRegionCode(_ *Config, value string) bool {
  425. if len(value) != 2 {
  426. return false
  427. }
  428. return -1 == strings.IndexFunc(value, func(c rune) bool {
  429. return c < 'A' || c > 'Z'
  430. })
  431. }
  432. func isDialAddress(config *Config, value string) bool {
  433. // "<host>:<port>", where <host> is a domain or IP address
  434. parts := strings.Split(value, ":")
  435. if len(parts) != 2 {
  436. return false
  437. }
  438. if !isIPAddress(config, parts[0]) && !isDomain(config, parts[0]) {
  439. return false
  440. }
  441. if !isDigits(config, parts[1]) {
  442. return false
  443. }
  444. port, err := strconv.Atoi(parts[1])
  445. if err != nil {
  446. return false
  447. }
  448. return port > 0 && port < 65536
  449. }
  450. func isIPAddress(_ *Config, value string) bool {
  451. return net.ParseIP(value) != nil
  452. }
  453. var isDomainRegex = regexp.MustCompile("[a-zA-Z\\d-]{1,63}$")
  454. func isDomain(_ *Config, value string) bool {
  455. // From: http://stackoverflow.com/questions/2532053/validate-a-hostname-string
  456. //
  457. // "ensures that each segment
  458. // * contains at least one character and a maximum of 63 characters
  459. // * consists only of allowed characters
  460. // * doesn't begin or end with a hyphen"
  461. //
  462. if len(value) > 255 {
  463. return false
  464. }
  465. value = strings.TrimSuffix(value, ".")
  466. for _, part := range strings.Split(value, ".") {
  467. // Note: regexp doesn't support the following Perl expression which
  468. // would check for '-' prefix/suffix: "(?!-)[a-zA-Z\\d-]{1,63}(?<!-)$"
  469. if strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  470. return false
  471. }
  472. if !isDomainRegex.Match([]byte(part)) {
  473. return false
  474. }
  475. }
  476. return true
  477. }
  478. func isHostHeader(config *Config, value string) bool {
  479. // "<host>:<port>", where <host> is a domain or IP address and ":<port>" is optional
  480. if strings.Contains(value, ":") {
  481. return isDialAddress(config, value)
  482. }
  483. return isIPAddress(config, value) || isDomain(config, value)
  484. }
  485. func isServerEntrySource(_ *Config, value string) bool {
  486. return psiphon.Contains(psiphon.SupportedServerEntrySources, value)
  487. }
  488. var isISO8601DateRegex = regexp.MustCompile(
  489. "(?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})))")
  490. func isISO8601Date(_ *Config, value string) bool {
  491. return isISO8601DateRegex.Match([]byte(value))
  492. }
  493. func isLastConnected(config *Config, value string) bool {
  494. return value == "None" || value == "Unknown" || isISO8601Date(config, value)
  495. }