serverEntry.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 psiphon
  20. import (
  21. "bytes"
  22. "encoding/hex"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "net"
  27. "strings"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  30. )
  31. // ServerEntry represents a Psiphon server. It contains information
  32. // about how to establish a tunnel connection to the server through
  33. // several protocols. Server entries are JSON records downloaded from
  34. // various sources.
  35. type ServerEntry struct {
  36. IpAddress string `json:"ipAddress"`
  37. WebServerPort string `json:"webServerPort"` // not an int
  38. WebServerSecret string `json:"webServerSecret"`
  39. WebServerCertificate string `json:"webServerCertificate"`
  40. SshPort int `json:"sshPort"`
  41. SshUsername string `json:"sshUsername"`
  42. SshPassword string `json:"sshPassword"`
  43. SshHostKey string `json:"sshHostKey"`
  44. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  45. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  46. Capabilities []string `json:"capabilities"`
  47. Region string `json:"region"`
  48. MeekServerPort int `json:"meekServerPort"`
  49. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  50. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  51. MeekFrontingHost string `json:"meekFrontingHost"`
  52. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  53. MeekFrontingDomain string `json:"meekFrontingDomain"`
  54. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  55. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  56. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  57. // These local fields are not expected to be present in downloaded server
  58. // entries. They are added by the client to record and report stats about
  59. // how and when server entries are obtained.
  60. LocalSource string `json:"localSource"`
  61. LocalTimestamp string `json:"localTimestamp"`
  62. }
  63. // GetCapability returns the server capability corresponding
  64. // to the protocol.
  65. func GetCapability(protocol string) string {
  66. return strings.TrimSuffix(protocol, "-OSSH")
  67. }
  68. // SupportsProtocol returns true if and only if the ServerEntry has
  69. // the necessary capability to support the specified tunnel protocol.
  70. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  71. requiredCapability := GetCapability(protocol)
  72. return common.Contains(serverEntry.Capabilities, requiredCapability)
  73. }
  74. // GetSupportedProtocols returns a list of tunnel protocols supported
  75. // by the ServerEntry's capabilities.
  76. func (serverEntry *ServerEntry) GetSupportedProtocols() []string {
  77. supportedProtocols := make([]string, 0)
  78. for _, protocol := range protocol.SupportedTunnelProtocols {
  79. if serverEntry.SupportsProtocol(protocol) {
  80. supportedProtocols = append(supportedProtocols, protocol)
  81. }
  82. }
  83. return supportedProtocols
  84. }
  85. // DisableImpairedProtocols modifies the ServerEntry to disable
  86. // the specified protocols.
  87. // Note: this assumes that protocol capabilities are 1-to-1.
  88. func (serverEntry *ServerEntry) DisableImpairedProtocols(impairedProtocols []string) {
  89. capabilities := make([]string, 0)
  90. for _, capability := range serverEntry.Capabilities {
  91. omit := false
  92. for _, protocol := range impairedProtocols {
  93. requiredCapability := GetCapability(protocol)
  94. if capability == requiredCapability {
  95. omit = true
  96. break
  97. }
  98. }
  99. if !omit {
  100. capabilities = append(capabilities, capability)
  101. }
  102. }
  103. serverEntry.Capabilities = capabilities
  104. }
  105. // SupportsSSHAPIRequests returns true when the server supports
  106. // SSH API requests.
  107. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  108. return common.Contains(serverEntry.Capabilities, protocol.CAPABILITY_SSH_API_REQUESTS)
  109. }
  110. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  111. ports := make([]string, 0)
  112. if common.Contains(serverEntry.Capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  113. // Server-side configuration quirk: there's a port forward from
  114. // port 443 to the web server, which we can try, except on servers
  115. // running FRONTED_MEEK, which listens on port 443.
  116. if !serverEntry.SupportsProtocol(protocol.TUNNEL_PROTOCOL_FRONTED_MEEK) {
  117. ports = append(ports, "443")
  118. }
  119. ports = append(ports, serverEntry.WebServerPort)
  120. }
  121. return ports
  122. }
  123. // EncodeServerEntry returns a string containing the encoding of
  124. // a ServerEntry following Psiphon conventions.
  125. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  126. serverEntryContents, err := json.Marshal(serverEntry)
  127. if err != nil {
  128. return "", common.ContextError(err)
  129. }
  130. return hex.EncodeToString([]byte(fmt.Sprintf(
  131. "%s %s %s %s %s",
  132. serverEntry.IpAddress,
  133. serverEntry.WebServerPort,
  134. serverEntry.WebServerSecret,
  135. serverEntry.WebServerCertificate,
  136. serverEntryContents))), nil
  137. }
  138. // DecodeServerEntry extracts server entries from the encoding
  139. // used by remote server lists and Psiphon server handshake requests.
  140. //
  141. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  142. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  143. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET.
  144. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  145. // should be a RFC 3339 formatted string. These local fields are stored with the
  146. // server entry and reported to the server as stats (a coarse granularity timestamp
  147. // is reported).
  148. func DecodeServerEntry(
  149. encodedServerEntry, timestamp,
  150. serverEntrySource string) (serverEntry *ServerEntry, err error) {
  151. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  152. if err != nil {
  153. return nil, common.ContextError(err)
  154. }
  155. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  156. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  157. if len(fields) != 5 {
  158. return nil, common.ContextError(errors.New("invalid encoded server entry"))
  159. }
  160. serverEntry = new(ServerEntry)
  161. err = json.Unmarshal(fields[4], &serverEntry)
  162. if err != nil {
  163. return nil, common.ContextError(err)
  164. }
  165. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  166. serverEntry.LocalSource = serverEntrySource
  167. serverEntry.LocalTimestamp = timestamp
  168. return serverEntry, nil
  169. }
  170. // ValidateServerEntry checks for malformed server entries.
  171. // Currently, it checks for a valid ipAddress. This is important since
  172. // handshake requests submit back to the server a list of known server
  173. // IP addresses and the handshake API expects well-formed inputs.
  174. // TODO: validate more fields
  175. func ValidateServerEntry(serverEntry *ServerEntry) error {
  176. ipAddr := net.ParseIP(serverEntry.IpAddress)
  177. if ipAddr == nil {
  178. errMsg := fmt.Sprintf("server entry has invalid IpAddress: '%s'", serverEntry.IpAddress)
  179. // Some callers skip invalid server entries without propagating
  180. // the error mesage, so issue a notice.
  181. NoticeAlert(errMsg)
  182. return common.ContextError(errors.New(errMsg))
  183. }
  184. return nil
  185. }
  186. // DecodeAndValidateServerEntryList extracts server entries from the list encoding
  187. // used by remote server lists and Psiphon server handshake requests.
  188. // Each server entry is validated and invalid entries are skipped.
  189. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  190. func DecodeAndValidateServerEntryList(
  191. encodedServerEntryList, timestamp,
  192. serverEntrySource string) (serverEntries []*ServerEntry, err error) {
  193. serverEntries = make([]*ServerEntry, 0)
  194. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  195. if len(encodedServerEntry) == 0 {
  196. continue
  197. }
  198. // TODO: skip this entry and continue if can't decode?
  199. serverEntry, err := DecodeServerEntry(encodedServerEntry, timestamp, serverEntrySource)
  200. if err != nil {
  201. return nil, common.ContextError(err)
  202. }
  203. if ValidateServerEntry(serverEntry) != nil {
  204. // Skip this entry and continue with the next one
  205. continue
  206. }
  207. serverEntries = append(serverEntries, serverEntry)
  208. }
  209. return serverEntries, nil
  210. }