api.go 21 KB

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