serverEntry.go 11 KB

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