serverEntry.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. "strings"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. )
  31. // ServerEntry represents a Psiphon server. It contains information
  32. // about how to establish a tunnel connection to the server through
  33. // several protocols. Server entries are JSON records downloaded from
  34. // various sources.
  35. type ServerEntry struct {
  36. IpAddress string `json:"ipAddress"`
  37. WebServerPort string `json:"webServerPort"` // not an int
  38. WebServerSecret string `json:"webServerSecret"`
  39. WebServerCertificate string `json:"webServerCertificate"`
  40. SshPort int `json:"sshPort"`
  41. SshUsername string `json:"sshUsername"`
  42. SshPassword string `json:"sshPassword"`
  43. SshHostKey string `json:"sshHostKey"`
  44. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  45. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  46. Capabilities []string `json:"capabilities"`
  47. Region string `json:"region"`
  48. MeekServerPort int `json:"meekServerPort"`
  49. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  50. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  51. MeekFrontingHost string `json:"meekFrontingHost"`
  52. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  53. MeekFrontingDomain string `json:"meekFrontingDomain"`
  54. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  55. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  56. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  57. // These local fields are not expected to be present in downloaded server
  58. // entries. They are added by the client to record and report stats about
  59. // how and when server entries are obtained.
  60. LocalSource string `json:"localSource"`
  61. LocalTimestamp string `json:"localTimestamp"`
  62. }
  63. // GetCapability returns the server capability corresponding
  64. // to the protocol.
  65. func GetCapability(protocol string) string {
  66. return strings.TrimSuffix(protocol, "-OSSH")
  67. }
  68. // SupportsProtocol returns true if and only if the ServerEntry has
  69. // the necessary capability to support the specified tunnel protocol.
  70. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  71. requiredCapability := GetCapability(protocol)
  72. return common.Contains(serverEntry.Capabilities, requiredCapability)
  73. }
  74. // GetSupportedProtocols returns a list of tunnel protocols supported
  75. // by the ServerEntry's capabilities.
  76. func (serverEntry *ServerEntry) GetSupportedProtocols() []string {
  77. supportedProtocols := make([]string, 0)
  78. for _, protocol := range SupportedTunnelProtocols {
  79. if serverEntry.SupportsProtocol(protocol) {
  80. supportedProtocols = append(supportedProtocols, protocol)
  81. }
  82. }
  83. return supportedProtocols
  84. }
  85. // DisableImpairedProtocols modifies the ServerEntry to disable
  86. // the specified protocols.
  87. // Note: this assumes that protocol capabilities are 1-to-1.
  88. func (serverEntry *ServerEntry) DisableImpairedProtocols(impairedProtocols []string) {
  89. capabilities := make([]string, 0)
  90. for _, capability := range serverEntry.Capabilities {
  91. omit := false
  92. for _, protocol := range impairedProtocols {
  93. requiredCapability := GetCapability(protocol)
  94. if capability == requiredCapability {
  95. omit = true
  96. break
  97. }
  98. }
  99. if !omit {
  100. capabilities = append(capabilities, capability)
  101. }
  102. }
  103. serverEntry.Capabilities = capabilities
  104. }
  105. // SupportsSSHAPIRequests returns true when the server supports
  106. // SSH API requests.
  107. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  108. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  109. }
  110. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  111. ports := make([]string, 0)
  112. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  113. // Server-side configuration quirk: there's a port forward from
  114. // port 443 to the web server, which we can try, except on servers
  115. // running FRONTED_MEEK, which listens on port 443.
  116. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  117. ports = append(ports, "443")
  118. }
  119. ports = append(ports, serverEntry.WebServerPort)
  120. }
  121. return ports
  122. }
  123. // EncodeServerEntry returns a string containing the encoding of
  124. // a ServerEntry following Psiphon conventions.
  125. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  126. serverEntryContents, err := json.Marshal(serverEntry)
  127. if err != nil {
  128. return "", common.ContextError(err)
  129. }
  130. return hex.EncodeToString([]byte(fmt.Sprintf(
  131. "%s %s %s %s %s",
  132. serverEntry.IpAddress,
  133. serverEntry.WebServerPort,
  134. serverEntry.WebServerSecret,
  135. serverEntry.WebServerCertificate,
  136. serverEntryContents))), nil
  137. }
  138. // DecodeServerEntry extracts server entries from the encoding
  139. // used by remote server lists and Psiphon server handshake requests.
  140. //
  141. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  142. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  143. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  144. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  145. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  146. // should be a RFC 3339 formatted string. These local fields are stored with the
  147. // server entry and reported to the server as stats (a coarse granularity timestamp
  148. // is reported).
  149. func DecodeServerEntry(
  150. encodedServerEntry, timestamp,
  151. serverEntrySource string) (serverEntry *ServerEntry, err error) {
  152. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  153. if err != nil {
  154. return nil, common.ContextError(err)
  155. }
  156. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  157. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  158. if len(fields) != 5 {
  159. return nil, common.ContextError(errors.New("invalid encoded server entry"))
  160. }
  161. serverEntry = new(ServerEntry)
  162. err = json.Unmarshal(fields[4], &serverEntry)
  163. if err != nil {
  164. return nil, common.ContextError(err)
  165. }
  166. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  167. serverEntry.LocalSource = serverEntrySource
  168. serverEntry.LocalTimestamp = timestamp
  169. return serverEntry, nil
  170. }
  171. // DecodeServerEntryList extracts server entries from the list encoding
  172. // used by remote server lists and Psiphon server handshake requests.
  173. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  174. func DecodeServerEntryList(
  175. encodedServerEntryList, timestamp,
  176. serverEntrySource string) (serverEntries []*ServerEntry, err error) {
  177. serverEntries = make([]*ServerEntry, 0)
  178. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  179. if len(encodedServerEntry) == 0 {
  180. continue
  181. }
  182. // TODO: skip this entry and continue if can't decode?
  183. serverEntry, err := DecodeServerEntry(encodedServerEntry, timestamp, serverEntrySource)
  184. if err != nil {
  185. return nil, common.ContextError(err)
  186. }
  187. serverEntries = append(serverEntries, serverEntry)
  188. }
  189. return serverEntries, nil
  190. }
  191. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  192. // operation, loading only one server entry into memory at a time.
  193. type StreamingServerEntryDecoder struct {
  194. scanner *bufio.Scanner
  195. timestamp string
  196. serverEntrySource string
  197. }
  198. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  199. func NewStreamingServerEntryDecoder(
  200. encodedServerEntryListReader io.Reader,
  201. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  202. return &StreamingServerEntryDecoder{
  203. scanner: bufio.NewScanner(encodedServerEntryListReader),
  204. timestamp: timestamp,
  205. serverEntrySource: serverEntrySource,
  206. }
  207. }
  208. // Next reads and decodes the next server entry from the input stream,
  209. // returning a nil server entry when the stream is complete.
  210. //
  211. // Limitations:
  212. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  213. // the default buffer size which this decoder uses. This is 64K.
  214. // - DecodeServerEntry is called on each encoded server entry line, which
  215. // will allocate memory to hex decode and JSON deserialze the server
  216. // entry. As this is not presently reusing a fixed buffer, each call
  217. // will allocate additional memory; garbage collection is necessary to
  218. // reclaim that memory for reuse for the next server entry. Memory-
  219. // constrained users could call runtime.GC() after each call to Next.
  220. //
  221. func (decoder *StreamingServerEntryDecoder) Next() (*ServerEntry, error) {
  222. if !decoder.scanner.Scan() {
  223. return nil, common.ContextError(decoder.scanner.Err())
  224. }
  225. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  226. // TODO: skip this entry and continue if can't decode?
  227. serverEntry, err := DecodeServerEntry(
  228. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  229. if err != nil {
  230. return nil, common.ContextError(err)
  231. }
  232. return serverEntry, nil
  233. }