serverEntry.go 32 KB

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