serverEntry.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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 SupportedServerEntrySources.
  905. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  906. // should be a RFC 3339 formatted string. These local fields are stored with the
  907. // server entry and reported to the server as stats (a coarse granularity timestamp
  908. // is reported).
  909. func DecodeServerEntry(
  910. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  911. serverEntry := new(ServerEntry)
  912. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  913. if err != nil {
  914. return nil, errors.Trace(err)
  915. }
  916. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  917. serverEntry.LocalSource = serverEntrySource
  918. serverEntry.LocalTimestamp = timestamp
  919. return serverEntry, nil
  920. }
  921. // DecodeServerEntryFields extracts an encoded server entry into a
  922. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  923. // not in ServerEntry are retained in the ServerEntryFields.
  924. //
  925. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  926. // inputs are non-blank.
  927. func DecodeServerEntryFields(
  928. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  929. serverEntryFields := make(ServerEntryFields)
  930. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  931. if err != nil {
  932. return nil, errors.Trace(err)
  933. }
  934. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  935. if serverEntrySource != "" {
  936. serverEntryFields.SetLocalSource(serverEntrySource)
  937. }
  938. if timestamp != "" {
  939. serverEntryFields.SetLocalTimestamp(timestamp)
  940. }
  941. return serverEntryFields, nil
  942. }
  943. func decodeServerEntry(
  944. encodedServerEntry, timestamp, serverEntrySource string,
  945. target interface{}) error {
  946. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  947. if err != nil {
  948. return errors.Trace(err)
  949. }
  950. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  951. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  952. if len(fields) != 5 {
  953. return errors.TraceNew("invalid encoded server entry")
  954. }
  955. err = json.Unmarshal(fields[4], target)
  956. if err != nil {
  957. return errors.Trace(err)
  958. }
  959. return nil
  960. }
  961. // ValidateServerEntryFields checks for malformed server entries.
  962. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  963. // Checks for a valid ipAddress. This is important since the IP
  964. // address is the key used to store/lookup the server entry.
  965. ipAddress := serverEntryFields.GetIPAddress()
  966. if net.ParseIP(ipAddress) == nil {
  967. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  968. }
  969. // TODO: validate more fields?
  970. // Ensure locally initialized fields have been set.
  971. source := serverEntryFields.GetLocalSource()
  972. if !common.ContainsWildcard(
  973. SupportedServerEntrySources, source) {
  974. return errors.Tracef("server entry has invalid source: %s", source)
  975. }
  976. timestamp := serverEntryFields.GetLocalTimestamp()
  977. _, err := time.Parse(time.RFC3339, timestamp)
  978. if err != nil {
  979. return errors.Tracef("server entry has invalid timestamp: %s", err)
  980. }
  981. return nil
  982. }
  983. // DecodeServerEntryList extracts server entries from the list encoding
  984. // used by remote server lists and Psiphon server handshake requests.
  985. // Each server entry is validated and invalid entries are skipped.
  986. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  987. func DecodeServerEntryList(
  988. encodedServerEntryList, timestamp,
  989. serverEntrySource string) ([]ServerEntryFields, error) {
  990. serverEntries := make([]ServerEntryFields, 0)
  991. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  992. if len(encodedServerEntry) == 0 {
  993. continue
  994. }
  995. // TODO: skip this entry and continue if can't decode?
  996. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  997. if err != nil {
  998. return nil, errors.Trace(err)
  999. }
  1000. if ValidateServerEntryFields(serverEntryFields) != nil {
  1001. // Skip this entry and continue with the next one
  1002. // TODO: invoke a logging callback
  1003. continue
  1004. }
  1005. serverEntries = append(serverEntries, serverEntryFields)
  1006. }
  1007. return serverEntries, nil
  1008. }
  1009. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  1010. // operation, loading only one server entry into memory at a time.
  1011. type StreamingServerEntryDecoder struct {
  1012. scanner *bufio.Scanner
  1013. timestamp string
  1014. serverEntrySource string
  1015. }
  1016. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  1017. func NewStreamingServerEntryDecoder(
  1018. encodedServerEntryListReader io.Reader,
  1019. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  1020. return &StreamingServerEntryDecoder{
  1021. scanner: bufio.NewScanner(encodedServerEntryListReader),
  1022. timestamp: timestamp,
  1023. serverEntrySource: serverEntrySource,
  1024. }
  1025. }
  1026. // Next reads and decodes, and validates the next server entry from the
  1027. // input stream, returning a nil server entry when the stream is complete.
  1028. //
  1029. // Limitations:
  1030. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  1031. // the default buffer size which this decoder uses. This is 64K.
  1032. // - DecodeServerEntry is called on each encoded server entry line, which
  1033. // will allocate memory to hex decode and JSON deserialze the server
  1034. // entry. As this is not presently reusing a fixed buffer, each call
  1035. // will allocate additional memory; garbage collection is necessary to
  1036. // reclaim that memory for reuse for the next server entry.
  1037. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  1038. for {
  1039. if !decoder.scanner.Scan() {
  1040. return nil, errors.Trace(decoder.scanner.Err())
  1041. }
  1042. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  1043. // TODO: skip this entry and continue if can't decode?
  1044. serverEntryFields, err := DecodeServerEntryFields(
  1045. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  1046. if err != nil {
  1047. return nil, errors.Trace(err)
  1048. }
  1049. if ValidateServerEntryFields(serverEntryFields) != nil {
  1050. // Skip this entry and continue with the next one
  1051. // TODO: invoke a logging callback
  1052. continue
  1053. }
  1054. return serverEntryFields, nil
  1055. }
  1056. }