serverEntry.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 common.Contains(DisabledTunnelProtocols, tunnelProtocol) {
  491. continue
  492. }
  493. if len(limitTunnelProtocols) > 0 {
  494. if !common.Contains(limitTunnelProtocols, tunnelProtocol) {
  495. continue
  496. }
  497. } else {
  498. if common.Contains(DefaultDisabledTunnelProtocols, tunnelProtocol) {
  499. continue
  500. }
  501. }
  502. if excludeIntensive && TunnelProtocolIsResourceIntensive(tunnelProtocol) {
  503. continue
  504. }
  505. if (TunnelProtocolUsesQUIC(tunnelProtocol) && !conditionallyEnabled.QUICEnabled()) ||
  506. (TunnelProtocolUsesRefractionNetworking(tunnelProtocol) &&
  507. !conditionallyEnabled.RefractionNetworkingEnabled()) {
  508. continue
  509. }
  510. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  511. continue
  512. }
  513. // If the server is limiting QUIC versions, at least one must be
  514. // supported. And if tactics is also limiting QUIC versions, there
  515. // must be a common version in both limit lists for this server entry
  516. // to support QUIC-OSSH.
  517. //
  518. // Limitation: to avoid additional complexity, we do not consider
  519. // DisableFrontingProviderQUICVersion here, as fronting providers are
  520. // expected to support QUICv1 and gQUIC is expected to become
  521. // obsolete in general.
  522. if TunnelProtocolUsesQUIC(tunnelProtocol) && len(serverEntry.LimitQUICVersions) > 0 {
  523. if !common.ContainsAny(serverEntry.LimitQUICVersions, SupportedQUICVersions) {
  524. continue
  525. }
  526. if len(limitQUICVersions) > 0 &&
  527. !common.ContainsAny(serverEntry.LimitQUICVersions, limitQUICVersions) {
  528. continue
  529. }
  530. }
  531. dialPortNumber, err := serverEntry.GetDialPortNumber(tunnelProtocol)
  532. if err != nil {
  533. continue
  534. }
  535. if len(limitTunnelDialPortNumbers) > 0 {
  536. if portList, ok := limitTunnelDialPortNumbers[tunnelProtocol]; ok {
  537. if !portList.Lookup(dialPortNumber) {
  538. continue
  539. }
  540. } else if portList, ok := limitTunnelDialPortNumbers[TUNNEL_PROTOCOLS_ALL]; ok {
  541. if !portList.Lookup(dialPortNumber) {
  542. continue
  543. }
  544. }
  545. }
  546. supportedProtocols = append(supportedProtocols, tunnelProtocol)
  547. }
  548. return supportedProtocols
  549. }
  550. func (serverEntry *ServerEntry) GetDialPortNumber(tunnelProtocol string) (int, error) {
  551. if !serverEntry.SupportsProtocol(tunnelProtocol) {
  552. return 0, errors.TraceNew("protocol not supported")
  553. }
  554. switch tunnelProtocol {
  555. case TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  556. if serverEntry.TlsOSSHPort == 0 {
  557. // Special case: a server which supports UNFRONTED-MEEK-HTTPS-OSSH
  558. // or UNFRONTED-MEEK-SESSION-TICKET-OSSH also supports TLS-OSSH
  559. // over the same port.
  560. return serverEntry.MeekServerPort, nil
  561. }
  562. return serverEntry.TlsOSSHPort, nil
  563. case TUNNEL_PROTOCOL_SSH:
  564. return serverEntry.SshPort, nil
  565. case TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  566. return serverEntry.SshObfuscatedPort, nil
  567. case TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
  568. return serverEntry.SshObfuscatedTapDancePort, nil
  569. case TUNNEL_PROTOCOL_CONJURE_OBFUSCATED_SSH:
  570. return serverEntry.SshObfuscatedConjurePort, nil
  571. case TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  572. return serverEntry.SshObfuscatedQUICPort, nil
  573. case TUNNEL_PROTOCOL_FRONTED_MEEK,
  574. TUNNEL_PROTOCOL_FRONTED_MEEK_QUIC_OBFUSCATED_SSH:
  575. return 443, nil
  576. case TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  577. return 80, nil
  578. case TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  579. TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  580. TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  581. return serverEntry.MeekServerPort, nil
  582. }
  583. return 0, errors.TraceNew("unknown protocol")
  584. }
  585. // GetSupportedTacticsProtocols returns a list of tunnel protocols,
  586. // supported by the ServerEntry's capabilities, that may be used
  587. // for tactics requests.
  588. func (serverEntry *ServerEntry) GetSupportedTacticsProtocols() []string {
  589. supportedProtocols := make([]string, 0)
  590. for _, protocol := range SupportedTunnelProtocols {
  591. if !TunnelProtocolUsesMeek(protocol) {
  592. continue
  593. }
  594. requiredCapability := GetTacticsCapability(protocol)
  595. if !serverEntry.hasCapability(requiredCapability) {
  596. continue
  597. }
  598. supportedProtocols = append(supportedProtocols, protocol)
  599. }
  600. return supportedProtocols
  601. }
  602. // SupportsSSHAPIRequests returns true when the server supports
  603. // SSH API requests.
  604. func (serverEntry *ServerEntry) SupportsSSHAPIRequests() bool {
  605. return serverEntry.hasCapability(CAPABILITY_SSH_API_REQUESTS)
  606. }
  607. func (serverEntry *ServerEntry) GetUntunneledWebRequestPorts() []string {
  608. ports := make([]string, 0)
  609. if serverEntry.hasCapability(CAPABILITY_UNTUNNELED_WEB_API_REQUESTS) {
  610. // Server-side configuration quirk: there's a port forward from
  611. // port 443 to the web server, which we can try, except on servers
  612. // running FRONTED_MEEK, which listens on port 443.
  613. if !serverEntry.SupportsProtocol(TUNNEL_PROTOCOL_FRONTED_MEEK) {
  614. ports = append(ports, "443")
  615. }
  616. ports = append(ports, serverEntry.WebServerPort)
  617. }
  618. return ports
  619. }
  620. func (serverEntry *ServerEntry) HasSignature() bool {
  621. return serverEntry.Signature != ""
  622. }
  623. func (serverEntry *ServerEntry) GetDiagnosticID() string {
  624. return TagToDiagnosticID(serverEntry.Tag)
  625. }
  626. // GenerateServerEntryTag creates a server entry tag value that is
  627. // cryptographically derived from the IP address and web server secret in a
  628. // way that is difficult to reverse the IP address value from the tag or
  629. // compute the tag without having the web server secret, a 256-bit random
  630. // value which is unique per server, in addition to the IP address. A database
  631. // consisting only of server entry tags should be resistent to an attack that
  632. // attempts to reverse all the server IPs, even given a small IP space (IPv4),
  633. // or some subset of the web server secrets.
  634. func GenerateServerEntryTag(ipAddress, webServerSecret string) string {
  635. h := hmac.New(sha256.New, []byte(webServerSecret))
  636. h.Write([]byte(ipAddress))
  637. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  638. }
  639. // TagToDiagnosticID returns a prefix of the server entry tag that should be
  640. // sufficient to uniquely identify servers in diagnostics, while also being
  641. // more human readable than emitting the full tag. The tag is used as the base
  642. // of the diagnostic ID as it doesn't leak the server IP address in diagnostic
  643. // output.
  644. func TagToDiagnosticID(tag string) string {
  645. if len(tag) < 8 {
  646. return "<unknown>"
  647. }
  648. return tag[:8]
  649. }
  650. // EncodeServerEntry returns a string containing the encoding of
  651. // a ServerEntry following Psiphon conventions.
  652. func EncodeServerEntry(serverEntry *ServerEntry) (string, error) {
  653. encodedServerEntry, err := encodeServerEntry(
  654. serverEntry.IpAddress,
  655. serverEntry.WebServerPort,
  656. serverEntry.WebServerSecret,
  657. serverEntry.WebServerCertificate,
  658. serverEntry)
  659. if err != nil {
  660. return "", errors.Trace(err)
  661. }
  662. return encodedServerEntry, nil
  663. }
  664. // EncodeServerEntryFields returns a string containing the encoding of
  665. // ServerEntryFields following Psiphon conventions.
  666. func EncodeServerEntryFields(serverEntryFields ServerEntryFields) (string, error) {
  667. encodedServerEntry, err := encodeServerEntry(
  668. serverEntryFields.GetIPAddress(),
  669. serverEntryFields.GetWebServerPort(),
  670. serverEntryFields.GetWebServerSecret(),
  671. serverEntryFields.GetWebServerCertificate(),
  672. serverEntryFields)
  673. if err != nil {
  674. return "", errors.Trace(err)
  675. }
  676. return encodedServerEntry, nil
  677. }
  678. func encodeServerEntry(
  679. prefixIPAddress string,
  680. prefixWebServerPort string,
  681. prefixWebServerSecret string,
  682. prefixWebServerCertificate string,
  683. serverEntry interface{}) (string, error) {
  684. serverEntryJSON, err := json.Marshal(serverEntry)
  685. if err != nil {
  686. return "", errors.Trace(err)
  687. }
  688. // Legacy clients use a space-delimited fields prefix, and all clients expect
  689. // to at least parse the prefix in order to skip over it.
  690. //
  691. // When the server entry has no web API server certificate, the entire prefix
  692. // can be compacted down to single character placeholders. Clients that can
  693. // use the ssh API always prefer it over the web API and won't use the prefix
  694. // values.
  695. if len(prefixWebServerCertificate) == 0 {
  696. prefixIPAddress = "0"
  697. prefixWebServerPort = "0"
  698. prefixWebServerSecret = "0"
  699. prefixWebServerCertificate = "0"
  700. }
  701. return hex.EncodeToString([]byte(fmt.Sprintf(
  702. "%s %s %s %s %s",
  703. prefixIPAddress,
  704. prefixWebServerPort,
  705. prefixWebServerSecret,
  706. prefixWebServerCertificate,
  707. serverEntryJSON))), nil
  708. }
  709. // DecodeServerEntry extracts a server entry from the encoding
  710. // used by remote server lists and Psiphon server handshake requests.
  711. //
  712. // The resulting ServerEntry.LocalSource is populated with serverEntrySource,
  713. // which should be one of SERVER_ENTRY_SOURCE_EMBEDDED, SERVER_ENTRY_SOURCE_REMOTE,
  714. // SERVER_ENTRY_SOURCE_DISCOVERY, SERVER_ENTRY_SOURCE_TARGET,
  715. // SERVER_ENTRY_SOURCE_OBFUSCATED.
  716. // ServerEntry.LocalTimestamp is populated with the provided timestamp, which
  717. // should be a RFC 3339 formatted string. These local fields are stored with the
  718. // server entry and reported to the server as stats (a coarse granularity timestamp
  719. // is reported).
  720. func DecodeServerEntry(
  721. encodedServerEntry, timestamp, serverEntrySource string) (*ServerEntry, error) {
  722. serverEntry := new(ServerEntry)
  723. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, serverEntry)
  724. if err != nil {
  725. return nil, errors.Trace(err)
  726. }
  727. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  728. serverEntry.LocalSource = serverEntrySource
  729. serverEntry.LocalTimestamp = timestamp
  730. return serverEntry, nil
  731. }
  732. // DecodeServerEntryFields extracts an encoded server entry into a
  733. // ServerEntryFields type, much like DecodeServerEntry. Unrecognized fields
  734. // not in ServerEntry are retained in the ServerEntryFields.
  735. //
  736. // LocalSource/LocalTimestamp map entries are set only when the corresponding
  737. // inputs are non-blank.
  738. func DecodeServerEntryFields(
  739. encodedServerEntry, timestamp, serverEntrySource string) (ServerEntryFields, error) {
  740. serverEntryFields := make(ServerEntryFields)
  741. err := decodeServerEntry(encodedServerEntry, timestamp, serverEntrySource, &serverEntryFields)
  742. if err != nil {
  743. return nil, errors.Trace(err)
  744. }
  745. // NOTE: if the source JSON happens to have values in these fields, they get clobbered.
  746. if serverEntrySource != "" {
  747. serverEntryFields.SetLocalSource(serverEntrySource)
  748. }
  749. if timestamp != "" {
  750. serverEntryFields.SetLocalTimestamp(timestamp)
  751. }
  752. return serverEntryFields, nil
  753. }
  754. func decodeServerEntry(
  755. encodedServerEntry, timestamp, serverEntrySource string,
  756. target interface{}) error {
  757. hexDecodedServerEntry, err := hex.DecodeString(encodedServerEntry)
  758. if err != nil {
  759. return errors.Trace(err)
  760. }
  761. // Skip past legacy format (4 space delimited fields) and just parse the JSON config
  762. fields := bytes.SplitN(hexDecodedServerEntry, []byte(" "), 5)
  763. if len(fields) != 5 {
  764. return errors.TraceNew("invalid encoded server entry")
  765. }
  766. err = json.Unmarshal(fields[4], target)
  767. if err != nil {
  768. return errors.Trace(err)
  769. }
  770. return nil
  771. }
  772. // ValidateServerEntryFields checks for malformed server entries.
  773. func ValidateServerEntryFields(serverEntryFields ServerEntryFields) error {
  774. // Checks for a valid ipAddress. This is important since the IP
  775. // address is the key used to store/lookup the server entry.
  776. ipAddress := serverEntryFields.GetIPAddress()
  777. if net.ParseIP(ipAddress) == nil {
  778. return errors.Tracef("server entry has invalid ipAddress: %s", ipAddress)
  779. }
  780. // TODO: validate more fields?
  781. // Ensure locally initialized fields have been set.
  782. source := serverEntryFields.GetLocalSource()
  783. if !common.Contains(
  784. SupportedServerEntrySources, source) {
  785. return errors.Tracef("server entry has invalid source: %s", source)
  786. }
  787. timestamp := serverEntryFields.GetLocalTimestamp()
  788. _, err := time.Parse(time.RFC3339, timestamp)
  789. if err != nil {
  790. return errors.Tracef("server entry has invalid timestamp: %s", err)
  791. }
  792. return nil
  793. }
  794. // DecodeServerEntryList extracts server entries from the list encoding
  795. // used by remote server lists and Psiphon server handshake requests.
  796. // Each server entry is validated and invalid entries are skipped.
  797. // See DecodeServerEntry for note on serverEntrySource/timestamp.
  798. func DecodeServerEntryList(
  799. encodedServerEntryList, timestamp,
  800. serverEntrySource string) ([]ServerEntryFields, error) {
  801. serverEntries := make([]ServerEntryFields, 0)
  802. for _, encodedServerEntry := range strings.Split(encodedServerEntryList, "\n") {
  803. if len(encodedServerEntry) == 0 {
  804. continue
  805. }
  806. // TODO: skip this entry and continue if can't decode?
  807. serverEntryFields, err := DecodeServerEntryFields(encodedServerEntry, timestamp, serverEntrySource)
  808. if err != nil {
  809. return nil, errors.Trace(err)
  810. }
  811. if ValidateServerEntryFields(serverEntryFields) != nil {
  812. // Skip this entry and continue with the next one
  813. // TODO: invoke a logging callback
  814. continue
  815. }
  816. serverEntries = append(serverEntries, serverEntryFields)
  817. }
  818. return serverEntries, nil
  819. }
  820. // StreamingServerEntryDecoder performs the DecodeServerEntryList
  821. // operation, loading only one server entry into memory at a time.
  822. type StreamingServerEntryDecoder struct {
  823. scanner *bufio.Scanner
  824. timestamp string
  825. serverEntrySource string
  826. }
  827. // NewStreamingServerEntryDecoder creates a new StreamingServerEntryDecoder.
  828. func NewStreamingServerEntryDecoder(
  829. encodedServerEntryListReader io.Reader,
  830. timestamp, serverEntrySource string) *StreamingServerEntryDecoder {
  831. return &StreamingServerEntryDecoder{
  832. scanner: bufio.NewScanner(encodedServerEntryListReader),
  833. timestamp: timestamp,
  834. serverEntrySource: serverEntrySource,
  835. }
  836. }
  837. // Next reads and decodes, and validates the next server entry from the
  838. // input stream, returning a nil server entry when the stream is complete.
  839. //
  840. // Limitations:
  841. // - Each encoded server entry line cannot exceed bufio.MaxScanTokenSize,
  842. // the default buffer size which this decoder uses. This is 64K.
  843. // - DecodeServerEntry is called on each encoded server entry line, which
  844. // will allocate memory to hex decode and JSON deserialze the server
  845. // entry. As this is not presently reusing a fixed buffer, each call
  846. // will allocate additional memory; garbage collection is necessary to
  847. // reclaim that memory for reuse for the next server entry.
  848. func (decoder *StreamingServerEntryDecoder) Next() (ServerEntryFields, error) {
  849. for {
  850. if !decoder.scanner.Scan() {
  851. return nil, errors.Trace(decoder.scanner.Err())
  852. }
  853. // TODO: use scanner.Bytes which doesn't allocate, instead of scanner.Text
  854. // TODO: skip this entry and continue if can't decode?
  855. serverEntryFields, err := DecodeServerEntryFields(
  856. decoder.scanner.Text(), decoder.timestamp, decoder.serverEntrySource)
  857. if err != nil {
  858. return nil, errors.Trace(err)
  859. }
  860. if ValidateServerEntryFields(serverEntryFields) != nil {
  861. // Skip this entry and continue with the next one
  862. // TODO: invoke a logging callback
  863. continue
  864. }
  865. return serverEntryFields, nil
  866. }
  867. }