serverEntry.go 14 KB

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