serverEntry.go 34 KB

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