serverEntry.go 16 KB

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