serverEntry.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. "errors"
  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/crypto/ed25519"
  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, common.ContextError(err)
  96. }
  97. var serverEntry *ServerEntry
  98. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  99. if err != nil {
  100. return nil, common.ContextError(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. marshaledFields, err := json.Marshal(copyFields)
  263. if err != nil {
  264. return common.ContextError(err)
  265. }
  266. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  267. if err != nil {
  268. return common.ContextError(err)
  269. }
  270. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  271. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  272. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  273. if err != nil {
  274. return common.ContextError(err)
  275. }
  276. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  277. fields["signature"] = base64.StdEncoding.EncodeToString(
  278. append(publicKeyID, signature...))
  279. return nil
  280. }
  281. // VerifySignature verifies the signature set by AddSignature.
  282. //
  283. // VerifySignature must be called before using any server entry that is
  284. // imported from an untrusted source, such as client-to-client exchange.
  285. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  286. // Make a copy so that removing unsigned fields will have no side effects
  287. copyFields := make(ServerEntryFields)
  288. for k, v := range fields {
  289. copyFields[k] = v
  290. }
  291. signatureField, ok := copyFields["signature"]
  292. if !ok {
  293. return common.ContextError(errors.New("missing signature field"))
  294. }
  295. signatureFieldStr, ok := signatureField.(string)
  296. if !ok {
  297. return common.ContextError(errors.New("invalid signature field"))
  298. }
  299. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  300. if err != nil {
  301. return common.ContextError(err)
  302. }
  303. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  304. return common.ContextError(errors.New("invalid signature field length"))
  305. }
  306. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  307. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  308. if len(signature) != ed25519.SignatureSize {
  309. return common.ContextError(errors.New("invalid signature length"))
  310. }
  311. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  312. if err != nil {
  313. return common.ContextError(err)
  314. }
  315. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  316. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  317. if bytes.Compare(expectedPublicKeyID, publicKeyID) != 0 {
  318. return common.ContextError(errors.New("unexpected public key ID"))
  319. }
  320. copyFields.RemoveUnsignedFields()
  321. delete(copyFields, "signature")
  322. marshaledFields, err := json.Marshal(copyFields)
  323. if err != nil {
  324. return common.ContextError(err)
  325. }
  326. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  327. return common.ContextError(errors.New("invalid signature"))
  328. }
  329. return nil
  330. }
  331. // RemoveUnsignedFields prepares a server entry for signing or signature
  332. // verification by removing unsigned fields. The JSON marshalling of the
  333. // remaining fields is the data that is signed.
  334. func (fields ServerEntryFields) RemoveUnsignedFields() {
  335. delete(fields, "localSource")
  336. delete(fields, "localTimestamp")
  337. // Only non-local, explicit tags are part of the signature
  338. isLocalDerivedTag, _ := fields["isLocalDerivedTag"]
  339. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  340. if ok && isLocalDerivedTagBool {
  341. delete(fields, "tag")
  342. }
  343. delete(fields, "isLocalDerivedTag")
  344. }
  345. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  346. // server entry signing and verification.
  347. func NewServerEntrySignatureKeyPair() (string, string, error) {
  348. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  349. if err != nil {
  350. return "", "", common.ContextError(err)
  351. }
  352. return base64.StdEncoding.EncodeToString(publicKey),
  353. base64.StdEncoding.EncodeToString(privateKey),
  354. nil
  355. }
  356. // GetCapability returns the server capability corresponding
  357. // to the tunnel protocol.
  358. func GetCapability(protocol string) string {
  359. return strings.TrimSuffix(protocol, "-OSSH")
  360. }
  361. // GetTacticsCapability returns the server tactics capability
  362. // corresponding to the tunnel protocol.
  363. func GetTacticsCapability(protocol string) string {
  364. return GetCapability(protocol) + "-TACTICS"
  365. }
  366. // SupportsProtocol returns true if and only if the ServerEntry has
  367. // the necessary capability to support the specified tunnel protocol.
  368. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  369. requiredCapability := GetCapability(protocol)
  370. return common.Contains(serverEntry.Capabilities, requiredCapability)
  371. }
  372. // GetSupportedProtocols returns a list of tunnel protocols supported
  373. // by the ServerEntry's capabilities.
  374. func (serverEntry *ServerEntry) GetSupportedProtocols(
  375. useUpstreamProxy bool,
  376. limitTunnelProtocols []string,
  377. excludeIntensive bool) []string {
  378. supportedProtocols := make([]string, 0)
  379. for _, protocol := range SupportedTunnelProtocols {
  380. // TODO: Marionette UDP formats are incompatible with
  381. // useUpstreamProxy, but not currently supported
  382. if useUpstreamProxy && TunnelProtocolUsesQUIC(protocol) {
  383. continue
  384. }
  385. if len(limitTunnelProtocols) > 0 {
  386. if !common.Contains(limitTunnelProtocols, protocol) {
  387. continue
  388. }
  389. } else {
  390. if common.Contains(DefaultDisabledTunnelProtocols, protocol) {
  391. continue
  392. }
  393. }
  394. if excludeIntensive && TunnelProtocolIsResourceIntensive(protocol) {
  395. continue
  396. }
  397. if serverEntry.SupportsProtocol(protocol) {
  398. supportedProtocols = append(supportedProtocols, protocol)
  399. }
  400. }
  401. return supportedProtocols
  402. }
  403. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  404. // supported by the ServerEntry's capabilities, that may be used
  405. // for tactics requests.
  406. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  407. supportedProtocols := make([]string, 0)
  408. for _, protocol := range SupportedTunnelProtocols {
  409. if !TunnelProtocolUsesMeek(protocol) {
  410. continue
  411. }
  412. requiredCapability := GetTacticsCapability(protocol)
  413. if !common.Contains(serverEntry.Capabilities, requiredCapability) {
  414. continue
  415. }
  416. supportedProtocols = append(supportedProtocols, protocol)
  417. }
  418. return supportedProtocols
  419. }
  420. // SupportsSSHAPIRequests returns true when the server supports
  421. // SSH API requests.
  422. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  423. return common.Contains(serverEntry.Capabilities, CAPABILITY_SSH_API_REQUESTS)
  424. }
  425. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  426. ports := make([]string, 0)
  427. if common.Contains(serverEntry.Capabilities, CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  428. // Server-side configuration quirk: there's a port forward from
  429. // port 443 to the web server, which we can try, except on servers
  430. // running FRONTED_MEEK, which listens on port 443.
  431. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  432. ports = append(ports, "443")
  433. }
  434. ports = append(ports, serverEntry.WebServerPort)
  435. }
  436. return ports
  437. }
  438. func (serverEntry *ServerEntry) HasSignature() bool {
  439. return serverEntry.Signature != ""
  440. }
  441. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  442. return TagToDiagnosticID(serverEntry.Tag)
  443. }
  444. // GenerateServerEntryTag creates a server entry tag value that is
  445. // cryptographically derived from the IP address and web server secret in a
  446. // way that is difficult to reverse the IP address value from the tag or
  447. // compute the tag without having the web server secret, a 256-bit random
  448. // value which is unique per server, in addition to the IP address. A database
  449. // consisting only of server entry tags should be resistent to an attack that
  450. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  451. // or some subset of the web server secrets.
  452. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  453. h := hmac.New(sha256.New, []byte(webServerSecret))
  454. h.Write([]byte(ipAddress))
  455. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  456. }
  457. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  458. // sufficient to uniquely identify servers in diagnostics, while also being
  459. // more human readable than emitting the full tag. The tag is used as the base
  460. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  461. // output.
  462. func TagToDiagnosticID(tag string) string {
  463. if len(tag) < 8 {
  464. return "<unknown>"
  465. }
  466. return tag[:8]
  467. }
  468. // EncodeServerEntry returns a string containing the encoding of
  469. // a ServerEntry following Psiphon conventions.
  470. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  471. return encodeServerEntry(
  472. serverEntry.IpAddress,
  473. serverEntry.WebServerPort,
  474. serverEntry.WebServerSecret,
  475. serverEntry.WebServerCertificate,
  476. serverEntry)
  477. }
  478. // EncodeServerEntryFields returns a string containing the encoding of
  479. // ServerEntryFields following Psiphon conventions.
  480. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  481. return encodeServerEntry(
  482. serverEntryFields.GetIPAddress(),
  483. serverEntryFields.GetWebServerPort(),
  484. serverEntryFields.GetWebServerSecret(),
  485. serverEntryFields.GetWebServerCertificate(),
  486. serverEntryFields)
  487. }
  488. func encodeServerEntry(
  489. IPAddress, webServerPort, webServerSecret, webServerCertificate string,
  490. serverEntry interface{}) (string, error) {
  491. serverEntryJSON, err := json.Marshal(serverEntry)
  492. if err != nil {
  493. return "", common.ContextError(err)
  494. }
  495. // Legacy clients expect the space-delimited fields.
  496. return hex.EncodeToString([]byte(fmt.Sprintf(
  497. "%s %s %s %s %s",
  498. IPAddress,
  499. webServerPort,
  500. webServerSecret,
  501. webServerCertificate,
  502. serverEntryJSON))), nil
  503. }
  504. // DecodeServerEntry extracts a server entry from the encoding
  505. // used by remote server lists and Psiphon server handshake requests.
  506. //
  507. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  508. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  509. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  510. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  511. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  512. // should be a RFC 3339 formatted string. These local fields are stored with the
  513. // server entry and reported to the server as stats (a coarse granularity timestamp
  514. // is reported).
  515. func DecodeServerEntry(
  516. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  517. serverEntry := new(ServerEntry)
  518. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  519. if err != nil {
  520. return nil, common.ContextError(err)
  521. }
  522. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  523. serverEntry.LocalSource = serverEntrySource
  524. serverEntry.LocalTimestamp = timestamp
  525. return serverEntry, nil
  526. }
  527. // DecodeServerEntryFields extracts an encoded server entry into a
  528. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  529. // not in ServerEntry are retained in the ServerEntryFields.
  530. //
  531. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  532. // inputs are non-blank.
  533. func DecodeServerEntryFields(
  534. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  535. serverEntryFields := make(ServerEntryFields)
  536. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  537. if err != nil {
  538. return nil, common.ContextError(err)
  539. }
  540. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  541. if serverEntrySource != "" {
  542. serverEntryFields.SetLocalSource(serverEntrySource)
  543. }
  544. if timestamp != "" {
  545. serverEntryFields.SetLocalTimestamp(timestamp)
  546. }
  547. return serverEntryFields, nil
  548. }
  549. func decodeServerEntry(
  550. encodedServerEntry, timestamp, serverEntrySource string,
  551. target interface{}) error {
  552. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  553. if err != nil {
  554. return common.ContextError(err)
  555. }
  556. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  557. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  558. if len(fields) != 5 {
  559. return common.ContextError(errors.New("invalid encoded server entry"))
  560. }
  561. err = json.Unmarshal(fields[4], target)
  562. if err != nil {
  563. return common.ContextError(err)
  564. }
  565. return nil
  566. }
  567. // ValidateServerEntryFields checks for malformed server entries.
  568. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  569. // Checks for a valid ipAddress. This is important since the IP
  570. // address is the key used to store/lookup the server entry.
  571. ipAddress := serverEntryFields.GetIPAddress()
  572. if net.ParseIP(ipAddress) == nil {
  573. return common.ContextError(
  574. fmt.Errorf("server entry has invalid ipAddress: %s", ipAddress))
  575. }
  576. // TODO: validate more fields?
  577. // Ensure locally initialized fields have been set.
  578. source := serverEntryFields.GetLocalSource()
  579. if !common.Contains(
  580. SupportedServerEntrySources, source) {
  581. return common.ContextError(
  582. fmt.Errorf("server entry has invalid source: %s", source))
  583. }
  584. timestamp := serverEntryFields.GetLocalTimestamp()
  585. _, err := time.Parse(time.RFC3339, timestamp)
  586. if err != nil {
  587. return common.ContextError(
  588. fmt.Errorf("server entry has invalid timestamp: %s", err))
  589. }
  590. return nil
  591. }
  592. // DecodeServerEntryList extracts server entries from the list encoding
  593. // used by remote server lists and Psiphon server handshake requests.
  594. // Each server entry is validated and invalid entries are skipped.
  595. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  596. func DecodeServerEntryList(
  597. encodedServerEntryList, timestamp,
  598. serverEntrySource string) ([]ServerEntryFields, error) {
  599. serverEntries := make([]ServerEntryFields, 0)
  600. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  601. if len(encodedServerEntry) == 0 {
  602. continue
  603. }
  604. // TODO: skip this entry and continue if can't decode?
  605. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  606. if err != nil {
  607. return nil, common.ContextError(err)
  608. }
  609. if ValidateServerEntryFields(serverEntryFields) != nil {
  610. // Skip this entry and continue with the next one
  611. // TODO: invoke a logging callback
  612. continue
  613. }
  614. serverEntries = append(serverEntries, serverEntryFields)
  615. }
  616. return serverEntries, nil
  617. }
  618. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  619. // operation, loading only one server entry into memory at a time.
  620. type StreamingServerEntryDecoder struct {
  621. scanner *bufio.Scanner
  622. timestamp string
  623. serverEntrySource string
  624. }
  625. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  626. func NewStreamingServerEntryDecoder(
  627. encodedServerEntryListReader io.Reader,
  628. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  629. return &StreamingServerEntryDecoder{
  630. scanner: bufio.NewScanner(encodedServerEntryListReader),
  631. timestamp: timestamp,
  632. serverEntrySource: serverEntrySource,
  633. }
  634. }
  635. // Next reads and decodes, and validates the next server entry from the
  636. // input stream, returning a nil server entry when the stream is complete.
  637. //
  638. // Limitations:
  639. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  640. // the default buffer size which this decoder uses. This is 64K.
  641. // - DecodeServerEntry is called on each encoded server entry line, which
  642. // will allocate memory to hex decode and JSON deserialze the server
  643. // entry. As this is not presently reusing a fixed buffer, each call
  644. // will allocate additional memory; garbage collection is necessary to
  645. // reclaim that memory for reuse for the next server entry.
  646. //
  647. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  648. for {
  649. if !decoder.scanner.Scan() {
  650. return nil, common.ContextError(decoder.scanner.Err())
  651. }
  652. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  653. // TODO: skip this entry and continue if can't decode?
  654. serverEntryFields, err := DecodeServerEntryFields(
  655. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  656. if err != nil {
  657. return nil, common.ContextError(err)
  658. }
  659. if ValidateServerEntryFields(serverEntryFields) != nil {
  660. // Skip this entry and continue with the next one
  661. // TODO: invoke a logging callback
  662. continue
  663. }
  664. return serverEntryFields, nil
  665. }
  666. }