serverEntry.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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) SetLocalSource(source string) {
  133. fields["localSource"] = source
  134. }
  135. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  136. fields["localTimestamp"] = timestamp
  137. }
  138. // GetCapability returns the server capability corresponding
  139. // to the tunnel protocol.
  140. func GetCapability(protocol string) string {
  141. return strings.TrimSuffix(protocol, "-OSSH")
  142. }
  143. // GetTacticsCapability returns the server tactics capability
  144. // corresponding to the tunnel protocol.
  145. func GetTacticsCapability(protocol string) string {
  146. return GetCapability(protocol) + "-TACTICS"
  147. }
  148. // SupportsProtocol returns true if and only if the ServerEntry has
  149. // the necessary capability to support the specified tunnel protocol.
  150. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  151. requiredCapability := GetCapability(protocol)
  152. return common.Contains(serverEntry.Capabilities, requiredCapability)
  153. }
  154. // GetSupportedProtocols returns a list of tunnel protocols supported
  155. // by the ServerEntry's capabilities.
  156. func (serverEntry *ServerEntry) GetSupportedProtocols(
  157. useUpstreamProxy bool,
  158. limitTunnelProtocols []string,
  159. excludeIntensive bool) []string {
  160. supportedProtocols := make([]string, 0)
  161. for _, protocol := range SupportedTunnelProtocols {
  162. // TODO: Marionette UDP formats are incompatible with
  163. // useUpstreamProxy, but not currently supported
  164. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  165. continue
  166. }
  167. if len(limitTunnelProtocols) > 0 {
  168. if !common.Contains(limitTunnelProtocols, protocol) {
  169. continue
  170. }
  171. } else {
  172. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  173. continue
  174. }
  175. }
  176. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  177. continue
  178. }
  179. if serverEntry.SupportsProtocol(protocol) {
  180. supportedProtocols = append(supportedProtocols, protocol)
  181. }
  182. }
  183. return supportedProtocols
  184. }
  185. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  186. // supported by the ServerEntry's capabilities, that may be used
  187. // for tactics requests.
  188. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  189. supportedProtocols := make([]string, 0)
  190. for _, protocol := range SupportedTunnelProtocols {
  191. if !TunnelProtocolUsesMeek(protocol) {
  192. continue
  193. }
  194. requiredCapability := GetTacticsCapability(protocol)
  195. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  196. continue
  197. }
  198. supportedProtocols = append(supportedProtocols, protocol)
  199. }
  200. return supportedProtocols
  201. }
  202. // SupportsSSHAPIRequests returns true when the server supports
  203. // SSH API requests.
  204. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  205. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  206. }
  207. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  208. ports := make([]string, 0)
  209. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  210. // Server-side configuration quirk: there's a port forward from
  211. // port 443 to the web server, which we can try, except on servers
  212. // running FRONTED_MEEK, which listens on port 443.
  213. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  214. ports = append(ports, "443")
  215. }
  216. ports = append(ports, serverEntry.WebServerPort)
  217. }
  218. return ports
  219. }
  220. // GenerateServerEntryTag creates a server entry tag value that is
  221. // cryptographically derived from the IP address and web server secret in a
  222. // way that is difficult to reverse the IP address value from the tag or
  223. // compute the tag without having the web server secret, a 256-bit random
  224. // value which is unique per server, in addition to the IP address. A database
  225. // consisting only of server entry tags should be resistent to an attack that
  226. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  227. // or some subset of the web server secrets.
  228. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  229. h := hmac.New(sha256.New, []byte(webServerSecret))
  230. h.Write([]byte(ipAddress))
  231. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  232. }
  233. // EncodeServerEntry returns a string containing the encoding of
  234. // a ServerEntry following Psiphon conventions.
  235. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  236. serverEntryContents, err := json.Marshal(serverEntry)
  237. if err != nil {
  238. return "", common.ContextError(err)
  239. }
  240. return hex.EncodeToString([]byte(fmt.Sprintf(
  241. "%s %s %s %s %s",
  242. serverEntry.IpAddress,
  243. serverEntry.WebServerPort,
  244. serverEntry.WebServerSecret,
  245. serverEntry.WebServerCertificate,
  246. serverEntryContents))), nil
  247. }
  248. // DecodeServerEntry extracts a server entry from the encoding
  249. // used by remote server lists and Psiphon server handshake requests.
  250. //
  251. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  252. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  253. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  254. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  255. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  256. // should be a RFC 3339 formatted string. These local fields are stored with the
  257. // server entry and reported to the server as stats (a coarse granularity timestamp
  258. // is reported).
  259. func DecodeServerEntry(
  260. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  261. serverEntry := new(ServerEntry)
  262. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  263. if err != nil {
  264. return nil, common.ContextError(err)
  265. }
  266. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  267. serverEntry.LocalSource = serverEntrySource
  268. serverEntry.LocalTimestamp = timestamp
  269. return serverEntry, nil
  270. }
  271. // DecodeServerEntryFields extracts an encoded server entry into a
  272. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  273. // not in ServerEntry are retained in the ServerEntryFields.
  274. func DecodeServerEntryFields(
  275. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  276. serverEntryFields := make(ServerEntryFields)
  277. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  278. if err != nil {
  279. return nil, common.ContextError(err)
  280. }
  281. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  282. serverEntryFields.SetLocalSource(serverEntrySource)
  283. serverEntryFields.SetLocalTimestamp(timestamp)
  284. return serverEntryFields, nil
  285. }
  286. func decodeServerEntry(
  287. encodedServerEntry, timestamp, serverEntrySource string,
  288. target interface{}) error {
  289. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  290. if err != nil {
  291. return common.ContextError(err)
  292. }
  293. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  294. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  295. if len(fields) != 5 {
  296. return common.ContextError(errors.New("invalid encoded server entry"))
  297. }
  298. err = json.Unmarshal(fields[4], target)
  299. if err != nil {
  300. return common.ContextError(err)
  301. }
  302. return nil
  303. }
  304. // ValidateServerEntryFields checks for malformed server entries.
  305. // Currently, it checks for a valid ipAddress. This is important since
  306. // the IP address is the key used to store/lookup the server entry.
  307. // TODO: validate more fields?
  308. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  309. ipAddress := serverEntryFields.GetIPAddress()
  310. if net.ParseIP(ipAddress) == nil {
  311. return common.ContextError(
  312. fmt.Errorf("server entry has invalid ipAddress: %s", ipAddress))
  313. }
  314. return nil
  315. }
  316. // DecodeServerEntryList extracts server entries from the list encoding
  317. // used by remote server lists and Psiphon server handshake requests.
  318. // Each server entry is validated and invalid entries are skipped.
  319. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  320. func DecodeServerEntryList(
  321. encodedServerEntryList, timestamp,
  322. serverEntrySource string) ([]ServerEntryFields, error) {
  323. serverEntries := make([]ServerEntryFields, 0)
  324. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  325. if len(encodedServerEntry) == 0 {
  326. continue
  327. }
  328. // TODO: skip this entry and continue if can't decode?
  329. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  330. if err != nil {
  331. return nil, common.ContextError(err)
  332. }
  333. if ValidateServerEntryFields(serverEntryFields) != nil {
  334. // Skip this entry and continue with the next one
  335. // TODO: invoke a logging callback
  336. continue
  337. }
  338. serverEntries = append(serverEntries, serverEntryFields)
  339. }
  340. return serverEntries, nil
  341. }
  342. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  343. // operation, loading only one server entry into memory at a time.
  344. type StreamingServerEntryDecoder struct {
  345. scanner *bufio.Scanner
  346. timestamp string
  347. serverEntrySource string
  348. }
  349. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  350. func NewStreamingServerEntryDecoder(
  351. encodedServerEntryListReader io.Reader,
  352. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  353. return &StreamingServerEntryDecoder{
  354. scanner: bufio.NewScanner(encodedServerEntryListReader),
  355. timestamp: timestamp,
  356. serverEntrySource: serverEntrySource,
  357. }
  358. }
  359. // Next reads and decodes, and validates the next server entry from the
  360. // input stream, returning a nil server entry when the stream is complete.
  361. //
  362. // Limitations:
  363. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  364. // the default buffer size which this decoder uses. This is 64K.
  365. // - DecodeServerEntry is called on each encoded server entry line, which
  366. // will allocate memory to hex decode and JSON deserialze the server
  367. // entry. As this is not presently reusing a fixed buffer, each call
  368. // will allocate additional memory; garbage collection is necessary to
  369. // reclaim that memory for reuse for the next server entry.
  370. //
  371. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  372. for {
  373. if !decoder.scanner.Scan() {
  374. return nil, common.ContextError(decoder.scanner.Err())
  375. }
  376. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  377. // TODO: skip this entry and continue if can't decode?
  378. serverEntryFields, err := DecodeServerEntryFields(
  379. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  380. if err != nil {
  381. return nil, common.ContextError(err)
  382. }
  383. if ValidateServerEntryFields(serverEntryFields) != nil {
  384. // Skip this entry and continue with the next one
  385. // TODO: invoke a logging callback
  386. continue
  387. }
  388. return serverEntryFields, nil
  389. }
  390. }