serverEntry.go 32 KB

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