serverEntry.go 33 KB

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