serverEntry.go 9.7 KB

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