serverEntry.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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/ed25519"
  24. "crypto/hmac"
  25. "crypto/rand"
  26. "crypto/sha256"
  27. "encoding/base64"
  28. "encoding/hex"
  29. "encoding/json"
  30. "fmt"
  31. "io"
  32. "net"
  33. "strings"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. )
  38. // ServerEntry represents a Psiphon server. It contains information
  39. // about how to establish a tunnel connection to the server through
  40. // several protocols. Server entries are JSON records downloaded from
  41. // various sources.
  42. type ServerEntry struct {
  43. Tag string `json:"tag"`
  44. IpAddress string `json:"ipAddress"`
  45. WebServerPort string `json:"webServerPort"` // not an int
  46. WebServerSecret string `json:"webServerSecret"`
  47. WebServerCertificate string `json:"webServerCertificate"`
  48. SshPort int `json:"sshPort"`
  49. SshUsername string `json:"sshUsername"`
  50. SshPassword string `json:"sshPassword"`
  51. SshHostKey string `json:"sshHostKey"`
  52. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  53. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort"`
  54. SshObfuscatedTapDancePort int `json:"sshObfuscatedTapdancePort"`
  55. SshObfuscatedConjurePort int `json:"sshObfuscatedConjurePort"`
  56. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  57. Capabilities []string `json:"capabilities"`
  58. Region string `json:"region"`
  59. FrontingProviderID string `json:"frontingProviderID"`
  60. MeekServerPort int `json:"meekServerPort"`
  61. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  62. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  63. MeekFrontingHost string `json:"meekFrontingHost"`
  64. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  65. MeekFrontingDomain string `json:"meekFrontingDomain"`
  66. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  67. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  68. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  69. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey"`
  70. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey"`
  71. ConfigurationVersion int `json:"configurationVersion"`
  72. Signature string `json:"signature"`
  73. // These local fields are not expected to be present in downloaded server
  74. // entries. They are added by the client to record and report stats about
  75. // how and when server entries are obtained.
  76. // All local fields should be included the list of fields in RemoveUnsignedFields.
  77. LocalSource string `json:"localSource,omitempty"`
  78. LocalTimestamp string `json:"localTimestamp,omitempty"`
  79. IsLocalDerivedTag bool `json:"isLocalDerivedTag,omitempty"`
  80. }
  81. // ServerEntryFields is an alternate representation of ServerEntry which
  82. // enables future compatibility when unmarshaling and persisting new server
  83. // entries which may contain new, unrecognized fields not in the ServerEntry
  84. // type for a particular client version.
  85. //
  86. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  87. // types, unrecognized fields are discarded. When unmarshaled to
  88. // ServerEntryFields, unrecognized fields are retained and may be persisted
  89. // and available when the client is upgraded and unmarshals to an updated
  90. // ServerEntry type.
  91. type ServerEntryFields map[string]interface{}
  92. // GetServerEntry converts a ServerEntryFields into a ServerEntry.
  93. func (fields ServerEntryFields) GetServerEntry() (*ServerEntry, error) {
  94. marshaledServerEntry, err := json.Marshal(fields)
  95. if err != nil {
  96. return nil, errors.Trace(err)
  97. }
  98. var serverEntry *ServerEntry
  99. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  100. if err != nil {
  101. return nil, errors.Trace(err)
  102. }
  103. return serverEntry, nil
  104. }
  105. func (fields ServerEntryFields) GetTag() string {
  106. tag, ok := fields["tag"]
  107. if !ok {
  108. return ""
  109. }
  110. tagStr, ok := tag.(string)
  111. if !ok {
  112. return ""
  113. }
  114. return tagStr
  115. }
  116. // SetTag sets a local, derived server entry tag. A tag is an identifier used
  117. // in server entry pruning and potentially other use cases. An explict tag,
  118. // set by the Psiphon Network, may be present in a server entry that is
  119. // imported; otherwise, the client will set a derived tag. The tag should be
  120. // generated using GenerateServerEntryTag. When SetTag finds a explicit tag,
  121. // the new, derived tag is ignored. The isLocalTag local field is set to
  122. // distinguish explict and derived tags and is used in signature verification
  123. // to determine if the tag field is part of the signature.
  124. func (fields ServerEntryFields) SetTag(tag string) {
  125. // Don't replace explicit tag
  126. if tag, ok := fields["tag"]; ok {
  127. tagStr, ok := tag.(string)
  128. if ok && tagStr != "" {
  129. isLocalDerivedTag, ok := fields["isLocalDerivedTag"]
  130. if !ok {
  131. return
  132. }
  133. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  134. if ok && !isLocalDerivedTagBool {
  135. return
  136. }
  137. }
  138. }
  139. fields["tag"] = tag
  140. // Mark this tag as local
  141. fields["isLocalDerivedTag"] = true
  142. }
  143. func (fields ServerEntryFields) GetDiagnosticID() string {
  144. tag, ok := fields["tag"]
  145. if !ok {
  146. return ""
  147. }
  148. tagStr, ok := tag.(string)
  149. if !ok {
  150. return ""
  151. }
  152. return TagToDiagnosticID(tagStr)
  153. }
  154. func (fields ServerEntryFields) GetIPAddress() string {
  155. ipAddress, ok := fields["ipAddress"]
  156. if !ok {
  157. return ""
  158. }
  159. ipAddressStr, ok := ipAddress.(string)
  160. if !ok {
  161. return ""
  162. }
  163. return ipAddressStr
  164. }
  165. func (fields ServerEntryFields) GetWebServerPort() string {
  166. webServerPort, ok := fields["webServerPort"]
  167. if !ok {
  168. return ""
  169. }
  170. webServerPortStr, ok := webServerPort.(string)
  171. if !ok {
  172. return ""
  173. }
  174. return webServerPortStr
  175. }
  176. func (fields ServerEntryFields) GetWebServerSecret() string {
  177. webServerSecret, ok := fields["webServerSecret"]
  178. if !ok {
  179. return ""
  180. }
  181. webServerSecretStr, ok := webServerSecret.(string)
  182. if !ok {
  183. return ""
  184. }
  185. return webServerSecretStr
  186. }
  187. func (fields ServerEntryFields) GetWebServerCertificate() string {
  188. webServerCertificate, ok := fields["webServerCertificate"]
  189. if !ok {
  190. return ""
  191. }
  192. webServerCertificateStr, ok := webServerCertificate.(string)
  193. if !ok {
  194. return ""
  195. }
  196. return webServerCertificateStr
  197. }
  198. func (fields ServerEntryFields) GetConfigurationVersion() int {
  199. configurationVersion, ok := fields["configurationVersion"]
  200. if !ok {
  201. return 0
  202. }
  203. configurationVersionFloat, ok := configurationVersion.(float64)
  204. if !ok {
  205. return 0
  206. }
  207. return int(configurationVersionFloat)
  208. }
  209. func (fields ServerEntryFields) GetLocalSource() string {
  210. localSource, ok := fields["localSource"]
  211. if !ok {
  212. return ""
  213. }
  214. localSourceStr, ok := localSource.(string)
  215. if !ok {
  216. return ""
  217. }
  218. return localSourceStr
  219. }
  220. func (fields ServerEntryFields) SetLocalSource(source string) {
  221. fields["localSource"] = source
  222. }
  223. func (fields ServerEntryFields) GetLocalTimestamp() string {
  224. localTimestamp, ok := fields["localTimestamp"]
  225. if !ok {
  226. return ""
  227. }
  228. localTimestampStr, ok := localTimestamp.(string)
  229. if !ok {
  230. return ""
  231. }
  232. return localTimestampStr
  233. }
  234. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  235. fields["localTimestamp"] = timestamp
  236. }
  237. func (fields ServerEntryFields) HasSignature() bool {
  238. signature, ok := fields["signature"]
  239. if !ok {
  240. return false
  241. }
  242. signatureStr, ok := signature.(string)
  243. if !ok {
  244. return false
  245. }
  246. return signatureStr != ""
  247. }
  248. const signaturePublicKeyDigestSize = 8
  249. // AddSignature signs a server entry and attaches a new field containing the
  250. // signature. Any existing "signature" field will be replaced.
  251. //
  252. // The signature incudes a public key ID that is derived from a digest of the
  253. // public key value. This ID is intended for future use when multiple signing
  254. // keys may be deployed.
  255. func (fields ServerEntryFields) AddSignature(publicKey, privateKey string) error {
  256. // Make a copy so that removing unsigned fields will have no side effects
  257. copyFields := make(ServerEntryFields)
  258. for k, v := range fields {
  259. copyFields[k] = v
  260. }
  261. copyFields.RemoveUnsignedFields()
  262. delete(copyFields, "signature")
  263. // Best practise would be to sign the JSON encoded server entry bytes and
  264. // append the signature to those bytes. However, due to backwards
  265. // compatibility requirements, we must retain the outer server entry encoding
  266. // as-is and insert the signature.
  267. //
  268. // Limitation: since the verifyier must remarshal its server entry before
  269. // verifying, the JSON produced there must be a byte-for-byte match to the
  270. // JSON signed here. The precise output of the JSON encoder that is used,
  271. // "encoding/json", with default formatting, as of Go 1.11.5, is therefore
  272. // part of the signature protocol.
  273. //
  274. // TODO: use a standard, canonical encoding, such as JCS:
  275. // https://tools.ietf.org/id/draft-rundgren-json-canonicalization-scheme-05.html
  276. marshaledFields, err := json.Marshal(copyFields)
  277. if err != nil {
  278. return errors.Trace(err)
  279. }
  280. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  281. if err != nil {
  282. return errors.Trace(err)
  283. }
  284. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  285. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  286. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  287. if err != nil {
  288. return errors.Trace(err)
  289. }
  290. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  291. fields["signature"] = base64.StdEncoding.EncodeToString(
  292. append(publicKeyID, signature...))
  293. return nil
  294. }
  295. // VerifySignature verifies the signature set by AddSignature.
  296. //
  297. // VerifySignature must be called before using any server entry that is
  298. // imported from an untrusted source, such as client-to-client exchange.
  299. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  300. if publicKey == "" {
  301. return errors.TraceNew("missing public key")
  302. }
  303. // Make a copy so that removing unsigned fields will have no side effects
  304. copyFields := make(ServerEntryFields)
  305. for k, v := range fields {
  306. copyFields[k] = v
  307. }
  308. signatureField, ok := copyFields["signature"]
  309. if !ok {
  310. return errors.TraceNew("missing signature field")
  311. }
  312. signatureFieldStr, ok := signatureField.(string)
  313. if !ok {
  314. return errors.TraceNew("invalid signature field")
  315. }
  316. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  317. if err != nil {
  318. return errors.Trace(err)
  319. }
  320. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  321. return errors.TraceNew("invalid signature field length")
  322. }
  323. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  324. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  325. if len(signature) != ed25519.SignatureSize {
  326. return errors.TraceNew("invalid signature length")
  327. }
  328. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  329. if err != nil {
  330. return errors.Trace(err)
  331. }
  332. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  333. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  334. if !bytes.Equal(expectedPublicKeyID, publicKeyID) {
  335. return errors.TraceNew("unexpected public key ID")
  336. }
  337. copyFields.RemoveUnsignedFields()
  338. delete(copyFields, "signature")
  339. marshaledFields, err := json.Marshal(copyFields)
  340. if err != nil {
  341. return errors.Trace(err)
  342. }
  343. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  344. return errors.TraceNew("invalid signature")
  345. }
  346. return nil
  347. }
  348. // RemoveUnsignedFields prepares a server entry for signing or signature
  349. // verification by removing unsigned fields. The JSON marshalling of the
  350. // remaining fields is the data that is signed.
  351. func (fields ServerEntryFields) RemoveUnsignedFields() {
  352. delete(fields, "localSource")
  353. delete(fields, "localTimestamp")
  354. // Only non-local, explicit tags are part of the signature
  355. isLocalDerivedTag := fields["isLocalDerivedTag"]
  356. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  357. if ok && isLocalDerivedTagBool {
  358. delete(fields, "tag")
  359. }
  360. delete(fields, "isLocalDerivedTag")
  361. }
  362. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  363. // server entry signing and verification.
  364. func NewServerEntrySignatureKeyPair() (string, string, error) {
  365. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  366. if err != nil {
  367. return "", "", errors.Trace(err)
  368. }
  369. return base64.StdEncoding.EncodeToString(publicKey),
  370. base64.StdEncoding.EncodeToString(privateKey),
  371. nil
  372. }
  373. // GetCapability returns the server capability corresponding
  374. // to the tunnel protocol.
  375. func GetCapability(protocol string) string {
  376. return strings.TrimSuffix(protocol, "-OSSH")
  377. }
  378. // GetTacticsCapability returns the server tactics capability
  379. // corresponding to the tunnel protocol.
  380. func GetTacticsCapability(protocol string) string {
  381. return GetCapability(protocol) + "-TACTICS"
  382. }
  383. // hasCapability indicates if the server entry has the specified capability.
  384. //
  385. // Any internal "PASSTHROUGH-v2 or "PASSTHROUGH" componant in the server
  386. // entry's capabilities is ignored. These PASSTHROUGH components are used to
  387. // mask protocols which are running the passthrough mechanisms from older
  388. // clients which do not implement the passthrough messages. Older clients will
  389. // treat these capabilities as unknown protocols and skip them.
  390. func (serverEntry *ServerEntry) hasCapability(requiredCapability string) bool {
  391. for _, capability := range serverEntry.Capabilities {
  392. capability = strings.ReplaceAll(capability, "-PASSTHROUGH-v2", "")
  393. capability = strings.ReplaceAll(capability, "-PASSTHROUGH", "")
  394. if capability == requiredCapability {
  395. return true
  396. }
  397. }
  398. return false
  399. }
  400. // SupportsProtocol returns true if and only if the ServerEntry has
  401. // the necessary capability to support the specified tunnel protocol.
  402. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  403. requiredCapability := GetCapability(protocol)
  404. return serverEntry.hasCapability(requiredCapability)
  405. }
  406. // ProtocolUsesLegacyPassthrough indicates whether the ServerEntry supports
  407. // the specified protocol using legacy passthrough messages.
  408. func (serverEntry *ServerEntry) ProtocolUsesLegacyPassthrough(protocol string) bool {
  409. legacyCapability := GetCapability(protocol) + "-PASSTHROUGH"
  410. for _, capability := range serverEntry.Capabilities {
  411. if capability == legacyCapability {
  412. return true
  413. }
  414. }
  415. return false
  416. }
  417. // ConditionallyEnabledComponents defines an interface which can be queried to
  418. // determine which conditionally compiled protocol components are present.
  419. type ConditionallyEnabledComponents interface {
  420. QUICEnabled() bool
  421. RefractionNetworkingEnabled() bool
  422. }
  423. // TunnelProtocolPortLists is a map from tunnel protocol names (or "All") to a
  424. // list of port number ranges.
  425. type TunnelProtocolPortLists map[string]*common.PortList
  426. // GetSupportedProtocols returns a list of tunnel protocols supported by the
  427. // ServerEntry's capabilities and allowed by various constraints.
  428. func (serverEntry *ServerEntry) GetSupportedProtocols(
  429. conditionallyEnabled ConditionallyEnabledComponents,
  430. useUpstreamProxy bool,
  431. limitTunnelProtocols []string,
  432. limitTunnelDialPortNumbers TunnelProtocolPortLists,
  433. excludeIntensive bool) []string {
  434. supportedProtocols := make([]string, 0)
  435. for _, tunnelProtocol := range SupportedTunnelProtocols {
  436. if useUpstreamProxy && !TunnelProtocolSupportsUpstreamProxy(tunnelProtocol) {
  437. continue
  438. }
  439. if len(limitTunnelProtocols) > 0 {
  440. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  441. continue
  442. }
  443. } else {
  444. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  445. continue
  446. }
  447. }
  448. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  449. continue
  450. }
  451. if (TunnelProtocolUsesQUIC(tunnelProtocol) && !conditionallyEnabled.QUICEnabled()) ||
  452. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  453. !conditionallyEnabled.RefractionNetworkingEnabled()) {
  454. continue
  455. }
  456. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  457. continue
  458. }
  459. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  460. if err != nil {
  461. continue
  462. }
  463. if len(limitTunnelDialPortNumbers) > 0 {
  464. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  465. if !portList.Lookup(dialPortNumber) {
  466. continue
  467. }
  468. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  469. if !portList.Lookup(dialPortNumber) {
  470. continue
  471. }
  472. }
  473. }
  474. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  475. }
  476. return supportedProtocols
  477. }
  478. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  479. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  480. return 0, errors.TraceNew("protocol not supported")
  481. }
  482. switch tunnelProtocol {
  483. case TUNNEL_PROTOCOL_SSH:
  484. return serverEntry.SshPort, nil
  485. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  486. return serverEntry.SshObfuscatedPort, nil
  487. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  488. return serverEntry.SshObfuscatedTapDancePort, nil
  489. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  490. return serverEntry.SshObfuscatedConjurePort, nil
  491. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  492. return serverEntry.SshObfuscatedQUICPort, nil
  493. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  494. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  495. return 443, nil
  496. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  497. return 80, nil
  498. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  499. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  500. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  501. return serverEntry.MeekServerPort, nil
  502. }
  503. return 0, errors.TraceNew("unknown protocol")
  504. }
  505. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  506. // supported by the ServerEntry's capabilities, that may be used
  507. // for tactics requests.
  508. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  509. supportedProtocols := make([]string, 0)
  510. for _, protocol := range SupportedTunnelProtocols {
  511. if !TunnelProtocolUsesMeek(protocol) {
  512. continue
  513. }
  514. requiredCapability := GetTacticsCapability(protocol)
  515. if !serverEntry.hasCapability(requiredCapability) {
  516. continue
  517. }
  518. supportedProtocols = append(supportedProtocols, protocol)
  519. }
  520. return supportedProtocols
  521. }
  522. // SupportsSSHAPIRequests returns true when the server supports
  523. // SSH API requests.
  524. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  525. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  526. }
  527. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  528. ports := make([]string, 0)
  529. if serverEntry.hasCapability(CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  530. // Server-side configuration quirk: there's a port forward from
  531. // port 443 to the web server, which we can try, except on servers
  532. // running FRONTED_MEEK, which listens on port 443.
  533. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  534. ports = append(ports, "443")
  535. }
  536. ports = append(ports, serverEntry.WebServerPort)
  537. }
  538. return ports
  539. }
  540. func (serverEntry *ServerEntry) HasSignature() bool {
  541. return serverEntry.Signature != ""
  542. }
  543. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  544. return TagToDiagnosticID(serverEntry.Tag)
  545. }
  546. // GenerateServerEntryTag creates a server entry tag value that is
  547. // cryptographically derived from the IP address and web server secret in a
  548. // way that is difficult to reverse the IP address value from the tag or
  549. // compute the tag without having the web server secret, a 256-bit random
  550. // value which is unique per server, in addition to the IP address. A database
  551. // consisting only of server entry tags should be resistent to an attack that
  552. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  553. // or some subset of the web server secrets.
  554. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  555. h := hmac.New(sha256.New, []byte(webServerSecret))
  556. h.Write([]byte(ipAddress))
  557. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  558. }
  559. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  560. // sufficient to uniquely identify servers in diagnostics, while also being
  561. // more human readable than emitting the full tag. The tag is used as the base
  562. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  563. // output.
  564. func TagToDiagnosticID(tag string) string {
  565. if len(tag) < 8 {
  566. return "<unknown>"
  567. }
  568. return tag[:8]
  569. }
  570. // EncodeServerEntry returns a string containing the encoding of
  571. // a ServerEntry following Psiphon conventions.
  572. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  573. return encodeServerEntry(
  574. serverEntry.IpAddress,
  575. serverEntry.WebServerPort,
  576. serverEntry.WebServerSecret,
  577. serverEntry.WebServerCertificate,
  578. serverEntry)
  579. }
  580. // EncodeServerEntryFields returns a string containing the encoding of
  581. // ServerEntryFields following Psiphon conventions.
  582. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  583. return encodeServerEntry(
  584. serverEntryFields.GetIPAddress(),
  585. serverEntryFields.GetWebServerPort(),
  586. serverEntryFields.GetWebServerSecret(),
  587. serverEntryFields.GetWebServerCertificate(),
  588. serverEntryFields)
  589. }
  590. func encodeServerEntry(
  591. prefixIPAddress string,
  592. prefixWebServerPort string,
  593. prefixWebServerSecret string,
  594. prefixWebServerCertificate string,
  595. serverEntry interface{}) (string, error) {
  596. serverEntryJSON, err := json.Marshal(serverEntry)
  597. if err != nil {
  598. return "", errors.Trace(err)
  599. }
  600. // Legacy clients use a space-delimited fields prefix, and all clients expect
  601. // to at least parse the prefix in order to skip over it.
  602. //
  603. // When the server entry has no web API server certificate, the entire prefix
  604. // can be compacted down to single character placeholders. Clients that can
  605. // use the ssh API always prefer it over the web API and won't use the prefix
  606. // values.
  607. if len(prefixWebServerCertificate) == 0 {
  608. prefixIPAddress = "0"
  609. prefixWebServerPort = "0"
  610. prefixWebServerSecret = "0"
  611. prefixWebServerCertificate = "0"
  612. }
  613. return hex.EncodeToString([]byte(fmt.Sprintf(
  614. "%s %s %s %s %s",
  615. prefixIPAddress,
  616. prefixWebServerPort,
  617. prefixWebServerSecret,
  618. prefixWebServerCertificate,
  619. serverEntryJSON))), nil
  620. }
  621. // DecodeServerEntry extracts a server entry from the encoding
  622. // used by remote server lists and Psiphon server handshake requests.
  623. //
  624. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  625. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  626. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  627. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  628. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  629. // should be a RFC 3339 formatted string. These local fields are stored with the
  630. // server entry and reported to the server as stats (a coarse granularity timestamp
  631. // is reported).
  632. func DecodeServerEntry(
  633. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  634. serverEntry := new(ServerEntry)
  635. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  636. if err != nil {
  637. return nil, errors.Trace(err)
  638. }
  639. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  640. serverEntry.LocalSource = serverEntrySource
  641. serverEntry.LocalTimestamp = timestamp
  642. return serverEntry, nil
  643. }
  644. // DecodeServerEntryFields extracts an encoded server entry into a
  645. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  646. // not in ServerEntry are retained in the ServerEntryFields.
  647. //
  648. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  649. // inputs are non-blank.
  650. func DecodeServerEntryFields(
  651. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  652. serverEntryFields := make(ServerEntryFields)
  653. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  654. if err != nil {
  655. return nil, errors.Trace(err)
  656. }
  657. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  658. if serverEntrySource != "" {
  659. serverEntryFields.SetLocalSource(serverEntrySource)
  660. }
  661. if timestamp != "" {
  662. serverEntryFields.SetLocalTimestamp(timestamp)
  663. }
  664. return serverEntryFields, nil
  665. }
  666. func decodeServerEntry(
  667. encodedServerEntry, timestamp, serverEntrySource string,
  668. target interface{}) error {
  669. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  670. if err != nil {
  671. return errors.Trace(err)
  672. }
  673. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  674. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  675. if len(fields) != 5 {
  676. return errors.TraceNew("invalid encoded server entry")
  677. }
  678. err = json.Unmarshal(fields[4], target)
  679. if err != nil {
  680. return errors.Trace(err)
  681. }
  682. return nil
  683. }
  684. // ValidateServerEntryFields checks for malformed server entries.
  685. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  686. // Checks for a valid ipAddress. This is important since the IP
  687. // address is the key used to store/lookup the server entry.
  688. ipAddress := serverEntryFields.GetIPAddress()
  689. if net.ParseIP(ipAddress) == nil {
  690. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  691. }
  692. // TODO: validate more fields?
  693. // Ensure locally initialized fields have been set.
  694. source := serverEntryFields.GetLocalSource()
  695. if !common.Contains(
  696. SupportedServerEntrySources, source) {
  697. return errors.Tracef("server entry has invalid source: %s", source)
  698. }
  699. timestamp := serverEntryFields.GetLocalTimestamp()
  700. _, err := time.Parse(time.RFC3339, timestamp)
  701. if err != nil {
  702. return errors.Tracef("server entry has invalid timestamp: %s", err)
  703. }
  704. return nil
  705. }
  706. // DecodeServerEntryList extracts server entries from the list encoding
  707. // used by remote server lists and Psiphon server handshake requests.
  708. // Each server entry is validated and invalid entries are skipped.
  709. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  710. func DecodeServerEntryList(
  711. encodedServerEntryList, timestamp,
  712. serverEntrySource string) ([]ServerEntryFields, error) {
  713. serverEntries := make([]ServerEntryFields, 0)
  714. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  715. if len(encodedServerEntry) == 0 {
  716. continue
  717. }
  718. // TODO: skip this entry and continue if can't decode?
  719. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  720. if err != nil {
  721. return nil, errors.Trace(err)
  722. }
  723. if ValidateServerEntryFields(serverEntryFields) != nil {
  724. // Skip this entry and continue with the next one
  725. // TODO: invoke a logging callback
  726. continue
  727. }
  728. serverEntries = append(serverEntries, serverEntryFields)
  729. }
  730. return serverEntries, nil
  731. }
  732. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  733. // operation, loading only one server entry into memory at a time.
  734. type StreamingServerEntryDecoder struct {
  735. scanner *bufio.Scanner
  736. timestamp string
  737. serverEntrySource string
  738. }
  739. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  740. func NewStreamingServerEntryDecoder(
  741. encodedServerEntryListReader io.Reader,
  742. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  743. return &StreamingServerEntryDecoder{
  744. scanner: bufio.NewScanner(encodedServerEntryListReader),
  745. timestamp: timestamp,
  746. serverEntrySource: serverEntrySource,
  747. }
  748. }
  749. // Next reads and decodes, and validates the next server entry from the
  750. // input stream, returning a nil server entry when the stream is complete.
  751. //
  752. // Limitations:
  753. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  754. // the default buffer size which this decoder uses. This is 64K.
  755. // - DecodeServerEntry is called on each encoded server entry line, which
  756. // will allocate memory to hex decode and JSON deserialze the server
  757. // entry. As this is not presently reusing a fixed buffer, each call
  758. // will allocate additional memory; garbage collection is necessary to
  759. // reclaim that memory for reuse for the next server entry.
  760. //
  761. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  762. for {
  763. if !decoder.scanner.Scan() {
  764. return nil, errors.Trace(decoder.scanner.Err())
  765. }
  766. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  767. // TODO: skip this entry and continue if can't decode?
  768. serverEntryFields, err := DecodeServerEntryFields(
  769. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  770. if err != nil {
  771. return nil, errors.Trace(err)
  772. }
  773. if ValidateServerEntryFields(serverEntryFields) != nil {
  774. // Skip this entry and continue with the next one
  775. // TODO: invoke a logging callback
  776. continue
  777. }
  778. return serverEntryFields, nil
  779. }
  780. }