serverEntry.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. // GetSupportedProtocols returns a list of tunnel protocols supported
  384. // by the ServerEntry's capabilities.
  385. func (serverEntry *ServerEntry) GetSupportedProtocols(
  386. useUpstreamProxy bool,
  387. limitTunnelProtocols []string,
  388. excludeIntensive bool) []string {
  389. supportedProtocols := make([]string, 0)
  390. for _, protocol := range SupportedTunnelProtocols {
  391. // TODO: Marionette UDP formats are incompatible with
  392. // useUpstreamProxy, but not currently supported
  393. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  394. continue
  395. }
  396. if len(limitTunnelProtocols) > 0 {
  397. if !common.Contains(limitTunnelProtocols, protocol) {
  398. continue
  399. }
  400. } else {
  401. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  402. continue
  403. }
  404. }
  405. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  406. continue
  407. }
  408. if serverEntry.SupportsProtocol(protocol) {
  409. supportedProtocols = append(supportedProtocols, protocol)
  410. }
  411. }
  412. return supportedProtocols
  413. }
  414. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  415. // supported by the ServerEntry's capabilities, that may be used
  416. // for tactics requests.
  417. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  418. supportedProtocols := make([]string, 0)
  419. for _, protocol := range SupportedTunnelProtocols {
  420. if !TunnelProtocolUsesMeek(protocol) {
  421. continue
  422. }
  423. requiredCapability := GetTacticsCapability(protocol)
  424. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  425. continue
  426. }
  427. supportedProtocols = append(supportedProtocols, protocol)
  428. }
  429. return supportedProtocols
  430. }
  431. // SupportsSSHAPIRequests returns true when the server supports
  432. // SSH API requests.
  433. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  434. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  435. }
  436. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  437. ports := make([]string, 0)
  438. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  439. // Server-side configuration quirk: there's a port forward from
  440. // port 443 to the web server, which we can try, except on servers
  441. // running FRONTED_MEEK, which listens on port 443.
  442. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  443. ports = append(ports, "443")
  444. }
  445. ports = append(ports, serverEntry.WebServerPort)
  446. }
  447. return ports
  448. }
  449. func (serverEntry *ServerEntry) HasSignature() bool {
  450. return serverEntry.Signature != ""
  451. }
  452. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  453. return TagToDiagnosticID(serverEntry.Tag)
  454. }
  455. // GenerateServerEntryTag creates a server entry tag value that is
  456. // cryptographically derived from the IP address and web server secret in a
  457. // way that is difficult to reverse the IP address value from the tag or
  458. // compute the tag without having the web server secret, a 256-bit random
  459. // value which is unique per server, in addition to the IP address. A database
  460. // consisting only of server entry tags should be resistent to an attack that
  461. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  462. // or some subset of the web server secrets.
  463. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  464. h := hmac.New(sha256.New, []byte(webServerSecret))
  465. h.Write([]byte(ipAddress))
  466. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  467. }
  468. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  469. // sufficient to uniquely identify servers in diagnostics, while also being
  470. // more human readable than emitting the full tag. The tag is used as the base
  471. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  472. // output.
  473. func TagToDiagnosticID(tag string) string {
  474. if len(tag) < 8 {
  475. return "<unknown>"
  476. }
  477. return tag[:8]
  478. }
  479. // EncodeServerEntry returns a string containing the encoding of
  480. // a ServerEntry following Psiphon conventions.
  481. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  482. return encodeServerEntry(
  483. serverEntry.IpAddress,
  484. serverEntry.WebServerPort,
  485. serverEntry.WebServerSecret,
  486. serverEntry.WebServerCertificate,
  487. serverEntry)
  488. }
  489. // EncodeServerEntryFields returns a string containing the encoding of
  490. // ServerEntryFields following Psiphon conventions.
  491. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  492. return encodeServerEntry(
  493. serverEntryFields.GetIPAddress(),
  494. serverEntryFields.GetWebServerPort(),
  495. serverEntryFields.GetWebServerSecret(),
  496. serverEntryFields.GetWebServerCertificate(),
  497. serverEntryFields)
  498. }
  499. func encodeServerEntry(
  500. IPAddress, webServerPort, webServerSecret, webServerCertificate string,
  501. serverEntry interface{}) (string, error) {
  502. serverEntryJSON, err := json.Marshal(serverEntry)
  503. if err != nil {
  504. return "", errors.Trace(err)
  505. }
  506. // Legacy clients expect the space-delimited fields.
  507. return hex.EncodeToString([]byte(fmt.Sprintf(
  508. "%s %s %s %s %s",
  509. IPAddress,
  510. webServerPort,
  511. webServerSecret,
  512. webServerCertificate,
  513. serverEntryJSON))), nil
  514. }
  515. // DecodeServerEntry extracts a server entry from the encoding
  516. // used by remote server lists and Psiphon server handshake requests.
  517. //
  518. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  519. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  520. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  521. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  522. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  523. // should be a RFC 3339 formatted string. These local fields are stored with the
  524. // server entry and reported to the server as stats (a coarse granularity timestamp
  525. // is reported).
  526. func DecodeServerEntry(
  527. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  528. serverEntry := new(ServerEntry)
  529. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  530. if err != nil {
  531. return nil, errors.Trace(err)
  532. }
  533. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  534. serverEntry.LocalSource = serverEntrySource
  535. serverEntry.LocalTimestamp = timestamp
  536. return serverEntry, nil
  537. }
  538. // DecodeServerEntryFields extracts an encoded server entry into a
  539. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  540. // not in ServerEntry are retained in the ServerEntryFields.
  541. //
  542. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  543. // inputs are non-blank.
  544. func DecodeServerEntryFields(
  545. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  546. serverEntryFields := make(ServerEntryFields)
  547. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  548. if err != nil {
  549. return nil, errors.Trace(err)
  550. }
  551. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  552. if serverEntrySource != "" {
  553. serverEntryFields.SetLocalSource(serverEntrySource)
  554. }
  555. if timestamp != "" {
  556. serverEntryFields.SetLocalTimestamp(timestamp)
  557. }
  558. return serverEntryFields, nil
  559. }
  560. func decodeServerEntry(
  561. encodedServerEntry, timestamp, serverEntrySource string,
  562. target interface{}) error {
  563. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  564. if err != nil {
  565. return errors.Trace(err)
  566. }
  567. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  568. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  569. if len(fields) != 5 {
  570. return errors.TraceNew("invalid encoded server entry")
  571. }
  572. err = json.Unmarshal(fields[4], target)
  573. if err != nil {
  574. return errors.Trace(err)
  575. }
  576. return nil
  577. }
  578. // ValidateServerEntryFields checks for malformed server entries.
  579. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  580. // Checks for a valid ipAddress. This is important since the IP
  581. // address is the key used to store/lookup the server entry.
  582. ipAddress := serverEntryFields.GetIPAddress()
  583. if net.ParseIP(ipAddress) == nil {
  584. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  585. }
  586. // TODO: validate more fields?
  587. // Ensure locally initialized fields have been set.
  588. source := serverEntryFields.GetLocalSource()
  589. if !common.Contains(
  590. SupportedServerEntrySources, source) {
  591. return errors.Tracef("server entry has invalid source: %s", source)
  592. }
  593. timestamp := serverEntryFields.GetLocalTimestamp()
  594. _, err := time.Parse(time.RFC3339, timestamp)
  595. if err != nil {
  596. return errors.Tracef("server entry has invalid timestamp: %s", err)
  597. }
  598. return nil
  599. }
  600. // DecodeServerEntryList extracts server entries from the list encoding
  601. // used by remote server lists and Psiphon server handshake requests.
  602. // Each server entry is validated and invalid entries are skipped.
  603. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  604. func DecodeServerEntryList(
  605. encodedServerEntryList, timestamp,
  606. serverEntrySource string) ([]ServerEntryFields, error) {
  607. serverEntries := make([]ServerEntryFields, 0)
  608. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  609. if len(encodedServerEntry) == 0 {
  610. continue
  611. }
  612. // TODO: skip this entry and continue if can't decode?
  613. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  614. if err != nil {
  615. return nil, errors.Trace(err)
  616. }
  617. if ValidateServerEntryFields(serverEntryFields) != nil {
  618. // Skip this entry and continue with the next one
  619. // TODO: invoke a logging callback
  620. continue
  621. }
  622. serverEntries = append(serverEntries, serverEntryFields)
  623. }
  624. return serverEntries, nil
  625. }
  626. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  627. // operation, loading only one server entry into memory at a time.
  628. type StreamingServerEntryDecoder struct {
  629. scanner *bufio.Scanner
  630. timestamp string
  631. serverEntrySource string
  632. }
  633. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  634. func NewStreamingServerEntryDecoder(
  635. encodedServerEntryListReader io.Reader,
  636. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  637. return &StreamingServerEntryDecoder{
  638. scanner: bufio.NewScanner(encodedServerEntryListReader),
  639. timestamp: timestamp,
  640. serverEntrySource: serverEntrySource,
  641. }
  642. }
  643. // Next reads and decodes, and validates the next server entry from the
  644. // input stream, returning a nil server entry when the stream is complete.
  645. //
  646. // Limitations:
  647. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  648. // the default buffer size which this decoder uses. This is 64K.
  649. // - DecodeServerEntry is called on each encoded server entry line, which
  650. // will allocate memory to hex decode and JSON deserialze the server
  651. // entry. As this is not presently reusing a fixed buffer, each call
  652. // will allocate additional memory; garbage collection is necessary to
  653. // reclaim that memory for reuse for the next server entry.
  654. //
  655. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  656. for {
  657. if !decoder.scanner.Scan() {
  658. return nil, errors.Trace(decoder.scanner.Err())
  659. }
  660. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  661. // TODO: skip this entry and continue if can't decode?
  662. serverEntryFields, err := DecodeServerEntryFields(
  663. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  664. if err != nil {
  665. return nil, errors.Trace(err)
  666. }
  667. if ValidateServerEntryFields(serverEntryFields) != nil {
  668. // Skip this entry and continue with the next one
  669. // TODO: invoke a logging callback
  670. continue
  671. }
  672. return serverEntryFields, nil
  673. }
  674. }