serverEntry.go 33 KB

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