api.go 21 KB

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