serverEntry.go 11 KB

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