serverEntry.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. "strings"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. )
  38. // ServerEntry represents a Psiphon server. It contains information
  39. // about how to establish a tunnel connection to the server through
  40. // several protocols. Server entries are JSON records downloaded from
  41. // various sources.
  42. type ServerEntry struct {
  43. Tag string `json:"tag"`
  44. IpAddress string `json:"ipAddress"`
  45. WebServerPort string `json:"webServerPort"` // not an int
  46. WebServerSecret string `json:"webServerSecret"`
  47. WebServerCertificate string `json:"webServerCertificate"`
  48. SshPort int `json:"sshPort"`
  49. SshUsername string `json:"sshUsername"`
  50. SshPassword string `json:"sshPassword"`
  51. SshHostKey string `json:"sshHostKey"`
  52. SshObfuscatedPort int `json:"sshObfuscatedPort"`
  53. SshObfuscatedQUICPort int `json:"sshObfuscatedQUICPort"`
  54. LimitQUICVersions []string `json:"limitQUICVersions"`
  55. SshObfuscatedTapDancePort int `json:"sshObfuscatedTapdancePort"`
  56. SshObfuscatedConjurePort int `json:"sshObfuscatedConjurePort"`
  57. SshObfuscatedKey string `json:"sshObfuscatedKey"`
  58. Capabilities []string `json:"capabilities"`
  59. Region string `json:"region"`
  60. FrontingProviderID string `json:"frontingProviderID"`
  61. TlsOSSHPort int `json:"tlsOSSHPort"`
  62. MeekServerPort int `json:"meekServerPort"`
  63. MeekCookieEncryptionPublicKey string `json:"meekCookieEncryptionPublicKey"`
  64. MeekObfuscatedKey string `json:"meekObfuscatedKey"`
  65. MeekFrontingHost string `json:"meekFrontingHost"`
  66. MeekFrontingHosts []string `json:"meekFrontingHosts"`
  67. MeekFrontingDomain string `json:"meekFrontingDomain"`
  68. MeekFrontingAddresses []string `json:"meekFrontingAddresses"`
  69. MeekFrontingAddressesRegex string `json:"meekFrontingAddressesRegex"`
  70. MeekFrontingDisableSNI bool `json:"meekFrontingDisableSNI"`
  71. TacticsRequestPublicKey string `json:"tacticsRequestPublicKey"`
  72. TacticsRequestObfuscatedKey string `json:"tacticsRequestObfuscatedKey"`
  73. ConfigurationVersion int `json:"configurationVersion"`
  74. Signature string `json:"signature"`
  75. DisableHTTPTransforms bool `json:"disableHTTPTransforms"`
  76. DisableObfuscatedQUICTransforms bool `json:"disableObfuscatedQUICTransforms"`
  77. DisableOSSHTransforms bool `json:"disableOSSHTransforms"`
  78. DisableOSSHPrefix bool `json:"disableOSSHPrefix"`
  79. // These local fields are not expected to be present in downloaded server
  80. // entries. They are added by the client to record and report stats about
  81. // how and when server entries are obtained.
  82. // All local fields should be included the list of fields in RemoveUnsignedFields.
  83. LocalSource string `json:"localSource,omitempty"`
  84. LocalTimestamp string `json:"localTimestamp,omitempty"`
  85. IsLocalDerivedTag bool `json:"isLocalDerivedTag,omitempty"`
  86. }
  87. // ServerEntryFields is an alternate representation of ServerEntry which
  88. // enables future compatibility when unmarshaling and persisting new server
  89. // entries which may contain new, unrecognized fields not in the ServerEntry
  90. // type for a particular client version.
  91. //
  92. // When new JSON server entries with new fields are unmarshaled to ServerEntry
  93. // types, unrecognized fields are discarded. When unmarshaled to
  94. // ServerEntryFields, unrecognized fields are retained and may be persisted
  95. // and available when the client is upgraded and unmarshals to an updated
  96. // ServerEntry type.
  97. type ServerEntryFields map[string]interface{}
  98. // GetServerEntry converts a ServerEntryFields into a ServerEntry.
  99. func (fields ServerEntryFields) GetServerEntry() (*ServerEntry, error) {
  100. marshaledServerEntry, err := json.Marshal(fields)
  101. if err != nil {
  102. return nil, errors.Trace(err)
  103. }
  104. var serverEntry *ServerEntry
  105. err = json.Unmarshal(marshaledServerEntry, &serverEntry)
  106. if err != nil {
  107. return nil, errors.Trace(err)
  108. }
  109. return serverEntry, nil
  110. }
  111. func (fields ServerEntryFields) GetTag() string {
  112. tag, ok := fields["tag"]
  113. if !ok {
  114. return ""
  115. }
  116. tagStr, ok := tag.(string)
  117. if !ok {
  118. return ""
  119. }
  120. return tagStr
  121. }
  122. // SetTag sets a local, derived server entry tag. A tag is an identifier used
  123. // in server entry pruning and potentially other use cases. An explict tag,
  124. // set by the Psiphon Network, may be present in a server entry that is
  125. // imported; otherwise, the client will set a derived tag. The tag should be
  126. // generated using GenerateServerEntryTag. When SetTag finds a explicit tag,
  127. // the new, derived tag is ignored. The isLocalTag local field is set to
  128. // distinguish explict and derived tags and is used in signature verification
  129. // to determine if the tag field is part of the signature.
  130. func (fields ServerEntryFields) SetTag(tag string) {
  131. // Don't replace explicit tag
  132. if tag, ok := fields["tag"]; ok {
  133. tagStr, ok := tag.(string)
  134. if ok && tagStr != "" {
  135. isLocalDerivedTag, ok := fields["isLocalDerivedTag"]
  136. if !ok {
  137. return
  138. }
  139. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  140. if ok && !isLocalDerivedTagBool {
  141. return
  142. }
  143. }
  144. }
  145. fields["tag"] = tag
  146. // Mark this tag as local
  147. fields["isLocalDerivedTag"] = true
  148. }
  149. func (fields ServerEntryFields) GetDiagnosticID() string {
  150. tag, ok := fields["tag"]
  151. if !ok {
  152. return ""
  153. }
  154. tagStr, ok := tag.(string)
  155. if !ok {
  156. return ""
  157. }
  158. return TagToDiagnosticID(tagStr)
  159. }
  160. func (fields ServerEntryFields) GetIPAddress() string {
  161. ipAddress, ok := fields["ipAddress"]
  162. if !ok {
  163. return ""
  164. }
  165. ipAddressStr, ok := ipAddress.(string)
  166. if !ok {
  167. return ""
  168. }
  169. return ipAddressStr
  170. }
  171. func (fields ServerEntryFields) GetWebServerPort() string {
  172. webServerPort, ok := fields["webServerPort"]
  173. if !ok {
  174. return ""
  175. }
  176. webServerPortStr, ok := webServerPort.(string)
  177. if !ok {
  178. return ""
  179. }
  180. return webServerPortStr
  181. }
  182. func (fields ServerEntryFields) GetWebServerSecret() string {
  183. webServerSecret, ok := fields["webServerSecret"]
  184. if !ok {
  185. return ""
  186. }
  187. webServerSecretStr, ok := webServerSecret.(string)
  188. if !ok {
  189. return ""
  190. }
  191. return webServerSecretStr
  192. }
  193. func (fields ServerEntryFields) GetWebServerCertificate() string {
  194. webServerCertificate, ok := fields["webServerCertificate"]
  195. if !ok {
  196. return ""
  197. }
  198. webServerCertificateStr, ok := webServerCertificate.(string)
  199. if !ok {
  200. return ""
  201. }
  202. return webServerCertificateStr
  203. }
  204. func (fields ServerEntryFields) GetConfigurationVersion() int {
  205. configurationVersion, ok := fields["configurationVersion"]
  206. if !ok {
  207. return 0
  208. }
  209. configurationVersionFloat, ok := configurationVersion.(float64)
  210. if !ok {
  211. return 0
  212. }
  213. return int(configurationVersionFloat)
  214. }
  215. func (fields ServerEntryFields) GetLocalSource() string {
  216. localSource, ok := fields["localSource"]
  217. if !ok {
  218. return ""
  219. }
  220. localSourceStr, ok := localSource.(string)
  221. if !ok {
  222. return ""
  223. }
  224. return localSourceStr
  225. }
  226. func (fields ServerEntryFields) SetLocalSource(source string) {
  227. fields["localSource"] = source
  228. }
  229. func (fields ServerEntryFields) GetLocalTimestamp() string {
  230. localTimestamp, ok := fields["localTimestamp"]
  231. if !ok {
  232. return ""
  233. }
  234. localTimestampStr, ok := localTimestamp.(string)
  235. if !ok {
  236. return ""
  237. }
  238. return localTimestampStr
  239. }
  240. func (fields ServerEntryFields) SetLocalTimestamp(timestamp string) {
  241. fields["localTimestamp"] = timestamp
  242. }
  243. func (fields ServerEntryFields) HasSignature() bool {
  244. signature, ok := fields["signature"]
  245. if !ok {
  246. return false
  247. }
  248. signatureStr, ok := signature.(string)
  249. if !ok {
  250. return false
  251. }
  252. return signatureStr != ""
  253. }
  254. const signaturePublicKeyDigestSize = 8
  255. // AddSignature signs a server entry and attaches a new field containing the
  256. // signature. Any existing "signature" field will be replaced.
  257. //
  258. // The signature incudes a public key ID that is derived from a digest of the
  259. // public key value. This ID is intended for future use when multiple signing
  260. // keys may be deployed.
  261. func (fields ServerEntryFields) AddSignature(publicKey, privateKey string) error {
  262. // Make a copy so that removing unsigned fields will have no side effects
  263. copyFields := make(ServerEntryFields)
  264. for k, v := range fields {
  265. copyFields[k] = v
  266. }
  267. copyFields.RemoveUnsignedFields()
  268. delete(copyFields, "signature")
  269. // Best practise would be to sign the JSON encoded server entry bytes and
  270. // append the signature to those bytes. However, due to backwards
  271. // compatibility requirements, we must retain the outer server entry encoding
  272. // as-is and insert the signature.
  273. //
  274. // Limitation: since the verifyier must remarshal its server entry before
  275. // verifying, the JSON produced there must be a byte-for-byte match to the
  276. // JSON signed here. The precise output of the JSON encoder that is used,
  277. // "encoding/json", with default formatting, as of Go 1.11.5, is therefore
  278. // part of the signature protocol.
  279. //
  280. // TODO: use a standard, canonical encoding, such as JCS:
  281. // https://tools.ietf.org/id/draft-rundgren-json-canonicalization-scheme-05.html
  282. marshaledFields, err := json.Marshal(copyFields)
  283. if err != nil {
  284. return errors.Trace(err)
  285. }
  286. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  287. if err != nil {
  288. return errors.Trace(err)
  289. }
  290. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  291. publicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  292. decodedPrivateKey, err := base64.StdEncoding.DecodeString(privateKey)
  293. if err != nil {
  294. return errors.Trace(err)
  295. }
  296. signature := ed25519.Sign(decodedPrivateKey, marshaledFields)
  297. fields["signature"] = base64.StdEncoding.EncodeToString(
  298. append(publicKeyID, signature...))
  299. return nil
  300. }
  301. // VerifySignature verifies the signature set by AddSignature.
  302. //
  303. // VerifySignature must be called before using any server entry that is
  304. // imported from an untrusted source, such as client-to-client exchange.
  305. func (fields ServerEntryFields) VerifySignature(publicKey string) error {
  306. if publicKey == "" {
  307. return errors.TraceNew("missing public key")
  308. }
  309. // Make a copy so that removing unsigned fields will have no side effects
  310. copyFields := make(ServerEntryFields)
  311. for k, v := range fields {
  312. copyFields[k] = v
  313. }
  314. signatureField, ok := copyFields["signature"]
  315. if !ok {
  316. return errors.TraceNew("missing signature field")
  317. }
  318. signatureFieldStr, ok := signatureField.(string)
  319. if !ok {
  320. return errors.TraceNew("invalid signature field")
  321. }
  322. decodedSignatureField, err := base64.StdEncoding.DecodeString(signatureFieldStr)
  323. if err != nil {
  324. return errors.Trace(err)
  325. }
  326. if len(decodedSignatureField) < signaturePublicKeyDigestSize {
  327. return errors.TraceNew("invalid signature field length")
  328. }
  329. publicKeyID := decodedSignatureField[:signaturePublicKeyDigestSize]
  330. signature := decodedSignatureField[signaturePublicKeyDigestSize:]
  331. if len(signature) != ed25519.SignatureSize {
  332. return errors.TraceNew("invalid signature length")
  333. }
  334. decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey)
  335. if err != nil {
  336. return errors.Trace(err)
  337. }
  338. publicKeyDigest := sha256.Sum256(decodedPublicKey)
  339. expectedPublicKeyID := publicKeyDigest[:signaturePublicKeyDigestSize]
  340. if !bytes.Equal(expectedPublicKeyID, publicKeyID) {
  341. return errors.TraceNew("unexpected public key ID")
  342. }
  343. copyFields.RemoveUnsignedFields()
  344. delete(copyFields, "signature")
  345. marshaledFields, err := json.Marshal(copyFields)
  346. if err != nil {
  347. return errors.Trace(err)
  348. }
  349. if !ed25519.Verify(decodedPublicKey, marshaledFields, signature) {
  350. return errors.TraceNew("invalid signature")
  351. }
  352. return nil
  353. }
  354. // RemoveUnsignedFields prepares a server entry for signing or signature
  355. // verification by removing unsigned fields. The JSON marshalling of the
  356. // remaining fields is the data that is signed.
  357. func (fields ServerEntryFields) RemoveUnsignedFields() {
  358. delete(fields, "localSource")
  359. delete(fields, "localTimestamp")
  360. // Only non-local, explicit tags are part of the signature
  361. isLocalDerivedTag := fields["isLocalDerivedTag"]
  362. isLocalDerivedTagBool, ok := isLocalDerivedTag.(bool)
  363. if ok && isLocalDerivedTagBool {
  364. delete(fields, "tag")
  365. }
  366. delete(fields, "isLocalDerivedTag")
  367. }
  368. // NewServerEntrySignatureKeyPair creates an ed25519 key pair for use in
  369. // server entry signing and verification.
  370. func NewServerEntrySignatureKeyPair() (string, string, error) {
  371. publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
  372. if err != nil {
  373. return "", "", errors.Trace(err)
  374. }
  375. return base64.StdEncoding.EncodeToString(publicKey),
  376. base64.StdEncoding.EncodeToString(privateKey),
  377. nil
  378. }
  379. // GetCapability returns the server capability corresponding
  380. // to the tunnel protocol.
  381. func GetCapability(protocol string) string {
  382. return strings.TrimSuffix(protocol, "-OSSH")
  383. }
  384. // GetTacticsCapability returns the server tactics capability
  385. // corresponding to the tunnel protocol.
  386. func GetTacticsCapability(protocol string) string {
  387. return GetCapability(protocol) + "-TACTICS"
  388. }
  389. // hasCapability indicates if the server entry has the specified capability.
  390. //
  391. // Any internal "PASSTHROUGH-v2 or "PASSTHROUGH" componant in the server
  392. // entry's capabilities is ignored. These PASSTHROUGH components are used to
  393. // mask protocols which are running the passthrough mechanisms from older
  394. // clients which do not implement the passthrough messages. Older clients
  395. // will treat these capabilities as unknown protocols and skip them.
  396. //
  397. // Any "QUICv1" capability is treated as "QUIC". "QUICv1" is used to mask the
  398. // QUIC-OSSH capability from older clients to ensure that older clients do
  399. // not send gQUIC packets to second generation QUICv1-only QUIC-OSSH servers.
  400. // New clients must check SupportsOnlyQUICv1 before selecting a QUIC version;
  401. // for "QUICv1", this ensures that new clients also do not select gQUIC to
  402. // QUICv1-only servers.
  403. func (serverEntry *ServerEntry) hasCapability(requiredCapability string) bool {
  404. for _, capability := range serverEntry.Capabilities {
  405. originalCapability := capability
  406. capability = strings.ReplaceAll(capability, "-PASSTHROUGH-v2", "")
  407. capability = strings.ReplaceAll(capability, "-PASSTHROUGH", "")
  408. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  409. if capability == quicCapability+"v1" {
  410. capability = quicCapability
  411. }
  412. if capability == requiredCapability {
  413. return true
  414. }
  415. // Special case: some capabilities may additionally support TLS-OSSH.
  416. if requiredCapability == GetCapability(TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH) && capabilitySupportsTLSOSSH(originalCapability) {
  417. return true
  418. }
  419. }
  420. return false
  421. }
  422. // capabilitySupportsTLSOSSH returns true if and only if the given capability
  423. // supports TLS-OSSH in addition to its primary protocol.
  424. func capabilitySupportsTLSOSSH(capability string) bool {
  425. tlsCapabilities := []string{
  426. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS),
  427. GetCapability(TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET),
  428. }
  429. for _, tlsCapability := range tlsCapabilities {
  430. // The TLS capability is additionally supported by UNFRONTED-MEEK-HTTPS
  431. // and UNFRONTED-MEEK-SESSION-TICKET capabilities with passthrough.
  432. if capability == tlsCapability+"-PASSTHROUGH-v2" {
  433. return true
  434. }
  435. }
  436. return false
  437. }
  438. // SupportsProtocol returns true if and only if the ServerEntry has
  439. // the necessary capability to support the specified tunnel protocol.
  440. func (serverEntry *ServerEntry) SupportsProtocol(protocol string) bool {
  441. requiredCapability := GetCapability(protocol)
  442. return serverEntry.hasCapability(requiredCapability)
  443. }
  444. // ProtocolUsesLegacyPassthrough indicates whether the ServerEntry supports
  445. // the specified protocol using legacy passthrough messages.
  446. //
  447. // There is no corresponding check for v2 passthrough, as clients send v2
  448. // passthrough messages unconditionally, by default, for passthrough
  449. // protocols.
  450. func (serverEntry *ServerEntry) ProtocolUsesLegacyPassthrough(protocol string) bool {
  451. legacyCapability := GetCapability(protocol) + "-PASSTHROUGH"
  452. for _, capability := range serverEntry.Capabilities {
  453. if capability == legacyCapability {
  454. return true
  455. }
  456. }
  457. return false
  458. }
  459. // SupportsOnlyQUICv1 indicates that the QUIC-OSSH server supports only QUICv1
  460. // and gQUIC versions should not be selected, as they will fail to connect
  461. // while sending atypical traffic to the server.
  462. func (serverEntry *ServerEntry) SupportsOnlyQUICv1() bool {
  463. quicCapability := GetCapability(TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH)
  464. return common.Contains(serverEntry.Capabilities, quicCapability+"v1") &&
  465. !common.Contains(serverEntry.Capabilities, quicCapability)
  466. }
  467. // ConditionallyEnabledComponents defines an interface which can be queried to
  468. // determine which conditionally compiled protocol components are present.
  469. type ConditionallyEnabledComponents interface {
  470. QUICEnabled() bool
  471. RefractionNetworkingEnabled() bool
  472. }
  473. // TunnelProtocolPortLists is a map from tunnel protocol names (or "All") to a
  474. // list of port number ranges.
  475. type TunnelProtocolPortLists map[string]*common.PortList
  476. // GetSupportedProtocols returns a list of tunnel protocols supported by the
  477. // ServerEntry's capabilities and allowed by various constraints.
  478. func (serverEntry *ServerEntry) GetSupportedProtocols(
  479. conditionallyEnabled ConditionallyEnabledComponents,
  480. useUpstreamProxy bool,
  481. limitTunnelProtocols TunnelProtocols,
  482. limitTunnelDialPortNumbers TunnelProtocolPortLists,
  483. limitQUICVersions QUICVersions,
  484. excludeIntensive bool) TunnelProtocols {
  485. supportedProtocols := make(TunnelProtocols, 0)
  486. for _, tunnelProtocol := range SupportedTunnelProtocols {
  487. if useUpstreamProxy && !TunnelProtocolSupportsUpstreamProxy(tunnelProtocol) {
  488. continue
  489. }
  490. if len(limitTunnelProtocols) > 0 {
  491. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  492. continue
  493. }
  494. } else {
  495. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  496. continue
  497. }
  498. }
  499. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  500. continue
  501. }
  502. if (TunnelProtocolUsesQUIC(tunnelProtocol) && !conditionallyEnabled.QUICEnabled()) ||
  503. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  504. !conditionallyEnabled.RefractionNetworkingEnabled()) {
  505. continue
  506. }
  507. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  508. continue
  509. }
  510. // If the server is limiting QUIC versions, at least one must be
  511. // supported. And if tactics is also limiting QUIC versions, there
  512. // must be a common version in both limit lists for this server entry
  513. // to support QUIC-OSSH.
  514. //
  515. // Limitation: to avoid additional complexity, we do not consider
  516. // DisableFrontingProviderQUICVersion here, as fronting providers are
  517. // expected to support QUICv1 and gQUIC is expected to become
  518. // obsolete in general.
  519. if TunnelProtocolUsesQUIC(tunnelProtocol) && len(serverEntry.LimitQUICVersions) > 0 {
  520. if !common.ContainsAny(serverEntry.LimitQUICVersions, SupportedQUICVersions) {
  521. continue
  522. }
  523. if len(limitQUICVersions) > 0 &&
  524. !common.ContainsAny(serverEntry.LimitQUICVersions, limitQUICVersions) {
  525. continue
  526. }
  527. }
  528. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  529. if err != nil {
  530. continue
  531. }
  532. if len(limitTunnelDialPortNumbers) > 0 {
  533. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  534. if !portList.Lookup(dialPortNumber) {
  535. continue
  536. }
  537. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  538. if !portList.Lookup(dialPortNumber) {
  539. continue
  540. }
  541. }
  542. }
  543. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  544. }
  545. return supportedProtocols
  546. }
  547. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  548. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  549. return 0, errors.TraceNew("protocol not supported")
  550. }
  551. switch tunnelProtocol {
  552. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  553. if serverEntry.TlsOSSHPort == 0 {
  554. // Special case: a server which supports UNFRONTED-MEEK-HTTPS-OSSH
  555. // or UNFRONTED-MEEK-SESSION-TICKET-OSSH also supports TLS-OSSH
  556. // over the same port.
  557. return serverEntry.MeekServerPort, nil
  558. }
  559. return serverEntry.TlsOSSHPort, nil
  560. case TUNNEL_PROTOCOL_SSH:
  561. return serverEntry.SshPort, nil
  562. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  563. return serverEntry.SshObfuscatedPort, nil
  564. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  565. return serverEntry.SshObfuscatedTapDancePort, nil
  566. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  567. return serverEntry.SshObfuscatedConjurePort, nil
  568. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  569. return serverEntry.SshObfuscatedQUICPort, nil
  570. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  571. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  572. return 443, nil
  573. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  574. return 80, nil
  575. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  576. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  577. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  578. return serverEntry.MeekServerPort, nil
  579. }
  580. return 0, errors.TraceNew("unknown protocol")
  581. }
  582. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  583. // supported by the ServerEntry's capabilities, that may be used
  584. // for tactics requests.
  585. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  586. supportedProtocols := make([]string, 0)
  587. for _, protocol := range SupportedTunnelProtocols {
  588. if !TunnelProtocolUsesMeek(protocol) {
  589. continue
  590. }
  591. requiredCapability := GetTacticsCapability(protocol)
  592. if !serverEntry.hasCapability(requiredCapability) {
  593. continue
  594. }
  595. supportedProtocols = append(supportedProtocols, protocol)
  596. }
  597. return supportedProtocols
  598. }
  599. // SupportsSSHAPIRequests returns true when the server supports
  600. // SSH API requests.
  601. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  602. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  603. }
  604. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  605. ports := make([]string, 0)
  606. if serverEntry.hasCapability(CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  607. // Server-side configuration quirk: there's a port forward from
  608. // port 443 to the web server, which we can try, except on servers
  609. // running FRONTED_MEEK, which listens on port 443.
  610. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  611. ports = append(ports, "443")
  612. }
  613. ports = append(ports, serverEntry.WebServerPort)
  614. }
  615. return ports
  616. }
  617. func (serverEntry *ServerEntry) HasSignature() bool {
  618. return serverEntry.Signature != ""
  619. }
  620. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  621. return TagToDiagnosticID(serverEntry.Tag)
  622. }
  623. // GenerateServerEntryTag creates a server entry tag value that is
  624. // cryptographically derived from the IP address and web server secret in a
  625. // way that is difficult to reverse the IP address value from the tag or
  626. // compute the tag without having the web server secret, a 256-bit random
  627. // value which is unique per server, in addition to the IP address. A database
  628. // consisting only of server entry tags should be resistent to an attack that
  629. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  630. // or some subset of the web server secrets.
  631. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  632. h := hmac.New(sha256.New, []byte(webServerSecret))
  633. h.Write([]byte(ipAddress))
  634. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  635. }
  636. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  637. // sufficient to uniquely identify servers in diagnostics, while also being
  638. // more human readable than emitting the full tag. The tag is used as the base
  639. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  640. // output.
  641. func TagToDiagnosticID(tag string) string {
  642. if len(tag) < 8 {
  643. return "<unknown>"
  644. }
  645. return tag[:8]
  646. }
  647. // EncodeServerEntry returns a string containing the encoding of
  648. // a ServerEntry following Psiphon conventions.
  649. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  650. encodedServerEntry, err := encodeServerEntry(
  651. serverEntry.IpAddress,
  652. serverEntry.WebServerPort,
  653. serverEntry.WebServerSecret,
  654. serverEntry.WebServerCertificate,
  655. serverEntry)
  656. if err != nil {
  657. return "", errors.Trace(err)
  658. }
  659. return encodedServerEntry, nil
  660. }
  661. // EncodeServerEntryFields returns a string containing the encoding of
  662. // ServerEntryFields following Psiphon conventions.
  663. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  664. encodedServerEntry, err := encodeServerEntry(
  665. serverEntryFields.GetIPAddress(),
  666. serverEntryFields.GetWebServerPort(),
  667. serverEntryFields.GetWebServerSecret(),
  668. serverEntryFields.GetWebServerCertificate(),
  669. serverEntryFields)
  670. if err != nil {
  671. return "", errors.Trace(err)
  672. }
  673. return encodedServerEntry, nil
  674. }
  675. func encodeServerEntry(
  676. prefixIPAddress string,
  677. prefixWebServerPort string,
  678. prefixWebServerSecret string,
  679. prefixWebServerCertificate string,
  680. serverEntry interface{}) (string, error) {
  681. serverEntryJSON, err := json.Marshal(serverEntry)
  682. if err != nil {
  683. return "", errors.Trace(err)
  684. }
  685. // Legacy clients use a space-delimited fields prefix, and all clients expect
  686. // to at least parse the prefix in order to skip over it.
  687. //
  688. // When the server entry has no web API server certificate, the entire prefix
  689. // can be compacted down to single character placeholders. Clients that can
  690. // use the ssh API always prefer it over the web API and won't use the prefix
  691. // values.
  692. if len(prefixWebServerCertificate) == 0 {
  693. prefixIPAddress = "0"
  694. prefixWebServerPort = "0"
  695. prefixWebServerSecret = "0"
  696. prefixWebServerCertificate = "0"
  697. }
  698. return hex.EncodeToString([]byte(fmt.Sprintf(
  699. "%s %s %s %s %s",
  700. prefixIPAddress,
  701. prefixWebServerPort,
  702. prefixWebServerSecret,
  703. prefixWebServerCertificate,
  704. serverEntryJSON))), nil
  705. }
  706. // DecodeServerEntry extracts a server entry from the encoding
  707. // used by remote server lists and Psiphon server handshake requests.
  708. //
  709. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  710. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  711. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  712. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  713. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  714. // should be a RFC 3339 formatted string. These local fields are stored with the
  715. // server entry and reported to the server as stats (a coarse granularity timestamp
  716. // is reported).
  717. func DecodeServerEntry(
  718. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  719. serverEntry := new(ServerEntry)
  720. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  721. if err != nil {
  722. return nil, errors.Trace(err)
  723. }
  724. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  725. serverEntry.LocalSource = serverEntrySource
  726. serverEntry.LocalTimestamp = timestamp
  727. return serverEntry, nil
  728. }
  729. // DecodeServerEntryFields extracts an encoded server entry into a
  730. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  731. // not in ServerEntry are retained in the ServerEntryFields.
  732. //
  733. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  734. // inputs are non-blank.
  735. func DecodeServerEntryFields(
  736. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  737. serverEntryFields := make(ServerEntryFields)
  738. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  739. if err != nil {
  740. return nil, errors.Trace(err)
  741. }
  742. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  743. if serverEntrySource != "" {
  744. serverEntryFields.SetLocalSource(serverEntrySource)
  745. }
  746. if timestamp != "" {
  747. serverEntryFields.SetLocalTimestamp(timestamp)
  748. }
  749. return serverEntryFields, nil
  750. }
  751. func decodeServerEntry(
  752. encodedServerEntry, timestamp, serverEntrySource string,
  753. target interface{}) error {
  754. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  755. if err != nil {
  756. return errors.Trace(err)
  757. }
  758. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  759. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  760. if len(fields) != 5 {
  761. return errors.TraceNew("invalid encoded server entry")
  762. }
  763. err = json.Unmarshal(fields[4], target)
  764. if err != nil {
  765. return errors.Trace(err)
  766. }
  767. return nil
  768. }
  769. // ValidateServerEntryFields checks for malformed server entries.
  770. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  771. // Checks for a valid ipAddress. This is important since the IP
  772. // address is the key used to store/lookup the server entry.
  773. ipAddress := serverEntryFields.GetIPAddress()
  774. if net.ParseIP(ipAddress) == nil {
  775. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  776. }
  777. // TODO: validate more fields?
  778. // Ensure locally initialized fields have been set.
  779. source := serverEntryFields.GetLocalSource()
  780. if !common.Contains(
  781. SupportedServerEntrySources, source) {
  782. return errors.Tracef("server entry has invalid source: %s", source)
  783. }
  784. timestamp := serverEntryFields.GetLocalTimestamp()
  785. _, err := time.Parse(time.RFC3339, timestamp)
  786. if err != nil {
  787. return errors.Tracef("server entry has invalid timestamp: %s", err)
  788. }
  789. return nil
  790. }
  791. // DecodeServerEntryList extracts server entries from the list encoding
  792. // used by remote server lists and Psiphon server handshake requests.
  793. // Each server entry is validated and invalid entries are skipped.
  794. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  795. func DecodeServerEntryList(
  796. encodedServerEntryList, timestamp,
  797. serverEntrySource string) ([]ServerEntryFields, error) {
  798. serverEntries := make([]ServerEntryFields, 0)
  799. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  800. if len(encodedServerEntry) == 0 {
  801. continue
  802. }
  803. // TODO: skip this entry and continue if can't decode?
  804. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  805. if err != nil {
  806. return nil, errors.Trace(err)
  807. }
  808. if ValidateServerEntryFields(serverEntryFields) != nil {
  809. // Skip this entry and continue with the next one
  810. // TODO: invoke a logging callback
  811. continue
  812. }
  813. serverEntries = append(serverEntries, serverEntryFields)
  814. }
  815. return serverEntries, nil
  816. }
  817. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  818. // operation, loading only one server entry into memory at a time.
  819. type StreamingServerEntryDecoder struct {
  820. scanner *bufio.Scanner
  821. timestamp string
  822. serverEntrySource string
  823. }
  824. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  825. func NewStreamingServerEntryDecoder(
  826. encodedServerEntryListReader io.Reader,
  827. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  828. return &StreamingServerEntryDecoder{
  829. scanner: bufio.NewScanner(encodedServerEntryListReader),
  830. timestamp: timestamp,
  831. serverEntrySource: serverEntrySource,
  832. }
  833. }
  834. // Next reads and decodes, and validates the next server entry from the
  835. // input stream, returning a nil server entry when the stream is complete.
  836. //
  837. // Limitations:
  838. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  839. // the default buffer size which this decoder uses. This is 64K.
  840. // - DecodeServerEntry is called on each encoded server entry line, which
  841. // will allocate memory to hex decode and JSON deserialze the server
  842. // entry. As this is not presently reusing a fixed buffer, each call
  843. // will allocate additional memory; garbage collection is necessary to
  844. // reclaim that memory for reuse for the next server entry.
  845. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  846. for {
  847. if !decoder.scanner.Scan() {
  848. return nil, errors.Trace(decoder.scanner.Err())
  849. }
  850. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  851. // TODO: skip this entry and continue if can't decode?
  852. serverEntryFields, err := DecodeServerEntryFields(
  853. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  854. if err != nil {
  855. return nil, errors.Trace(err)
  856. }
  857. if ValidateServerEntryFields(serverEntryFields) != nil {
  858. // Skip this entry and continue with the next one
  859. // TODO: invoke a logging callback
  860. continue
  861. }
  862. return serverEntryFields, nil
  863. }
  864. }