serverEntry.go 30 KB

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