serverEntry.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. // GetCapability returns the server capability corresponding
  69. // to the tunnel protocol.
  70. func GetCapability(protocol string) string {
  71. return strings.TrimSuffix(protocol, "-OSSH")
  72. }
  73. // GetTacticsCapability returns the server tactics capability
  74. // corresponding to the tunnel protocol.
  75. func GetTacticsCapability(protocol string) string {
  76. return GetCapability(protocol) + "-TACTICS"
  77. }
  78. // SupportsProtocol returns true if and only if the ServerEntry has
  79. // the necessary capability to support the specified tunnel protocol.
  80. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  81. requiredCapability := GetCapability(protocol)
  82. return common.Contains(serverEntry.Capabilities, requiredCapability)
  83. }
  84. // GetSupportedProtocols returns a list of tunnel protocols supported
  85. // by the ServerEntry's capabilities.
  86. func (serverEntry *ServerEntry) GetSupportedProtocols(
  87. useUpstreamProxy bool,
  88. limitTunnelProtocols []string,
  89. impairedTunnelProtocols []string,
  90. excludeIntensive bool) []string {
  91. supportedProtocols := make([]string, 0)
  92. for _, protocol := range SupportedTunnelProtocols {
  93. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  94. continue
  95. }
  96. if len(limitTunnelProtocols) > 0 {
  97. if !common.Contains(limitTunnelProtocols, protocol) {
  98. continue
  99. }
  100. } else {
  101. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  102. continue
  103. }
  104. }
  105. if len(impairedTunnelProtocols) > 0 &&
  106. !common.Contains(impairedTunnelProtocols, protocol) {
  107. continue
  108. }
  109. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  110. continue
  111. }
  112. if serverEntry.SupportsProtocol(protocol) {
  113. supportedProtocols = append(supportedProtocols, protocol)
  114. }
  115. }
  116. return supportedProtocols
  117. }
  118. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  119. // supported by the ServerEntry's capabilities, that may be used
  120. // for tactics requests.
  121. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  122. supportedProtocols := make([]string, 0)
  123. for _, protocol := range SupportedTunnelProtocols {
  124. if !TunnelProtocolUsesMeek(protocol) {
  125. continue
  126. }
  127. requiredCapability := GetTacticsCapability(protocol)
  128. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  129. continue
  130. }
  131. supportedProtocols = append(supportedProtocols, protocol)
  132. }
  133. return supportedProtocols
  134. }
  135. // SupportsSSHAPIRequests returns true when the server supports
  136. // SSH API requests.
  137. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  138. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  139. }
  140. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  141. ports := make([]string, 0)
  142. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  143. // Server-side configuration quirk: there's a port forward from
  144. // port 443 to the web server, which we can try, except on servers
  145. // running FRONTED_MEEK, which listens on port 443.
  146. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  147. ports = append(ports, "443")
  148. }
  149. ports = append(ports, serverEntry.WebServerPort)
  150. }
  151. return ports
  152. }
  153. // EncodeServerEntry returns a string containing the encoding of
  154. // a ServerEntry following Psiphon conventions.
  155. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  156. serverEntryContents, err := json.Marshal(serverEntry)
  157. if err != nil {
  158. return "", common.ContextError(err)
  159. }
  160. return hex.EncodeToString([]byte(fmt.Sprintf(
  161. "%s %s %s %s %s",
  162. serverEntry.IpAddress,
  163. serverEntry.WebServerPort,
  164. serverEntry.WebServerSecret,
  165. serverEntry.WebServerCertificate,
  166. serverEntryContents))), nil
  167. }
  168. // DecodeServerEntry extracts server entries from the encoding
  169. // used by remote server lists and Psiphon server handshake requests.
  170. //
  171. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  172. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  173. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  174. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  175. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  176. // should be a RFC 3339 formatted string. These local fields are stored with the
  177. // server entry and reported to the server as stats (a coarse granularity timestamp
  178. // is reported).
  179. func DecodeServerEntry(
  180. encodedServerEntry, timestamp,
  181. serverEntrySource string) (serverEntry *ServerEntry, err error) {
  182. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  183. if err != nil {
  184. return nil, common.ContextError(err)
  185. }
  186. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  187. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  188. if len(fields) != 5 {
  189. return nil, common.ContextError(errors.New("invalid encoded server entry"))
  190. }
  191. serverEntry = new(ServerEntry)
  192. err = json.Unmarshal(fields[4], &serverEntry)
  193. if err != nil {
  194. return nil, common.ContextError(err)
  195. }
  196. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  197. serverEntry.LocalSource = serverEntrySource
  198. serverEntry.LocalTimestamp = timestamp
  199. return serverEntry, nil
  200. }
  201. // ValidateServerEntry checks for malformed server entries.
  202. // Currently, it checks for a valid ipAddress. This is important since
  203. // the IP address is the key used to store/lookup the server entry.
  204. // TODO: validate more fields?
  205. func ValidateServerEntry(serverEntry *ServerEntry) error {
  206. ipAddr := net.ParseIP(serverEntry.IpAddress)
  207. if ipAddr == nil {
  208. return common.ContextError(
  209. fmt.Errorf("server entry has invalid ipAddress: '%s'", serverEntry.IpAddress))
  210. }
  211. return nil
  212. }
  213. // DecodeServerEntryList extracts server entries from the list encoding
  214. // used by remote server lists and Psiphon server handshake requests.
  215. // Each server entry is validated and invalid entries are skipped.
  216. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  217. func DecodeServerEntryList(
  218. encodedServerEntryList, timestamp,
  219. serverEntrySource string) (serverEntries []*ServerEntry, err error) {
  220. serverEntries = make([]*ServerEntry, 0)
  221. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  222. if len(encodedServerEntry) == 0 {
  223. continue
  224. }
  225. // TODO: skip this entry and continue if can't decode?
  226. serverEntry, err := DecodeServerEntry(encodedServerEntry, timestamp, serverEntrySource)
  227. if err != nil {
  228. return nil, common.ContextError(err)
  229. }
  230. if ValidateServerEntry(serverEntry) != nil {
  231. // Skip this entry and continue with the next one
  232. // TODO: invoke a logging callback
  233. continue
  234. }
  235. serverEntries = append(serverEntries, serverEntry)
  236. }
  237. return serverEntries, nil
  238. }
  239. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  240. // operation, loading only one server entry into memory at a time.
  241. type StreamingServerEntryDecoder struct {
  242. scanner *bufio.Scanner
  243. timestamp string
  244. serverEntrySource string
  245. }
  246. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  247. func NewStreamingServerEntryDecoder(
  248. encodedServerEntryListReader io.Reader,
  249. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  250. return &StreamingServerEntryDecoder{
  251. scanner: bufio.NewScanner(encodedServerEntryListReader),
  252. timestamp: timestamp,
  253. serverEntrySource: serverEntrySource,
  254. }
  255. }
  256. // Next reads and decodes, and validates the next server entry from the
  257. // input stream, returning a nil server entry when the stream is complete.
  258. //
  259. // Limitations:
  260. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  261. // the default buffer size which this decoder uses. This is 64K.
  262. // - DecodeServerEntry is called on each encoded server entry line, which
  263. // will allocate memory to hex decode and JSON deserialze the server
  264. // entry. As this is not presently reusing a fixed buffer, each call
  265. // will allocate additional memory; garbage collection is necessary to
  266. // reclaim that memory for reuse for the next server entry.
  267. //
  268. func (decoder *StreamingServerEntryDecoder) Next() (*ServerEntry, error) {
  269. for {
  270. if !decoder.scanner.Scan() {
  271. return nil, common.ContextError(decoder.scanner.Err())
  272. }
  273. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  274. // TODO: skip this entry and continue if can't decode?
  275. serverEntry, err := DecodeServerEntry(
  276. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  277. if err != nil {
  278. return nil, common.ContextError(err)
  279. }
  280. if ValidateServerEntry(serverEntry) != nil {
  281. // Skip this entry and continue with the next one
  282. // TODO: invoke a logging callback
  283. continue
  284. }
  285. return serverEntry, nil
  286. }
  287. }