serverEntry.go 8.6 KB

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