serverEntry.go 14 KB

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