serverEntry.go 10 KB

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