serverEntry.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. // IsTacticsCapability indicates if the specified capability is a server
  421. // tactics capability.
  422. func IsTacticsCapability(protocol string) bool {
  423. return strings.HasSuffix(protocol, "-TACTICS")
  424. }
  425. // GetServerEntryFields converts a ServerEntry to ServerEntryFields.
  426. //
  427. // Note that a conversion in this direction doesn't retain unrecognized
  428. // fields; see ServerEntryFields comment. Clients should only store
  429. // ServerEntryFields obtained from DecodeServerEntryFields or
  430. // DecodePackedServerEntryFields.
  431. func (serverEntry *ServerEntry) GetServerEntryFields() (ServerEntryFields, error) {
  432. marshaledServerEntry, err := json.Marshal(serverEntry)
  433. if err != nil {
  434. return nil, errors.Trace(err)
  435. }
  436. var serverEntryFields ServerEntryFields
  437. err = json.Unmarshal(marshaledServerEntry, &serverEntryFields)
  438. if err != nil {
  439. return nil, errors.Trace(err)
  440. }
  441. return serverEntryFields, nil
  442. }
  443. // hasCapability indicates if the server entry has the specified capability.
  444. //
  445. // Any internal "PASSTHROUGH-v2 or "PASSTHROUGH" component in the server
  446. // entry's capabilities is ignored. These PASSTHROUGH components are used to
  447. // mask protocols which are running the passthrough mechanisms from older
  448. // clients which do not implement the passthrough messages. Older clients
  449. // will treat these capabilities as unknown protocols and skip them.
  450. //
  451. // Any "QUICv1" capability is treated as "QUIC". "QUICv1" is used to mask the
  452. // QUIC-OSSH capability from older clients to ensure that older clients do
  453. // not send gQUIC packets to second generation QUICv1-only QUIC-OSSH servers.
  454. // New clients must check SupportsOnlyQUICv1 before selecting a QUIC version;
  455. // for "QUICv1", this ensures that new clients also do not select gQUIC to
  456. // QUICv1-only servers.
  457. //
  458. // In-proxy tunnel protocols omit the "v1" and "PASSTHROUGH" suffixes. For
  459. // in-proxy QUIC, gQUIC is never used; and for in-proxy HTTPS/TLS, clients
  460. // always apply PASSTHROUGH-v2.
  461. func (serverEntry *ServerEntry) hasCapability(requiredCapability string) bool {
  462. for _, capability := range serverEntry.Capabilities {
  463. originalCapability := capability
  464. capability = strings.ReplaceAll(capability, "-PASSTHROUGH-v2", "")
  465. capability = strings.ReplaceAll(capability, "-PASSTHROUGH", "")
  466. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  467. if capability == quicCapability+"v1" {
  468. capability = quicCapability
  469. }
  470. if capability == requiredCapability {
  471. return true
  472. }
  473. // Special case: some capabilities may additionally support TLS-OSSH.
  474. // This does not apply to in-proxy TLS-OSSH.
  475. if requiredCapability == GetCapability(TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH) &&
  476. capabilitySupportsTLSOSSH(originalCapability) {
  477. return true
  478. }
  479. }
  480. return false
  481. }
  482. // capabilitySupportsTLSOSSH returns true if and only if the given capability
  483. // supports TLS-OSSH in addition to its primary protocol.
  484. func capabilitySupportsTLSOSSH(capability string) bool {
  485. tlsCapabilities := []string{
  486. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS),
  487. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET),
  488. }
  489. for _, tlsCapability := range tlsCapabilities {
  490. // The TLS capability is additionally supported by UNFRONTED-MEEK-HTTPS
  491. // and UNFRONTED-MEEK-SESSION-TICKET capabilities with passthrough.
  492. if capability == tlsCapability+"-PASSTHROUGH-v2" {
  493. return true
  494. }
  495. }
  496. return false
  497. }
  498. // SupportsProtocol returns true if and only if the ServerEntry has
  499. // the necessary capability to support the specified tunnel protocol.
  500. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  501. requiredCapability := GetCapability(protocol)
  502. return serverEntry.hasCapability(requiredCapability)
  503. }
  504. // ProtocolUsesLegacyPassthrough indicates whether the ServerEntry supports
  505. // the specified protocol using legacy passthrough messages.
  506. //
  507. // There is no corresponding check for v2 passthrough, as clients send v2
  508. // passthrough messages unconditionally, by default, for passthrough
  509. // protocols.
  510. func (serverEntry *ServerEntry) ProtocolUsesLegacyPassthrough(protocol string) bool {
  511. legacyCapability := GetCapability(protocol) + "-PASSTHROUGH"
  512. for _, capability := range serverEntry.Capabilities {
  513. if capability == legacyCapability {
  514. return true
  515. }
  516. }
  517. return false
  518. }
  519. // SupportsOnlyQUICv1 indicates that the QUIC-OSSH server supports only QUICv1
  520. // and gQUIC versions should not be selected, as they will fail to connect
  521. // while sending atypical traffic to the server.
  522. //
  523. // SupportsOnlyQUICv1 strictly applies to QUIC-OSSH and not the in-proxy
  524. // variant.
  525. func (serverEntry *ServerEntry) SupportsOnlyQUICv1() bool {
  526. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  527. return common.Contains(serverEntry.Capabilities, quicCapability+"v1") &&
  528. !common.Contains(serverEntry.Capabilities, quicCapability)
  529. }
  530. // ConditionallyEnabledComponents defines an interface which can be queried to
  531. // determine which conditionally compiled protocol components are present.
  532. type ConditionallyEnabledComponents interface {
  533. QUICEnabled() bool
  534. RefractionNetworkingEnabled() bool
  535. InproxyEnabled() bool
  536. }
  537. // TunnelProtocolPortLists is a map from tunnel protocol names (or "All") to a
  538. // list of port number ranges.
  539. type TunnelProtocolPortLists map[string]*common.PortList
  540. // GetSupportedProtocols returns a list of tunnel protocols supported by the
  541. // ServerEntry's capabilities and allowed by various constraints.
  542. func (serverEntry *ServerEntry) GetSupportedProtocols(
  543. conditionallyEnabled ConditionallyEnabledComponents,
  544. useUpstreamProxy bool,
  545. limitTunnelProtocols TunnelProtocols,
  546. limitTunnelDialPortNumbers TunnelProtocolPortLists,
  547. limitQUICVersions QUICVersions,
  548. excludeIntensive bool) TunnelProtocols {
  549. supportedProtocols := make(TunnelProtocols, 0)
  550. for _, tunnelProtocol := range SupportedTunnelProtocols {
  551. if useUpstreamProxy && !TunnelProtocolSupportsUpstreamProxy(tunnelProtocol) {
  552. continue
  553. }
  554. if common.Contains(DisabledTunnelProtocols, tunnelProtocol) {
  555. continue
  556. }
  557. if len(limitTunnelProtocols) > 0 {
  558. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  559. continue
  560. }
  561. } else {
  562. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  563. continue
  564. }
  565. }
  566. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  567. continue
  568. }
  569. if (TunnelProtocolUsesQUIC(tunnelProtocol) &&
  570. !conditionallyEnabled.QUICEnabled()) ||
  571. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  572. !conditionallyEnabled.RefractionNetworkingEnabled()) ||
  573. (TunnelProtocolUsesInproxy(tunnelProtocol) &&
  574. !conditionallyEnabled.InproxyEnabled()) {
  575. continue
  576. }
  577. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  578. continue
  579. }
  580. // If the server is limiting QUIC versions, at least one must be
  581. // supported. And if tactics is also limiting QUIC versions, there
  582. // must be a common version in both limit lists for this server entry
  583. // to support QUIC-OSSH.
  584. //
  585. // Limitation: to avoid additional complexity, we do not consider
  586. // DisableFrontingProviderQUICVersion here, as fronting providers are
  587. // expected to support QUICv1 and gQUIC is expected to become
  588. // obsolete in general.
  589. if TunnelProtocolUsesQUIC(tunnelProtocol) && len(serverEntry.LimitQUICVersions) > 0 {
  590. if !common.ContainsAny(serverEntry.LimitQUICVersions, SupportedQUICVersions) {
  591. continue
  592. }
  593. if len(limitQUICVersions) > 0 &&
  594. !common.ContainsAny(serverEntry.LimitQUICVersions, limitQUICVersions) {
  595. continue
  596. }
  597. }
  598. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  599. if err != nil {
  600. continue
  601. }
  602. if len(limitTunnelDialPortNumbers) > 0 {
  603. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  604. if !portList.Lookup(dialPortNumber) {
  605. continue
  606. }
  607. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  608. if !portList.Lookup(dialPortNumber) {
  609. continue
  610. }
  611. }
  612. }
  613. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  614. }
  615. return supportedProtocols
  616. }
  617. var frontedMeekHTTPSDialPortNumber = int32(443)
  618. // SetFrontedMeekHTTPDialPortNumber sets the FRONTED-MEEK-OSSH dial port
  619. // number, which defaults to 443. Overriding the port number enables running
  620. // test servers where binding to port 443 is not possible.
  621. func SetFrontedMeekHTTPDialPortNumber(port int) {
  622. atomic.StoreInt32(&frontedMeekHTTPSDialPortNumber, int32(port))
  623. }
  624. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  625. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  626. return 0, errors.TraceNew("protocol not supported")
  627. }
  628. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  629. switch tunnelProtocol {
  630. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  631. if serverEntry.TlsOSSHPort == 0 {
  632. // Special case: a server which supports UNFRONTED-MEEK-HTTPS-OSSH
  633. // or UNFRONTED-MEEK-SESSION-TICKET-OSSH also supports TLS-OSSH
  634. // over the same port.
  635. return serverEntry.MeekServerPort, nil
  636. }
  637. return serverEntry.TlsOSSHPort, nil
  638. case TUNNEL_PROTOCOL_SSH:
  639. return serverEntry.SshPort, nil
  640. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  641. return serverEntry.SshObfuscatedPort, nil
  642. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  643. return serverEntry.SshObfuscatedTapDancePort, nil
  644. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  645. return serverEntry.SshObfuscatedConjurePort, nil
  646. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  647. return serverEntry.SshObfuscatedQUICPort, nil
  648. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  649. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  650. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  651. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  652. return 80, nil
  653. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  654. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  655. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  656. return serverEntry.MeekServerPort, nil
  657. case TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  658. return serverEntry.SshShadowsocksPort, nil
  659. }
  660. } else {
  661. // Distinct dial/listening ports are used for tunnel protocols when
  662. // used as an in-proxy 2nd hop, as the server will require a relayed
  663. // in-proxy broker report for in-proxy 2nd hops.
  664. switch TunnelProtocolMinusInproxy(tunnelProtocol) {
  665. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  666. if serverEntry.InproxyTlsOSSHPort == 0 {
  667. return serverEntry.InproxyMeekPort, nil
  668. }
  669. return serverEntry.InproxyTlsOSSHPort, nil
  670. case TUNNEL_PROTOCOL_SSH:
  671. return serverEntry.InproxySSHPort, nil
  672. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  673. return serverEntry.InproxyOSSHPort, nil
  674. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  675. return serverEntry.InproxyQUICPort, nil
  676. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  677. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  678. return int(atomic.LoadInt32(&frontedMeekHTTPSDialPortNumber)), nil
  679. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  680. return 80, nil
  681. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  682. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  683. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  684. return serverEntry.InproxyMeekPort, nil
  685. case TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  686. return serverEntry.InproxyShadowsocksPort, nil
  687. }
  688. }
  689. return 0, errors.TraceNew("unknown protocol")
  690. }
  691. // GetTLSSessionCacheKeyAddress returns a network address (IP:port) that is
  692. // suitable to use as a TLS session cache key.
  693. //
  694. // By default, TLS implementations, including crypto/tls and utls use SNI as a
  695. // session cache key, but this is not a suitable key when SNI is manipulated.
  696. // When SNI is not present, these implementations fall back to using the peer
  697. // remote address, which is also not a suitable key in cases where there is a
  698. // non-TLS-terminating temporary intermediary, such as an in-proxy proxy.
  699. //
  700. // The key is unique to the Psiphon server and tunnel protocol listener. For
  701. // direct tunnel protocols, the key precisely maps TLS sessions to the
  702. // corresponding TLS server. For indirect tunnel protocols, with an
  703. // intermediate TLS server, the key is an approximate map which assumes the
  704. // redials will mostly use the same intermediate TLS server.
  705. //
  706. // Do not use the GetTLSSessionCacheKeyAddress value for dialing.
  707. func (serverEntry *ServerEntry) GetTLSSessionCacheKeyAddress(tunnelProtocol string) (string, error) {
  708. port, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  709. if err != nil {
  710. return "", errors.Trace(err)
  711. }
  712. return net.JoinHostPort(serverEntry.IpAddress, strconv.Itoa(port)), nil
  713. }
  714. // IsValidInproxyDialAddress indicates whether the dial destination
  715. // network/host/port matches the dial parameters for any of the tunnel
  716. // protocols supported by the server entry.
  717. //
  718. // Limitations:
  719. // - TAPDANCE-OSSH and CONJURE-OSSH are not supported.
  720. // - The host header is not considered in the case of fronted protocols.
  721. func (serverEntry *ServerEntry) IsValidInproxyDialAddress(
  722. networkProtocol string, dialHost string, dialPortNumber int) bool {
  723. // The TapDance and Conjure destination addresses are not included
  724. // in the server entry, so TAPDANCE-OSSH and CONJURE-OSSH dial
  725. // destinations cannot be validated for in-proxy use.
  726. for _, tunnelProtocol := range SupportedTunnelProtocols {
  727. if !TunnelProtocolUsesInproxy(tunnelProtocol) {
  728. continue
  729. }
  730. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  731. continue
  732. }
  733. usesTCP := TunnelProtocolUsesTCP(tunnelProtocol)
  734. if (usesTCP && networkProtocol != "tcp") || (!usesTCP && networkProtocol != "udp") {
  735. continue
  736. }
  737. tunnelPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  738. if err != nil || tunnelPortNumber != dialPortNumber {
  739. // Silently fail on error as the server entry should be well-formed.
  740. continue
  741. }
  742. if !TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  743. // For all direct protocols, the destination host must be the
  744. // server IP address.
  745. if serverEntry.IpAddress != dialHost {
  746. continue
  747. }
  748. } else {
  749. // For fronted protocols, the destination host may be domain and
  750. // must match either MeekFrontingAddressesRegex or
  751. // MeekFrontingAddresses. As in psiphon.selectFrontingParameters,
  752. // MeekFrontingAddressesRegex takes precedence when not empty.
  753. //
  754. // As the host header value is not checked here, additional
  755. // measures must be taken to ensure the destination is a Psiphon server.
  756. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  757. re, err := regexp.Compile(serverEntry.MeekFrontingAddressesRegex)
  758. if err != nil {
  759. continue
  760. }
  761. // The entire dialHost string must match the regex.
  762. re.Longest()
  763. match := re.FindString(dialHost)
  764. if match == "" || match != dialHost {
  765. continue
  766. }
  767. } else {
  768. if !common.Contains(serverEntry.MeekFrontingAddresses, dialHost) {
  769. continue
  770. }
  771. }
  772. }
  773. // When all of the checks pass for this protocol, the input is a valid
  774. // dial destination.
  775. return true
  776. }
  777. return false
  778. }
  779. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  780. // supported by the ServerEntry's capabilities, that may be used
  781. // for tactics requests.
  782. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  783. supportedProtocols := make([]string, 0)
  784. for _, protocol := range SupportedTunnelProtocols {
  785. if !TunnelProtocolUsesMeek(protocol) {
  786. continue
  787. }
  788. requiredCapability := GetTacticsCapability(protocol)
  789. if !serverEntry.hasCapability(requiredCapability) {
  790. continue
  791. }
  792. supportedProtocols = append(supportedProtocols, protocol)
  793. }
  794. return supportedProtocols
  795. }
  796. // SupportsSSHAPIRequests returns true when the server supports
  797. // SSH API requests.
  798. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  799. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  800. }
  801. func (serverEntry *ServerEntry) HasProviderID() bool {
  802. return serverEntry.ProviderID != ""
  803. }
  804. func (serverEntry *ServerEntry) HasSignature() bool {
  805. return serverEntry.Signature != ""
  806. }
  807. func (serverEntry *ServerEntry) GetTag() string {
  808. if serverEntry.Tag != "" {
  809. return serverEntry.Tag
  810. }
  811. return GenerateServerEntryTag(
  812. serverEntry.IpAddress, serverEntry.WebServerSecret)
  813. }
  814. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  815. return TagToDiagnosticID(serverEntry.GetTag())
  816. }
  817. // GenerateServerEntryTag creates a server entry tag value that is
  818. // cryptographically derived from the IP address and web server secret in a
  819. // way that is difficult to reverse the IP address value from the tag or
  820. // compute the tag without having the web server secret, a 256-bit random
  821. // value which is unique per server, in addition to the IP address. A database
  822. // consisting only of server entry tags should be resistent to an attack that
  823. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  824. // or some subset of the web server secrets.
  825. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  826. h := hmac.New(sha256.New, []byte(webServerSecret))
  827. h.Write([]byte(ipAddress))
  828. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  829. }
  830. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  831. // sufficient to uniquely identify servers in diagnostics, while also being
  832. // more human readable than emitting the full tag. The tag is used as the base
  833. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  834. // output.
  835. func TagToDiagnosticID(tag string) string {
  836. if len(tag) < 8 {
  837. return "<unknown>"
  838. }
  839. return tag[:8]
  840. }
  841. // EncodeServerEntry returns a string containing the encoding of
  842. // a ServerEntry following Psiphon conventions.
  843. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  844. encodedServerEntry, err := encodeServerEntry(
  845. serverEntry.IpAddress,
  846. serverEntry.WebServerPort,
  847. serverEntry.WebServerSecret,
  848. serverEntry.WebServerCertificate,
  849. serverEntry)
  850. if err != nil {
  851. return "", errors.Trace(err)
  852. }
  853. return encodedServerEntry, nil
  854. }
  855. // EncodeServerEntryFields returns a string containing the encoding of
  856. // ServerEntryFields following Psiphon conventions.
  857. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  858. encodedServerEntry, err := encodeServerEntry(
  859. serverEntryFields.GetIPAddress(),
  860. serverEntryFields.GetWebServerPort(),
  861. serverEntryFields.GetWebServerSecret(),
  862. serverEntryFields.GetWebServerCertificate(),
  863. serverEntryFields)
  864. if err != nil {
  865. return "", errors.Trace(err)
  866. }
  867. return encodedServerEntry, nil
  868. }
  869. func encodeServerEntry(
  870. prefixIPAddress string,
  871. prefixWebServerPort string,
  872. prefixWebServerSecret string,
  873. prefixWebServerCertificate string,
  874. serverEntry interface{}) (string, error) {
  875. serverEntryJSON, err := json.Marshal(serverEntry)
  876. if err != nil {
  877. return "", errors.Trace(err)
  878. }
  879. // Legacy clients use a space-delimited fields prefix, and all clients expect
  880. // to at least parse the prefix in order to skip over it.
  881. //
  882. // When the server entry has no web API server certificate, the entire prefix
  883. // can be compacted down to single character placeholders. Clients that can
  884. // use the ssh API always prefer it over the web API and won't use the prefix
  885. // values.
  886. if len(prefixWebServerCertificate) == 0 {
  887. prefixIPAddress = "0"
  888. prefixWebServerPort = "0"
  889. prefixWebServerSecret = "0"
  890. prefixWebServerCertificate = "0"
  891. }
  892. return hex.EncodeToString([]byte(fmt.Sprintf(
  893. "%s %s %s %s %s",
  894. prefixIPAddress,
  895. prefixWebServerPort,
  896. prefixWebServerSecret,
  897. prefixWebServerCertificate,
  898. serverEntryJSON))), nil
  899. }
  900. // DecodeServerEntry extracts a server entry from the encoding
  901. // used by remote server lists and Psiphon server handshake requests.
  902. //
  903. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  904. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  905. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  906. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  907. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  908. // should be a RFC 3339 formatted string. These local fields are stored with the
  909. // server entry and reported to the server as stats (a coarse granularity timestamp
  910. // is reported).
  911. func DecodeServerEntry(
  912. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  913. serverEntry := new(ServerEntry)
  914. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  915. if err != nil {
  916. return nil, errors.Trace(err)
  917. }
  918. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  919. serverEntry.LocalSource = serverEntrySource
  920. serverEntry.LocalTimestamp = timestamp
  921. return serverEntry, nil
  922. }
  923. // DecodeServerEntryFields extracts an encoded server entry into a
  924. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  925. // not in ServerEntry are retained in the ServerEntryFields.
  926. //
  927. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  928. // inputs are non-blank.
  929. func DecodeServerEntryFields(
  930. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  931. serverEntryFields := make(ServerEntryFields)
  932. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  933. if err != nil {
  934. return nil, errors.Trace(err)
  935. }
  936. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  937. if serverEntrySource != "" {
  938. serverEntryFields.SetLocalSource(serverEntrySource)
  939. }
  940. if timestamp != "" {
  941. serverEntryFields.SetLocalTimestamp(timestamp)
  942. }
  943. return serverEntryFields, nil
  944. }
  945. func decodeServerEntry(
  946. encodedServerEntry, timestamp, serverEntrySource string,
  947. target interface{}) error {
  948. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  949. if err != nil {
  950. return errors.Trace(err)
  951. }
  952. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  953. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  954. if len(fields) != 5 {
  955. return errors.TraceNew("invalid encoded server entry")
  956. }
  957. err = json.Unmarshal(fields[4], target)
  958. if err != nil {
  959. return errors.Trace(err)
  960. }
  961. return nil
  962. }
  963. // ValidateServerEntryFields checks for malformed server entries.
  964. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  965. // Checks for a valid ipAddress. This is important since the IP
  966. // address is the key used to store/lookup the server entry.
  967. ipAddress := serverEntryFields.GetIPAddress()
  968. if net.ParseIP(ipAddress) == nil {
  969. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  970. }
  971. // TODO: validate more fields?
  972. // Ensure locally initialized fields have been set.
  973. source := serverEntryFields.GetLocalSource()
  974. if !common.ContainsWildcard(
  975. SupportedServerEntrySources, source) {
  976. return errors.Tracef("server entry has invalid source: %s", source)
  977. }
  978. timestamp := serverEntryFields.GetLocalTimestamp()
  979. _, err := time.Parse(time.RFC3339, timestamp)
  980. if err != nil {
  981. return errors.Tracef("server entry has invalid timestamp: %s", err)
  982. }
  983. return nil
  984. }
  985. // DecodeServerEntryList extracts server entries from the list encoding
  986. // used by remote server lists and Psiphon server handshake requests.
  987. // Each server entry is validated and invalid entries are skipped.
  988. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  989. func DecodeServerEntryList(
  990. encodedServerEntryList, timestamp,
  991. serverEntrySource string) ([]ServerEntryFields, error) {
  992. serverEntries := make([]ServerEntryFields, 0)
  993. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  994. if len(encodedServerEntry) == 0 {
  995. continue
  996. }
  997. // TODO: skip this entry and continue if can't decode?
  998. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  999. if err != nil {
  1000. return nil, errors.Trace(err)
  1001. }
  1002. if ValidateServerEntryFields(serverEntryFields) != nil {
  1003. // Skip this entry and continue with the next one
  1004. // TODO: invoke a logging callback
  1005. continue
  1006. }
  1007. serverEntries = append(serverEntries, serverEntryFields)
  1008. }
  1009. return serverEntries, nil
  1010. }
  1011. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  1012. // operation, loading only one server entry into memory at a time.
  1013. type StreamingServerEntryDecoder struct {
  1014. scanner *bufio.Scanner
  1015. timestamp string
  1016. serverEntrySource string
  1017. }
  1018. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  1019. func NewStreamingServerEntryDecoder(
  1020. encodedServerEntryListReader io.Reader,
  1021. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  1022. return &StreamingServerEntryDecoder{
  1023. scanner: bufio.NewScanner(encodedServerEntryListReader),
  1024. timestamp: timestamp,
  1025. serverEntrySource: serverEntrySource,
  1026. }
  1027. }
  1028. // Next reads and decodes, and validates the next server entry from the
  1029. // input stream, returning a nil server entry when the stream is complete.
  1030. //
  1031. // Limitations:
  1032. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  1033. // the default buffer size which this decoder uses. This is 64K.
  1034. // - DecodeServerEntry is called on each encoded server entry line, which
  1035. // will allocate memory to hex decode and JSON deserialze the server
  1036. // entry. As this is not presently reusing a fixed buffer, each call
  1037. // will allocate additional memory; garbage collection is necessary to
  1038. // reclaim that memory for reuse for the next server entry.
  1039. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  1040. for {
  1041. if !decoder.scanner.Scan() {
  1042. return nil, errors.Trace(decoder.scanner.Err())
  1043. }
  1044. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  1045. // TODO: skip this entry and continue if can't decode?
  1046. serverEntryFields, err := DecodeServerEntryFields(
  1047. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  1048. if err != nil {
  1049. return nil, errors.Trace(err)
  1050. }
  1051. if ValidateServerEntryFields(serverEntryFields) != nil {
  1052. // Skip this entry and continue with the next one
  1053. // TODO: invoke a logging callback
  1054. continue
  1055. }
  1056. return serverEntryFields, nil
  1057. }
  1058. }