serverEntry.go 11 KB

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