api.go 21 KB

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