serverEntry.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. * Copyright (c) 2015, 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 protocol
  20. import (
  21. "bufio"
  22. "bytes"
  23. "encoding/hex"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "io"
  28. "net"
  29. "strings"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. // ServerEntry represents a Psiphon server. It contains information
  33. // about how to establish a tunnel connection to the server through
  34. // several protocols. Server entries are JSON records downloaded from
  35. // various sources.
  36. type ServerEntry struct {
  37. IpAddress string `json:"ipAddress"`
  38. WebServerPort string `json:"webServerPort"` // not an int
  39. WebServerSecret string `json:"webServerSecret"`
  40. WebServerCertificate string `json:"webServerCertificate"`
  41. SshPort int `json:"sshPort"`
  42. SshUsername string `json:"sshUsername"`
  43. SshPassword string `json:"sshPassword"`
  44. SshHostKey string `json:"sshHostKey"`
  45. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  46. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort"`
  47. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  48. Capabilities []string `json:"capabilities"`
  49. Region string `json:"region"`
  50. MeekServerPort int `json:"meekServerPort"`
  51. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  52. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  53. MeekFrontingHost string `json:"meekFrontingHost"`
  54. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  55. MeekFrontingDomain string `json:"meekFrontingDomain"`
  56. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  57. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  58. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  59. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey"`
  60. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey"`
  61. ConfigurationVersion int `json:"configurationVersion"`
  62. // These local fields are not expected to be present in downloaded server
  63. // entries. They are added by the client to record and report stats about
  64. // how and when server entries are obtained.
  65. LocalSource string `json:"localSource"`
  66. LocalTimestamp string `json:"localTimestamp"`
  67. }
  68. // ServerEntryFields is an alternate representation of ServerEntry which
  69. // enables future compatibility when unmarshaling and persisting new server
  70. // entries which may contain new, unrecognized fields not in the ServerEntry
  71. // type for a particular client version.
  72. //
  73. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  74. // types, unrecognized fields are discarded. When unmarshaled to
  75. // ServerEntryFields, unrecognized fields are retained and may be persisted
  76. // and available when the client is upgraded and unmarshals to an updated
  77. // ServerEntry type.
  78. type ServerEntryFields map[string]interface{}
  79. func (fields ServerEntryFields) GetIPAddress() string {
  80. ipAddress, ok := fields["ipAddress"]
  81. if !ok {
  82. return ""
  83. }
  84. ipAddressStr, ok := ipAddress.(string)
  85. if !ok {
  86. return ""
  87. }
  88. return ipAddressStr
  89. }
  90. func (fields ServerEntryFields) GetConfigurationVersion() int {
  91. configurationVersion, ok := fields["configurationVersion"]
  92. if !ok {
  93. return 0
  94. }
  95. configurationVersionInt, ok := configurationVersion.(int)
  96. if !ok {
  97. return 0
  98. }
  99. return configurationVersionInt
  100. }
  101. func (fields ServerEntryFields) SetLocalSource(source string) {
  102. fields["localSource"] = source
  103. }
  104. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  105. fields["localTimestamp"] = timestamp
  106. }
  107. // GetCapability returns the server capability corresponding
  108. // to the tunnel protocol.
  109. func GetCapability(protocol string) string {
  110. return strings.TrimSuffix(protocol, "-OSSH")
  111. }
  112. // GetTacticsCapability returns the server tactics capability
  113. // corresponding to the tunnel protocol.
  114. func GetTacticsCapability(protocol string) string {
  115. return GetCapability(protocol) + "-TACTICS"
  116. }
  117. // SupportsProtocol returns true if and only if the ServerEntry has
  118. // the necessary capability to support the specified tunnel protocol.
  119. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  120. requiredCapability := GetCapability(protocol)
  121. return common.Contains(serverEntry.Capabilities, requiredCapability)
  122. }
  123. // GetSupportedProtocols returns a list of tunnel protocols supported
  124. // by the ServerEntry's capabilities.
  125. func (serverEntry *ServerEntry) GetSupportedProtocols(
  126. useUpstreamProxy bool,
  127. limitTunnelProtocols []string,
  128. impairedTunnelProtocols []string,
  129. excludeIntensive bool) []string {
  130. supportedProtocols := make([]string, 0)
  131. for _, protocol := range SupportedTunnelProtocols {
  132. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  133. continue
  134. }
  135. if len(limitTunnelProtocols) > 0 {
  136. if !common.Contains(limitTunnelProtocols, protocol) {
  137. continue
  138. }
  139. } else {
  140. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  141. continue
  142. }
  143. }
  144. if len(impairedTunnelProtocols) > 0 &&
  145. common.Contains(impairedTunnelProtocols, protocol) {
  146. continue
  147. }
  148. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  149. continue
  150. }
  151. if serverEntry.SupportsProtocol(protocol) {
  152. supportedProtocols = append(supportedProtocols, protocol)
  153. }
  154. }
  155. return supportedProtocols
  156. }
  157. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  158. // supported by the ServerEntry's capabilities, that may be used
  159. // for tactics requests.
  160. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  161. supportedProtocols := make([]string, 0)
  162. for _, protocol := range SupportedTunnelProtocols {
  163. if !TunnelProtocolUsesMeek(protocol) {
  164. continue
  165. }
  166. requiredCapability := GetTacticsCapability(protocol)
  167. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  168. continue
  169. }
  170. supportedProtocols = append(supportedProtocols, protocol)
  171. }
  172. return supportedProtocols
  173. }
  174. // SupportsSSHAPIRequests returns true when the server supports
  175. // SSH API requests.
  176. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  177. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  178. }
  179. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  180. ports := make([]string, 0)
  181. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  182. // Server-side configuration quirk: there's a port forward from
  183. // port 443 to the web server, which we can try, except on servers
  184. // running FRONTED_MEEK, which listens on port 443.
  185. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  186. ports = append(ports, "443")
  187. }
  188. ports = append(ports, serverEntry.WebServerPort)
  189. }
  190. return ports
  191. }
  192. // EncodeServerEntry returns a string containing the encoding of
  193. // a ServerEntry following Psiphon conventions.
  194. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  195. serverEntryContents, err := json.Marshal(serverEntry)
  196. if err != nil {
  197. return "", common.ContextError(err)
  198. }
  199. return hex.EncodeToString([]byte(fmt.Sprintf(
  200. "%s %s %s %s %s",
  201. serverEntry.IpAddress,
  202. serverEntry.WebServerPort,
  203. serverEntry.WebServerSecret,
  204. serverEntry.WebServerCertificate,
  205. serverEntryContents))), nil
  206. }
  207. // DecodeServerEntry extracts a server entry from the encoding
  208. // used by remote server lists and Psiphon server handshake requests.
  209. //
  210. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  211. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  212. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  213. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  214. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  215. // should be a RFC 3339 formatted string. These local fields are stored with the
  216. // server entry and reported to the server as stats (a coarse granularity timestamp
  217. // is reported).
  218. func DecodeServerEntry(
  219. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  220. serverEntry := new(ServerEntry)
  221. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  222. if err != nil {
  223. return nil, common.ContextError(err)
  224. }
  225. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  226. serverEntry.LocalSource = serverEntrySource
  227. serverEntry.LocalTimestamp = timestamp
  228. return serverEntry, nil
  229. }
  230. // DecodeServerEntryFields extracts an encoded server entry into a
  231. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  232. // not in ServerEntry are retained in the ServerEntryFields.
  233. func DecodeServerEntryFields(
  234. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  235. serverEntryFields := make(ServerEntryFields)
  236. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  237. if err != nil {
  238. return nil, common.ContextError(err)
  239. }
  240. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  241. serverEntryFields.SetLocalSource(serverEntrySource)
  242. serverEntryFields.SetLocalTimestamp(timestamp)
  243. return serverEntryFields, nil
  244. }
  245. func decodeServerEntry(
  246. encodedServerEntry, timestamp, serverEntrySource string,
  247. target interface{}) error {
  248. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  249. if err != nil {
  250. return common.ContextError(err)
  251. }
  252. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  253. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  254. if len(fields) != 5 {
  255. return common.ContextError(errors.New("invalid encoded server entry"))
  256. }
  257. err = json.Unmarshal(fields[4], target)
  258. if err != nil {
  259. return common.ContextError(err)
  260. }
  261. return nil
  262. }
  263. // ValidateServerEntryFields checks for malformed server entries.
  264. // Currently, it checks for a valid ipAddress. This is important since
  265. // the IP address is the key used to store/lookup the server entry.
  266. // TODO: validate more fields?
  267. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  268. ipAddress := serverEntryFields.GetIPAddress()
  269. if net.ParseIP(ipAddress) == nil {
  270. return common.ContextError(
  271. fmt.Errorf("server entry has invalid ipAddress: %s", ipAddress))
  272. }
  273. return nil
  274. }
  275. // DecodeServerEntryList extracts server entries from the list encoding
  276. // used by remote server lists and Psiphon server handshake requests.
  277. // Each server entry is validated and invalid entries are skipped.
  278. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  279. func DecodeServerEntryList(
  280. encodedServerEntryList, timestamp,
  281. serverEntrySource string) ([]ServerEntryFields, error) {
  282. serverEntries := make([]ServerEntryFields, 0)
  283. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  284. if len(encodedServerEntry) == 0 {
  285. continue
  286. }
  287. // TODO: skip this entry and continue if can't decode?
  288. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  289. if err != nil {
  290. return nil, common.ContextError(err)
  291. }
  292. if ValidateServerEntryFields(serverEntryFields) != nil {
  293. // Skip this entry and continue with the next one
  294. // TODO: invoke a logging callback
  295. continue
  296. }
  297. serverEntries = append(serverEntries, serverEntryFields)
  298. }
  299. return serverEntries, nil
  300. }
  301. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  302. // operation, loading only one server entry into memory at a time.
  303. type StreamingServerEntryDecoder struct {
  304. scanner *bufio.Scanner
  305. timestamp string
  306. serverEntrySource string
  307. }
  308. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  309. func NewStreamingServerEntryDecoder(
  310. encodedServerEntryListReader io.Reader,
  311. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  312. return &StreamingServerEntryDecoder{
  313. scanner: bufio.NewScanner(encodedServerEntryListReader),
  314. timestamp: timestamp,
  315. serverEntrySource: serverEntrySource,
  316. }
  317. }
  318. // Next reads and decodes, and validates the next server entry from the
  319. // input stream, returning a nil server entry when the stream is complete.
  320. //
  321. // Limitations:
  322. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  323. // the default buffer size which this decoder uses. This is 64K.
  324. // - DecodeServerEntry is called on each encoded server entry line, which
  325. // will allocate memory to hex decode and JSON deserialze the server
  326. // entry. As this is not presently reusing a fixed buffer, each call
  327. // will allocate additional memory; garbage collection is necessary to
  328. // reclaim that memory for reuse for the next server entry.
  329. //
  330. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  331. for {
  332. if !decoder.scanner.Scan() {
  333. return nil, common.ContextError(decoder.scanner.Err())
  334. }
  335. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  336. // TODO: skip this entry and continue if can't decode?
  337. serverEntryFields, err := DecodeServerEntryFields(
  338. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  339. if err != nil {
  340. return nil, common.ContextError(err)
  341. }
  342. if ValidateServerEntryFields(serverEntryFields) != nil {
  343. // Skip this entry and continue with the next one
  344. // TODO: invoke a logging callback
  345. continue
  346. }
  347. return serverEntryFields, nil
  348. }
  349. }