serverEntry.go 11 KB

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