serverEntry.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package protocol
  20. import (
  21. "bufio"
  22. "bytes"
  23. "crypto/ed25519"
  24. "crypto/hmac"
  25. "crypto/rand"
  26. "crypto/sha256"
  27. "encoding/base64"
  28. "encoding/hex"
  29. "encoding/json"
  30. "fmt"
  31. "io"
  32. "net"
  33. "regexp"
  34. "strconv"
  35. "strings"
  36. "sync/atomic"
  37. "time"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  40. )
  41. // ServerEntry represents a Psiphon server. It contains information
  42. // about how to establish a tunnel connection to the server through
  43. // several protocols. Server entries are JSON records downloaded from
  44. // various sources.
  45. type ServerEntry struct {
  46. Tag string `json:"tag,omitempty"`
  47. IpAddress string `json:"ipAddress,omitempty"`
  48. WebServerPort string `json:"webServerPort,omitempty"` // not an int
  49. WebServerSecret string `json:"webServerSecret,omitempty"`
  50. WebServerCertificate string `json:"webServerCertificate,omitempty"`
  51. SshPort int `json:"sshPort,omitempty"`
  52. SshUsername string `json:"sshUsername,omitempty"`
  53. SshPassword string `json:"sshPassword,omitempty"`
  54. SshHostKey string `json:"sshHostKey,omitempty"`
  55. SshObfuscatedPort int `json:"sshObfuscatedPort,omitempty"`
  56. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort,omitempty"`
  57. LimitQUICVersions []string `json:"limitQUICVersions,omitempty"`
  58. SshObfuscatedTapDancePort int `json:"sshObfuscatedTapdancePort,omitempty"`
  59. SshObfuscatedConjurePort int `json:"sshObfuscatedConjurePort,omitempty"`
  60. SshObfuscatedKey string `json:"sshObfuscatedKey,omitempty"`
  61. SshShadowsocksPort int `json:"sshShadowsocksPort,omitempty"`
  62. SshShadowsocksKey string `json:"sshShadowsocksKey,omitempty"`
  63. Capabilities []string `json:"capabilities,omitempty"`
  64. Region string `json:"region,omitempty"`
  65. ProviderID string `json:"providerID,omitempty"`
  66. FrontingProviderID string `json:"frontingProviderID,omitempty"`
  67. TlsOSSHPort int `json:"tlsOSSHPort,omitempty"`
  68. MeekServerPort int `json:"meekServerPort,omitempty"`
  69. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey,omitempty"`
  70. MeekObfuscatedKey string `json:"meekObfuscatedKey,omitempty"`
  71. MeekFrontingHost string `json:"meekFrontingHost,omitempty"`
  72. MeekFrontingHosts []string `json:"meekFrontingHosts,omitempty"`
  73. MeekFrontingDomain string `json:"meekFrontingDomain,omitempty"`
  74. MeekFrontingAddresses []string `json:"meekFrontingAddresses,omitempty"`
  75. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex,omitempty"`
  76. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI,omitempty"`
  77. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey,omitempty"`
  78. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey,omitempty"`
  79. ConfigurationVersion int `json:"configurationVersion,omitempty"`
  80. Signature string `json:"signature,omitempty"`
  81. DisableHTTPTransforms bool `json:"disableHTTPTransforms,omitempty"`
  82. DisableObfuscatedQUICTransforms bool `json:"disableObfuscatedQUICTransforms,omitempty"`
  83. DisableOSSHTransforms bool `json:"disableOSSHTransforms,omitempty"`
  84. DisableOSSHPrefix bool `json:"disableOSSHPrefix,omitempty"`
  85. DisableShadowsocksPrefix bool `json:"disableShadowsocksPrefix,omitempty"`
  86. InproxySessionPublicKey string `json:"inproxySessionPublicKey,omitempty"`
  87. InproxySessionRootObfuscationSecret string `json:"inproxySessionRootObfuscationSecret,omitempty"`
  88. InproxySSHPort int `json:"inproxySSHPort,omitempty"`
  89. InproxyOSSHPort int `json:"inproxyOSSHPort,omitempty"`
  90. InproxyQUICPort int `json:"inproxyQUICPort,omitempty"`
  91. InproxyMeekPort int `json:"inproxyMeekPort,omitempty"`
  92. InproxyTlsOSSHPort int `json:"inproxyTlsOSSHPort,omitempty"`
  93. InproxyShadowsocksPort int `json:"inproxyShadowsocksPort,omitempty"`
  94. // These local fields are not expected to be present in downloaded server
  95. // entries. They are added by the client to record and report stats about
  96. // how and when server entries are obtained.
  97. // All local fields should be included the list of fields in RemoveUnsignedFields.
  98. LocalSource string `json:"localSource,omitempty"`
  99. LocalTimestamp string `json:"localTimestamp,omitempty"`
  100. IsLocalDerivedTag bool `json:"isLocalDerivedTag,omitempty"`
  101. }
  102. // ServerEntryFields is an alternate representation of ServerEntry which
  103. // enables future compatibility when unmarshaling and persisting new server
  104. // entries which may contain new, unrecognized fields not in the ServerEntry
  105. // type for a particular client version.
  106. //
  107. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  108. // types, unrecognized fields are discarded. When unmarshaled to
  109. // ServerEntryFields, unrecognized fields are retained and may be persisted
  110. // and available when the client is upgraded and unmarshals to an updated
  111. // ServerEntry type.
  112. type ServerEntryFields map[string]interface{}
  113. // GetServerEntry converts a ServerEntryFields into a ServerEntry.
  114. func (fields ServerEntryFields) GetServerEntry() (*ServerEntry, error) {
  115. marshaledServerEntry, err := json.Marshal(fields)
  116. if err != nil {
  117. return nil, errors.Trace(err)
  118. }
  119. var serverEntry *ServerEntry
  120. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  121. if err != nil {
  122. return nil, errors.Trace(err)
  123. }
  124. return serverEntry, nil
  125. }
  126. func (fields ServerEntryFields) GetTag() string {
  127. tag, ok := fields["tag"]
  128. if !ok {
  129. return ""
  130. }
  131. tagStr, ok := tag.(string)
  132. if !ok {
  133. return ""
  134. }
  135. return tagStr
  136. }
  137. // SetTag sets a local, derived server entry tag. A tag is an identifier used
  138. // in server entry pruning and potentially other use cases. An explict tag,
  139. // set by the Psiphon Network, may be present in a server entry that is
  140. // imported; otherwise, the client will set a derived tag. The tag should be
  141. // generated using GenerateServerEntryTag. When SetTag finds a explicit tag,
  142. // the new, derived tag is ignored. The isLocalTag local field is set to
  143. // distinguish explict and derived tags and is used in signature verification
  144. // to determine if the tag field is part of the signature.
  145. func (fields ServerEntryFields) SetTag(tag string) {
  146. // Don't replace explicit tag
  147. if tag, ok := fields["tag"]; ok {
  148. tagStr, ok := tag.(string)
  149. if ok && tagStr != "" {
  150. isLocalDerivedTag, ok := fields["isLocalDerivedTag"]
  151. if !ok {
  152. return
  153. }
  154. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  155. if ok && !isLocalDerivedTagBool {
  156. return
  157. }
  158. }
  159. }
  160. fields["tag"] = tag
  161. // Mark this tag as local
  162. fields["isLocalDerivedTag"] = true
  163. }
  164. func (fields ServerEntryFields) GetDiagnosticID() string {
  165. tag, ok := fields["tag"]
  166. if !ok {
  167. return ""
  168. }
  169. tagStr, ok := tag.(string)
  170. if !ok {
  171. return ""
  172. }
  173. return TagToDiagnosticID(tagStr)
  174. }
  175. func (fields ServerEntryFields) GetIPAddress() string {
  176. ipAddress, ok := fields["ipAddress"]
  177. if !ok {
  178. return ""
  179. }
  180. ipAddressStr, ok := ipAddress.(string)
  181. if !ok {
  182. return ""
  183. }
  184. return ipAddressStr
  185. }
  186. func (fields ServerEntryFields) GetWebServerPort() string {
  187. webServerPort, ok := fields["webServerPort"]
  188. if !ok {
  189. return ""
  190. }
  191. webServerPortStr, ok := webServerPort.(string)
  192. if !ok {
  193. return ""
  194. }
  195. return webServerPortStr
  196. }
  197. func (fields ServerEntryFields) GetWebServerSecret() string {
  198. webServerSecret, ok := fields["webServerSecret"]
  199. if !ok {
  200. return ""
  201. }
  202. webServerSecretStr, ok := webServerSecret.(string)
  203. if !ok {
  204. return ""
  205. }
  206. return webServerSecretStr
  207. }
  208. func (fields ServerEntryFields) GetWebServerCertificate() string {
  209. webServerCertificate, ok := fields["webServerCertificate"]
  210. if !ok {
  211. return ""
  212. }
  213. webServerCertificateStr, ok := webServerCertificate.(string)
  214. if !ok {
  215. return ""
  216. }
  217. return webServerCertificateStr
  218. }
  219. func (fields ServerEntryFields) GetConfigurationVersion() int {
  220. configurationVersion, ok := fields["configurationVersion"]
  221. if !ok {
  222. return 0
  223. }
  224. configurationVersionFloat, ok := configurationVersion.(float64)
  225. if !ok {
  226. return 0
  227. }
  228. return int(configurationVersionFloat)
  229. }
  230. func (fields ServerEntryFields) GetLocalSource() string {
  231. localSource, ok := fields["localSource"]
  232. if !ok {
  233. return ""
  234. }
  235. localSourceStr, ok := localSource.(string)
  236. if !ok {
  237. return ""
  238. }
  239. return localSourceStr
  240. }
  241. func (fields ServerEntryFields) SetLocalSource(source string) {
  242. fields["localSource"] = source
  243. }
  244. func (fields ServerEntryFields) GetLocalTimestamp() string {
  245. localTimestamp, ok := fields["localTimestamp"]
  246. if !ok {
  247. return ""
  248. }
  249. localTimestampStr, ok := localTimestamp.(string)
  250. if !ok {
  251. return ""
  252. }
  253. return localTimestampStr
  254. }
  255. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  256. fields["localTimestamp"] = timestamp
  257. }
  258. func (fields ServerEntryFields) HasSignature() bool {
  259. signature, ok := fields["signature"]
  260. if !ok {
  261. return false
  262. }
  263. signatureStr, ok := signature.(string)
  264. if !ok {
  265. return false
  266. }
  267. return signatureStr != ""
  268. }
  269. const signaturePublicKeyDigestSize = 8
  270. // AddSignature signs a server entry and attaches a new field containing the
  271. // signature. Any existing "signature" field will be replaced.
  272. //
  273. // The signature incudes a public key ID that is derived from a digest of the
  274. // public key value. This ID is intended for future use when multiple signing
  275. // keys may be deployed.
  276. func (fields ServerEntryFields) AddSignature(publicKey, privateKey string) error {
  277. // Make a copy so that removing unsigned fields will have no side effects
  278. copyFields := make(ServerEntryFields)
  279. for k, v := range fields {
  280. copyFields[k] = v
  281. }
  282. copyFields.RemoveUnsignedFields()
  283. delete(copyFields, "signature")
  284. // Best practise would be to sign the JSON encoded server entry bytes and
  285. // append the signature to those bytes. However, due to backwards
  286. // compatibility requirements, we must retain the outer server entry encoding
  287. // as-is and insert the signature.
  288. //
  289. // Limitation: since the verifyier must remarshal its server entry before
  290. // verifying, the JSON produced there must be a byte-for-byte match to the
  291. // JSON signed here. The precise output of the JSON encoder that is used,
  292. // "encoding/json", with default formatting, as of Go 1.11.5, is therefore
  293. // part of the signature protocol.
  294. //
  295. // TODO: use a standard, canonical encoding, such as JCS:
  296. // https://tools.ietf.org/id/draft-rundgren-json-canonicalization-scheme-05.html
  297. marshaledFields, err := json.Marshal(copyFields)
  298. if err != nil {
  299. return errors.Trace(err)
  300. }
  301. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  302. if err != nil {
  303. return errors.Trace(err)
  304. }
  305. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  306. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  307. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  308. if err != nil {
  309. return errors.Trace(err)
  310. }
  311. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  312. fields["signature"] = base64.StdEncoding.EncodeToString(
  313. append(publicKeyID, signature...))
  314. return nil
  315. }
  316. // VerifySignature verifies the signature set by AddSignature.
  317. //
  318. // VerifySignature must be called before using any server entry that is
  319. // imported from an untrusted source, such as client-to-client exchange.
  320. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  321. if publicKey == "" {
  322. return errors.TraceNew("missing public key")
  323. }
  324. // Make a copy so that removing unsigned fields will have no side effects
  325. copyFields := make(ServerEntryFields)
  326. for k, v := range fields {
  327. copyFields[k] = v
  328. }
  329. signatureField, ok := copyFields["signature"]
  330. if !ok {
  331. return errors.TraceNew("missing signature field")
  332. }
  333. signatureFieldStr, ok := signatureField.(string)
  334. if !ok {
  335. return errors.TraceNew("invalid signature field")
  336. }
  337. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  338. if err != nil {
  339. return errors.Trace(err)
  340. }
  341. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  342. return errors.TraceNew("invalid signature field length")
  343. }
  344. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  345. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  346. if len(signature) != ed25519.SignatureSize {
  347. return errors.TraceNew("invalid signature length")
  348. }
  349. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  350. if err != nil {
  351. return errors.Trace(err)
  352. }
  353. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  354. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  355. if !bytes.Equal(expectedPublicKeyID, publicKeyID) {
  356. return errors.TraceNew("unexpected public key ID")
  357. }
  358. copyFields.RemoveUnsignedFields()
  359. delete(copyFields, "signature")
  360. marshaledFields, err := json.Marshal(copyFields)
  361. if err != nil {
  362. return errors.Trace(err)
  363. }
  364. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  365. return errors.TraceNew("invalid signature")
  366. }
  367. return nil
  368. }
  369. // RemoveUnsignedFields prepares a server entry for signing or signature
  370. // verification by removing unsigned fields. The JSON marshalling of the
  371. // remaining fields is the data that is signed.
  372. func (fields ServerEntryFields) RemoveUnsignedFields() {
  373. delete(fields, "localSource")
  374. delete(fields, "localTimestamp")
  375. // Only non-local, explicit tags are part of the signature
  376. isLocalDerivedTag := fields["isLocalDerivedTag"]
  377. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  378. if ok && isLocalDerivedTagBool {
  379. delete(fields, "tag")
  380. }
  381. delete(fields, "isLocalDerivedTag")
  382. }
  383. // ToSignedFields checks for a signature and calls RemoveUnsignedFields.
  384. func (fields ServerEntryFields) ToSignedFields() error {
  385. if !fields.HasSignature() {
  386. return errors.TraceNew("missing signature field")
  387. }
  388. fields.RemoveUnsignedFields()
  389. return nil
  390. }
  391. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  392. // server entry signing and verification.
  393. func NewServerEntrySignatureKeyPair() (string, string, error) {
  394. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  395. if err != nil {
  396. return "", "", errors.Trace(err)
  397. }
  398. return base64.StdEncoding.EncodeToString(publicKey),
  399. base64.StdEncoding.EncodeToString(privateKey),
  400. nil
  401. }
  402. // GetCapability returns the server capability corresponding
  403. // to the tunnel protocol.
  404. func GetCapability(protocol string) string {
  405. // The "-OSSH" suffix drop is for legacy compatibility. Newer protocols,
  406. // including in-proxy protocols, use the full protocol name as the
  407. // capability. This avoids ambiguities such as in the case
  408. // of "INPROXY-WEBRTC-OSSH", where a truncated "INPROXY-WEBRTC" is
  409. // ambiguous.
  410. if TunnelProtocolUsesInproxy(protocol) {
  411. return protocol
  412. }
  413. return strings.TrimSuffix(protocol, "-OSSH")
  414. }
  415. // GetTacticsCapability returns the server tactics capability
  416. // corresponding to the tunnel protocol.
  417. func GetTacticsCapability(protocol string) string {
  418. return GetCapability(protocol) + "-TACTICS"
  419. }
  420. // GetServerEntryFields converts a ServerEntry to ServerEntryFields.
  421. //
  422. // Note that a conversion in this direction doesn't retain unrecognized
  423. // fields; see ServerEntryFields comment. Clients should only store
  424. // ServerEntryFields obtained from DecodeServerEntryFields or
  425. // DecodePackedServerEntryFields.
  426. func (serverEntry *ServerEntry) GetServerEntryFields() (ServerEntryFields, error) {
  427. marshaledServerEntry, err := json.Marshal(serverEntry)
  428. if err != nil {
  429. return nil, errors.Trace(err)
  430. }
  431. var serverEntryFields ServerEntryFields
  432. err = json.Unmarshal(marshaledServerEntry, &serverEntryFields)
  433. if err != nil {
  434. return nil, errors.Trace(err)
  435. }
  436. return serverEntryFields, nil
  437. }
  438. // hasCapability indicates if the server entry has the specified capability.
  439. //
  440. // Any internal "PASSTHROUGH-v2 or "PASSTHROUGH" component in the server
  441. // entry's capabilities is ignored. These PASSTHROUGH components are used to
  442. // mask protocols which are running the passthrough mechanisms from older
  443. // clients which do not implement the passthrough messages. Older clients
  444. // will treat these capabilities as unknown protocols and skip them.
  445. //
  446. // Any "QUICv1" capability is treated as "QUIC". "QUICv1" is used to mask the
  447. // QUIC-OSSH capability from older clients to ensure that older clients do
  448. // not send gQUIC packets to second generation QUICv1-only QUIC-OSSH servers.
  449. // New clients must check SupportsOnlyQUICv1 before selecting a QUIC version;
  450. // for "QUICv1", this ensures that new clients also do not select gQUIC to
  451. // QUICv1-only servers.
  452. //
  453. // In-proxy tunnel protocols omit the "v1" and "PASSTHROUGH" suffixes. For
  454. // in-proxy QUIC, gQUIC is never used; and for in-proxy HTTPS/TLS, clients
  455. // always apply PASSTHROUGH-v2.
  456. func (serverEntry *ServerEntry) hasCapability(requiredCapability string) bool {
  457. for _, capability := range serverEntry.Capabilities {
  458. originalCapability := capability
  459. capability = strings.ReplaceAll(capability, "-PASSTHROUGH-v2", "")
  460. capability = strings.ReplaceAll(capability, "-PASSTHROUGH", "")
  461. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  462. if capability == quicCapability+"v1" {
  463. capability = quicCapability
  464. }
  465. if capability == requiredCapability {
  466. return true
  467. }
  468. // Special case: some capabilities may additionally support TLS-OSSH.
  469. // This does not apply to in-proxy TLS-OSSH.
  470. if requiredCapability == GetCapability(TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH) &&
  471. capabilitySupportsTLSOSSH(originalCapability) {
  472. return true
  473. }
  474. }
  475. return false
  476. }
  477. // capabilitySupportsTLSOSSH returns true if and only if the given capability
  478. // supports TLS-OSSH in addition to its primary protocol.
  479. func capabilitySupportsTLSOSSH(capability string) bool {
  480. tlsCapabilities := []string{
  481. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS),
  482. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET),
  483. }
  484. for _, tlsCapability := range tlsCapabilities {
  485. // The TLS capability is additionally supported by UNFRONTED-MEEK-HTTPS
  486. // and UNFRONTED-MEEK-SESSION-TICKET capabilities with passthrough.
  487. if capability == tlsCapability+"-PASSTHROUGH-v2" {
  488. return true
  489. }
  490. }
  491. return false
  492. }
  493. // SupportsProtocol returns true if and only if the ServerEntry has
  494. // the necessary capability to support the specified tunnel protocol.
  495. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  496. requiredCapability := GetCapability(protocol)
  497. return serverEntry.hasCapability(requiredCapability)
  498. }
  499. // ProtocolUsesLegacyPassthrough indicates whether the ServerEntry supports
  500. // the specified protocol using legacy passthrough messages.
  501. //
  502. // There is no corresponding check for v2 passthrough, as clients send v2
  503. // passthrough messages unconditionally, by default, for passthrough
  504. // protocols.
  505. func (serverEntry *ServerEntry) ProtocolUsesLegacyPassthrough(protocol string) bool {
  506. legacyCapability := GetCapability(protocol) + "-PASSTHROUGH"
  507. for _, capability := range serverEntry.Capabilities {
  508. if capability == legacyCapability {
  509. return true
  510. }
  511. }
  512. return false
  513. }
  514. // SupportsOnlyQUICv1 indicates that the QUIC-OSSH server supports only QUICv1
  515. // and gQUIC versions should not be selected, as they will fail to connect
  516. // while sending atypical traffic to the server.
  517. //
  518. // SupportsOnlyQUICv1 strictly applies to QUIC-OSSH and not the in-proxy
  519. // variant.
  520. func (serverEntry *ServerEntry) SupportsOnlyQUICv1() bool {
  521. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  522. return common.Contains(serverEntry.Capabilities, quicCapability+"v1") &&
  523. !common.Contains(serverEntry.Capabilities, quicCapability)
  524. }
  525. // ConditionallyEnabledComponents defines an interface which can be queried to
  526. // determine which conditionally compiled protocol components are present.
  527. type ConditionallyEnabledComponents interface {
  528. QUICEnabled() bool
  529. RefractionNetworkingEnabled() bool
  530. InproxyEnabled() bool
  531. }
  532. // TunnelProtocolPortLists is a map from tunnel protocol names (or "All") to a
  533. // list of port number ranges.
  534. type TunnelProtocolPortLists map[string]*common.PortList
  535. // GetSupportedProtocols returns a list of tunnel protocols supported by the
  536. // ServerEntry's capabilities and allowed by various constraints.
  537. func (serverEntry *ServerEntry) GetSupportedProtocols(
  538. conditionallyEnabled ConditionallyEnabledComponents,
  539. useUpstreamProxy bool,
  540. limitTunnelProtocols TunnelProtocols,
  541. limitTunnelDialPortNumbers TunnelProtocolPortLists,
  542. limitQUICVersions QUICVersions,
  543. excludeIntensive bool) TunnelProtocols {
  544. supportedProtocols := make(TunnelProtocols, 0)
  545. for _, tunnelProtocol := range SupportedTunnelProtocols {
  546. if useUpstreamProxy && !TunnelProtocolSupportsUpstreamProxy(tunnelProtocol) {
  547. continue
  548. }
  549. if common.Contains(DisabledTunnelProtocols, tunnelProtocol) {
  550. continue
  551. }
  552. if len(limitTunnelProtocols) > 0 {
  553. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  554. continue
  555. }
  556. } else {
  557. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  558. continue
  559. }
  560. }
  561. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  562. continue
  563. }
  564. if (TunnelProtocolUsesQUIC(tunnelProtocol) &&
  565. !conditionallyEnabled.QUICEnabled()) ||
  566. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  567. !conditionallyEnabled.RefractionNetworkingEnabled()) ||
  568. (TunnelProtocolUsesInproxy(tunnelProtocol) &&
  569. !conditionallyEnabled.InproxyEnabled()) {
  570. continue
  571. }
  572. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  573. continue
  574. }
  575. // If the server is limiting QUIC versions, at least one must be
  576. // supported. And if tactics is also limiting QUIC versions, there
  577. // must be a common version in both limit lists for this server entry
  578. // to support QUIC-OSSH.
  579. //
  580. // Limitation: to avoid additional complexity, we do not consider
  581. // DisableFrontingProviderQUICVersion here, as fronting providers are
  582. // expected to support QUICv1 and gQUIC is expected to become
  583. // obsolete in general.
  584. if TunnelProtocolUsesQUIC(tunnelProtocol) && len(serverEntry.LimitQUICVersions) > 0 {
  585. if !common.ContainsAny(serverEntry.LimitQUICVersions, SupportedQUICVersions) {
  586. continue
  587. }
  588. if len(limitQUICVersions) > 0 &&
  589. !common.ContainsAny(serverEntry.LimitQUICVersions, limitQUICVersions) {
  590. continue
  591. }
  592. }
  593. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  594. if err != nil {
  595. continue
  596. }
  597. if len(limitTunnelDialPortNumbers) > 0 {
  598. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  599. if !portList.Lookup(dialPortNumber) {
  600. continue
  601. }
  602. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  603. if !portList.Lookup(dialPortNumber) {
  604. continue
  605. }
  606. }
  607. }
  608. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  609. }
  610. return supportedProtocols
  611. }
  612. var frontedMeekHTTPSDialPortNumber = int32(443)
  613. // SetFrontedMeekHTTPDialPortNumber sets the FRONTED-MEEK-OSSH dial port
  614. // number, which defaults to 443. Overriding the port number enables running
  615. // test servers where binding to port 443 is not possible.
  616. func SetFrontedMeekHTTPDialPortNumber(port int) {
  617. atomic.StoreInt32(&frontedMeekHTTPSDialPortNumber, int32(port))
  618. }
  619. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  620. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  621. return 0, errors.TraceNew("protocol not supported")
  622. }
  623. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  624. switch tunnelProtocol {
  625. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  626. if serverEntry.TlsOSSHPort == 0 {
  627. // Special case: a server which supports UNFRONTED-MEEK-HTTPS-OSSH
  628. // or UNFRONTED-MEEK-SESSION-TICKET-OSSH also supports TLS-OSSH
  629. // over the same port.
  630. return serverEntry.MeekServerPort, nil
  631. }
  632. return serverEntry.TlsOSSHPort, nil
  633. case TUNNEL_PROTOCOL_SSH:
  634. return serverEntry.SshPort, nil
  635. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  636. return serverEntry.SshObfuscatedPort, nil
  637. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  638. return serverEntry.SshObfuscatedTapDancePort, nil
  639. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  640. return serverEntry.SshObfuscatedConjurePort, nil
  641. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  642. return serverEntry.SshObfuscatedQUICPort, nil
  643. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  644. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  645. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  646. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  647. return 80, nil
  648. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  649. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  650. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  651. return serverEntry.MeekServerPort, nil
  652. case TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  653. return serverEntry.SshShadowsocksPort, nil
  654. }
  655. } else {
  656. // Distinct dial/listening ports are used for tunnel protocols when
  657. // used as an in-proxy 2nd hop, as the server will require a relayed
  658. // in-proxy broker report for in-proxy 2nd hops.
  659. switch TunnelProtocolMinusInproxy(tunnelProtocol) {
  660. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  661. if serverEntry.InproxyTlsOSSHPort == 0 {
  662. return serverEntry.InproxyMeekPort, nil
  663. }
  664. return serverEntry.InproxyTlsOSSHPort, nil
  665. case TUNNEL_PROTOCOL_SSH:
  666. return serverEntry.InproxySSHPort, nil
  667. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  668. return serverEntry.InproxyOSSHPort, nil
  669. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  670. return serverEntry.InproxyQUICPort, nil
  671. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  672. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  673. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  674. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  675. return 80, nil
  676. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  677. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  678. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  679. return serverEntry.InproxyMeekPort, nil
  680. case TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  681. return serverEntry.InproxyShadowsocksPort, nil
  682. }
  683. }
  684. return 0, errors.TraceNew("unknown protocol")
  685. }
  686. // GetTLSSessionCacheKeyAddress returns a network address (IP:port) that is
  687. // suitable to use as a TLS session cache key.
  688. //
  689. // By default, TLS implementations, including crypto/tls and utls use SNI as a
  690. // session cache key, but this is not a suitable key when SNI is manipulated.
  691. // When SNI is not present, these implementations fall back to using the peer
  692. // remote address, which is also not a suitable key in cases where there is a
  693. // non-TLS-terminating temporary intermediary, such as an in-proxy proxy.
  694. //
  695. // The key is unique to the Psiphon server and tunnel protocol listener. For
  696. // direct tunnel protocols, the key precisely maps TLS sessions to the
  697. // corresponding TLS server. For indirect tunnel protocols, with an
  698. // intermediate TLS server, the key is an approximate map which assumes the
  699. // redials will mostly use the same intermediate TLS server.
  700. //
  701. // Do not use the GetTLSSessionCacheKeyAddress value for dialing.
  702. func (serverEntry *ServerEntry) GetTLSSessionCacheKeyAddress(tunnelProtocol string) (string, error) {
  703. port, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  704. if err != nil {
  705. return "", errors.Trace(err)
  706. }
  707. return net.JoinHostPort(serverEntry.IpAddress, strconv.Itoa(port)), nil
  708. }
  709. // IsValidInproxyDialAddress indicates whether the dial destination
  710. // network/host/port matches the dial parameters for any of the tunnel
  711. // protocols supported by the server entry.
  712. //
  713. // Limitations:
  714. // - TAPDANCE-OSSH and CONJURE-OSSH are not supported.
  715. // - The host header is not considered in the case of fronted protocols.
  716. func (serverEntry *ServerEntry) IsValidInproxyDialAddress(
  717. networkProtocol string, dialHost string, dialPortNumber int) bool {
  718. // The TapDance and Conjure destination addresses are not included
  719. // in the server entry, so TAPDANCE-OSSH and CONJURE-OSSH dial
  720. // destinations cannot be validated for in-proxy use.
  721. for _, tunnelProtocol := range SupportedTunnelProtocols {
  722. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  723. continue
  724. }
  725. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  726. continue
  727. }
  728. usesTCP := TunnelProtocolUsesTCP(tunnelProtocol)
  729. if (usesTCP && networkProtocol != "tcp") || (!usesTCP && networkProtocol != "udp") {
  730. continue
  731. }
  732. tunnelPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  733. if err != nil || tunnelPortNumber != dialPortNumber {
  734. // Silently fail on error as the server entry should be well-formed.
  735. continue
  736. }
  737. if !TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  738. // For all direct protocols, the destination host must be the
  739. // server IP address.
  740. if serverEntry.IpAddress != dialHost {
  741. continue
  742. }
  743. } else {
  744. // For fronted protocols, the destination host may be domain and
  745. // must match either MeekFrontingAddressesRegex or
  746. // MeekFrontingAddresses. As in psiphon.selectFrontingParameters,
  747. // MeekFrontingAddressesRegex takes precedence when not empty.
  748. //
  749. // As the host header value is not checked here, additional
  750. // measures must be taken to ensure the destination is a Psiphon server.
  751. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  752. re, err := regexp.Compile(serverEntry.MeekFrontingAddressesRegex)
  753. if err != nil {
  754. continue
  755. }
  756. // The entire dialHost string must match the regex.
  757. re.Longest()
  758. match := re.FindString(dialHost)
  759. if match == "" || match != dialHost {
  760. continue
  761. }
  762. } else {
  763. if !common.Contains(serverEntry.MeekFrontingAddresses, dialHost) {
  764. continue
  765. }
  766. }
  767. }
  768. // When all of the checks pass for this protocol, the input is a valid
  769. // dial destination.
  770. return true
  771. }
  772. return false
  773. }
  774. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  775. // supported by the ServerEntry's capabilities, that may be used
  776. // for tactics requests.
  777. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  778. supportedProtocols := make([]string, 0)
  779. for _, protocol := range SupportedTunnelProtocols {
  780. if !TunnelProtocolUsesMeek(protocol) {
  781. continue
  782. }
  783. requiredCapability := GetTacticsCapability(protocol)
  784. if !serverEntry.hasCapability(requiredCapability) {
  785. continue
  786. }
  787. supportedProtocols = append(supportedProtocols, protocol)
  788. }
  789. return supportedProtocols
  790. }
  791. // SupportsSSHAPIRequests returns true when the server supports
  792. // SSH API requests.
  793. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  794. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  795. }
  796. func (serverEntry *ServerEntry) HasProviderID() bool {
  797. return serverEntry.ProviderID != ""
  798. }
  799. func (serverEntry *ServerEntry) HasSignature() bool {
  800. return serverEntry.Signature != ""
  801. }
  802. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  803. return TagToDiagnosticID(serverEntry.Tag)
  804. }
  805. // GenerateServerEntryTag creates a server entry tag value that is
  806. // cryptographically derived from the IP address and web server secret in a
  807. // way that is difficult to reverse the IP address value from the tag or
  808. // compute the tag without having the web server secret, a 256-bit random
  809. // value which is unique per server, in addition to the IP address. A database
  810. // consisting only of server entry tags should be resistent to an attack that
  811. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  812. // or some subset of the web server secrets.
  813. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  814. h := hmac.New(sha256.New, []byte(webServerSecret))
  815. h.Write([]byte(ipAddress))
  816. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  817. }
  818. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  819. // sufficient to uniquely identify servers in diagnostics, while also being
  820. // more human readable than emitting the full tag. The tag is used as the base
  821. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  822. // output.
  823. func TagToDiagnosticID(tag string) string {
  824. if len(tag) < 8 {
  825. return "<unknown>"
  826. }
  827. return tag[:8]
  828. }
  829. // EncodeServerEntry returns a string containing the encoding of
  830. // a ServerEntry following Psiphon conventions.
  831. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  832. encodedServerEntry, err := encodeServerEntry(
  833. serverEntry.IpAddress,
  834. serverEntry.WebServerPort,
  835. serverEntry.WebServerSecret,
  836. serverEntry.WebServerCertificate,
  837. serverEntry)
  838. if err != nil {
  839. return "", errors.Trace(err)
  840. }
  841. return encodedServerEntry, nil
  842. }
  843. // EncodeServerEntryFields returns a string containing the encoding of
  844. // ServerEntryFields following Psiphon conventions.
  845. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  846. encodedServerEntry, err := encodeServerEntry(
  847. serverEntryFields.GetIPAddress(),
  848. serverEntryFields.GetWebServerPort(),
  849. serverEntryFields.GetWebServerSecret(),
  850. serverEntryFields.GetWebServerCertificate(),
  851. serverEntryFields)
  852. if err != nil {
  853. return "", errors.Trace(err)
  854. }
  855. return encodedServerEntry, nil
  856. }
  857. func encodeServerEntry(
  858. prefixIPAddress string,
  859. prefixWebServerPort string,
  860. prefixWebServerSecret string,
  861. prefixWebServerCertificate string,
  862. serverEntry interface{}) (string, error) {
  863. serverEntryJSON, err := json.Marshal(serverEntry)
  864. if err != nil {
  865. return "", errors.Trace(err)
  866. }
  867. // Legacy clients use a space-delimited fields prefix, and all clients expect
  868. // to at least parse the prefix in order to skip over it.
  869. //
  870. // When the server entry has no web API server certificate, the entire prefix
  871. // can be compacted down to single character placeholders. Clients that can
  872. // use the ssh API always prefer it over the web API and won't use the prefix
  873. // values.
  874. if len(prefixWebServerCertificate) == 0 {
  875. prefixIPAddress = "0"
  876. prefixWebServerPort = "0"
  877. prefixWebServerSecret = "0"
  878. prefixWebServerCertificate = "0"
  879. }
  880. return hex.EncodeToString([]byte(fmt.Sprintf(
  881. "%s %s %s %s %s",
  882. prefixIPAddress,
  883. prefixWebServerPort,
  884. prefixWebServerSecret,
  885. prefixWebServerCertificate,
  886. serverEntryJSON))), nil
  887. }
  888. // DecodeServerEntry extracts a server entry from the encoding
  889. // used by remote server lists and Psiphon server handshake requests.
  890. //
  891. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  892. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  893. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  894. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  895. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  896. // should be a RFC 3339 formatted string. These local fields are stored with the
  897. // server entry and reported to the server as stats (a coarse granularity timestamp
  898. // is reported).
  899. func DecodeServerEntry(
  900. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  901. serverEntry := new(ServerEntry)
  902. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  903. if err != nil {
  904. return nil, errors.Trace(err)
  905. }
  906. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  907. serverEntry.LocalSource = serverEntrySource
  908. serverEntry.LocalTimestamp = timestamp
  909. return serverEntry, nil
  910. }
  911. // DecodeServerEntryFields extracts an encoded server entry into a
  912. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  913. // not in ServerEntry are retained in the ServerEntryFields.
  914. //
  915. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  916. // inputs are non-blank.
  917. func DecodeServerEntryFields(
  918. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  919. serverEntryFields := make(ServerEntryFields)
  920. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  921. if err != nil {
  922. return nil, errors.Trace(err)
  923. }
  924. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  925. if serverEntrySource != "" {
  926. serverEntryFields.SetLocalSource(serverEntrySource)
  927. }
  928. if timestamp != "" {
  929. serverEntryFields.SetLocalTimestamp(timestamp)
  930. }
  931. return serverEntryFields, nil
  932. }
  933. func decodeServerEntry(
  934. encodedServerEntry, timestamp, serverEntrySource string,
  935. target interface{}) error {
  936. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  937. if err != nil {
  938. return errors.Trace(err)
  939. }
  940. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  941. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  942. if len(fields) != 5 {
  943. return errors.TraceNew("invalid encoded server entry")
  944. }
  945. err = json.Unmarshal(fields[4], target)
  946. if err != nil {
  947. return errors.Trace(err)
  948. }
  949. return nil
  950. }
  951. // ValidateServerEntryFields checks for malformed server entries.
  952. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  953. // Checks for a valid ipAddress. This is important since the IP
  954. // address is the key used to store/lookup the server entry.
  955. ipAddress := serverEntryFields.GetIPAddress()
  956. if net.ParseIP(ipAddress) == nil {
  957. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  958. }
  959. // TODO: validate more fields?
  960. // Ensure locally initialized fields have been set.
  961. source := serverEntryFields.GetLocalSource()
  962. if !common.ContainsWildcard(
  963. SupportedServerEntrySources, source) {
  964. return errors.Tracef("server entry has invalid source: %s", source)
  965. }
  966. timestamp := serverEntryFields.GetLocalTimestamp()
  967. _, err := time.Parse(time.RFC3339, timestamp)
  968. if err != nil {
  969. return errors.Tracef("server entry has invalid timestamp: %s", err)
  970. }
  971. return nil
  972. }
  973. // DecodeServerEntryList extracts server entries from the list encoding
  974. // used by remote server lists and Psiphon server handshake requests.
  975. // Each server entry is validated and invalid entries are skipped.
  976. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  977. func DecodeServerEntryList(
  978. encodedServerEntryList, timestamp,
  979. serverEntrySource string) ([]ServerEntryFields, error) {
  980. serverEntries := make([]ServerEntryFields, 0)
  981. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  982. if len(encodedServerEntry) == 0 {
  983. continue
  984. }
  985. // TODO: skip this entry and continue if can't decode?
  986. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  987. if err != nil {
  988. return nil, errors.Trace(err)
  989. }
  990. if ValidateServerEntryFields(serverEntryFields) != nil {
  991. // Skip this entry and continue with the next one
  992. // TODO: invoke a logging callback
  993. continue
  994. }
  995. serverEntries = append(serverEntries, serverEntryFields)
  996. }
  997. return serverEntries, nil
  998. }
  999. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  1000. // operation, loading only one server entry into memory at a time.
  1001. type StreamingServerEntryDecoder struct {
  1002. scanner *bufio.Scanner
  1003. timestamp string
  1004. serverEntrySource string
  1005. }
  1006. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  1007. func NewStreamingServerEntryDecoder(
  1008. encodedServerEntryListReader io.Reader,
  1009. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  1010. return &StreamingServerEntryDecoder{
  1011. scanner: bufio.NewScanner(encodedServerEntryListReader),
  1012. timestamp: timestamp,
  1013. serverEntrySource: serverEntrySource,
  1014. }
  1015. }
  1016. // Next reads and decodes, and validates the next server entry from the
  1017. // input stream, returning a nil server entry when the stream is complete.
  1018. //
  1019. // Limitations:
  1020. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  1021. // the default buffer size which this decoder uses. This is 64K.
  1022. // - DecodeServerEntry is called on each encoded server entry line, which
  1023. // will allocate memory to hex decode and JSON deserialze the server
  1024. // entry. As this is not presently reusing a fixed buffer, each call
  1025. // will allocate additional memory; garbage collection is necessary to
  1026. // reclaim that memory for reuse for the next server entry.
  1027. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  1028. for {
  1029. if !decoder.scanner.Scan() {
  1030. return nil, errors.Trace(decoder.scanner.Err())
  1031. }
  1032. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  1033. // TODO: skip this entry and continue if can't decode?
  1034. serverEntryFields, err := DecodeServerEntryFields(
  1035. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  1036. if err != nil {
  1037. return nil, errors.Trace(err)
  1038. }
  1039. if ValidateServerEntryFields(serverEntryFields) != nil {
  1040. // Skip this entry and continue with the next one
  1041. // TODO: invoke a logging callback
  1042. continue
  1043. }
  1044. return serverEntryFields, nil
  1045. }
  1046. }