api.go 21 KB

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