serverEntry.go 11 KB

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