serverEntry.go 25 KB

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