serverEntry.go 41 KB

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